Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: import auth user to the model

In Django I created a new model:

from django.db import models from django.contrib.auth import user  class Workers(models.Model):     user = models.OneToOneField(User, primary_key=True)         work_group = models.CharField(max_length=20)         card_num = models.IntegerField()     def __unicode__(self):             return self.user 

But it doesn't work: ImportError: cannot import name user

How to fix it?

I want to create a new table "workers" in db, which has a OneToOne relationship with table "auth_user".

like image 470
Lev Avatar asked Oct 16 '12 19:10

Lev


People also ask

How do I import Auth user model?

In order to keep your code generic, use the get_user_model() method to retrieve the user model and the AUTH_USER_MODEL setting to refer to it when defining model's relations to the user model, instead of referring to the auth user model directly.

How do I get Auth user model in Django?

Method 3 – get_user_model() : The other way to reference the user model is via get_user_model which returns the currently active user model: either a custom user model specificed in AUTH_USER_MODEL or else the default built-in User. Inside the models.py add the following code: Python3.

How do I reference a user model in Django?

Referencing the User model Instead of referring to User directly, you should reference the user model using django. contrib. auth. get_user_model() .


2 Answers

from django.contrib.auth.models import User 

You missed the models - and user is capitalized.

If you use a custom user model you should use:

from django.contrib.auth import get_user_model User = get_user_model() 

More details can be found in the docs.

Changed in Django 1.11:

The ability to call get_user_model() at import time was added.

like image 66
Thomas Schwärzl Avatar answered Sep 28 '22 10:09

Thomas Schwärzl


If you're using a custom User model, do the following to reference it:

from django.contrib.auth import get_user_model User = get_user_model() 

Or if using it in foreign key or many-to-many relations:

from django.conf import settings .... user = models.ForeignKey(settings.AUTH_USER_MODEL) 

docs

like image 44
Cianan Sims Avatar answered Sep 28 '22 12:09

Cianan Sims