I am a newbie of django. I want to make a ForeignKey to the auth_user table.
I try to do that:
user = models.ForeignKey(auth_user)
It cause the error:
NameError: name 'auth_user' is not defined
So, can somebody tell me how to import auth_user.
Since foreign keys accept strings, you can use the AUTH_USER_MODEL setting in your foreign key.
from django.conf import settings
class MyModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
This works whether you are using the built in User model, or a custom model.
Presumably you are talking about django.contrib.auth.models.User then do
from django.contrib.auth.models import User
class MyModel(models.model):
user = models.ForeignKey(User)
If you are talking about a custom User model that comes from elsewhere, replace the import with the relevent import for that class.
Related
My Blog model has a User field like following:
from django.contrib.auth.models import User
class Blog:
author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog', default=User('monty'))
This works as in I can see 'monty' set as a default user in the admin interface when I create a blog post. However, when I make migrations, I get the following error:
ValueError: Cannot serialize: <User: >
There are some values Django cannot serialize into migration files.
I also tried this:
default=User.objects.filter(username='monty'))
and that returns a slightly different error when I make migrations:
ValueError: Cannot serialize: <User: monty>
There are some values Django cannot serialize into migration files.
Does anyone know how to get past this error?
You can make a callable that determines the User object, so:
from django.conf import settings
from django.contrib.auth import get_user_model
def get_monty():
if get_monty.user:
return user
user, __ = get_user_model().get_or_create(username='monty')
get_monty.user = user
return user
get_monty.user = None
class Blog(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='blog',
default=get_monty
)
That being said, I think it makes no sense to specify a default here. Your views can determine the logged in user and set that as the author. By using a default you likely will eventually end up with some Posts for which the view did not implement the logic, and are thus all assigned to monty, it
thus will silence an error that probably should not be silenced.
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
I want to create a model with a ManyToOne relationship with the user database.
Here's the code I used for the field:
from django.db import models
from django.contrib.auth.models import User
class user_extended(models.Model):
user_ID = models.ManyToOneRel(User)
The migration doesn't work. It returns TypeError:
TypeError: init() missing 1 required positional argument: 'field_name'
How should I create a relationship with user database?
We define ManyToOne relationships on Django with a ForeingKey. So you should change
user_ID = models.ManyToOneRel(User)
to
user_ID = models.ForeignKey(User, on_delete=models.CASCADE)
Check out Django's documentation: https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/
If you want to have a ManytoOne relation (many user_extended to one User), you'd do it like this:
from django.db import models
from django.conf import settings
class user_extended(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Note: the class name should be CamelCase, like this: UserExtended
I need to use the intermediate model between user and group in another model like this:
Class SomeModel(models.Model):
usergroup = models.ForeignKey(UserGroupIntermediate, on_delete=models.DO_NOTHINH)
That is possible?
Thanks!
EDIT!:
My model looks like this, i'm using a custom user model:
from django.db import models
from django.contrib.auth import get_user_model
from model_utils.models import TimeStampedModel
class Enrollment(TimeStampedModel):
usergroups = models.ForeignKey(
get_user_model().groups.through,
but, this return an error when execute makemigrations
enrollments.Enrollment.usergroups: (fields.E300) Field defines a relation with model 'User_groups', which is either not installed, or is abstract.
You can refer to the model via the through attribute of the field.
usergroup = models.ForeignKey(User.groups.through, ...)
When I need to use the current user in a model.
lets say I have a model with a current_user field, something like:
class MyModel(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,default=None)
my understanding is User can be fetched either:
1)by importing the current user:
from django.contrib.auth.models import User
or
2) setting User to:
from django.contrib.auth import get_user_model
User = get_user_model()
I understand both will work if I am not wrong!!
So What is the main difference between those two methods if there is any?
Thanks
If you are using the default User model, both approaches will work.
However if you are using a custom user model (or are writing a reusable app), then you should use get_user_model() to ensure you get the correct model.
Note that the docs suggest you use settings.AUTH_USER_MODEL in foreign keys.
class MyModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default=None)
I'm trying to create a custom user class and I'd like to know the best practice for implementing referencing the new user. After following the Django docs method of implementing the custom user as follows in models.py:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
pass
And settings.py
AUTH_USER_MODEL = 'myapp.MyUser'
And admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User
admin.site.register(User, UserAdmin)
The Django docs say to use settings.AUTH_USER_MODEL in place of user specifically for ForeignKeys and OnetoOneField, but it's not clear about other instances.
My question is specific to how to refer to the custom user class in views.py. Before defining the user class I was using
from django.contrib.auth.models import User
But after defining a custom class this is no longer correct. I've seen boilerplate code use this method in the beginning of views.py:
from django.contrib.auth import get_user_model
User = get_user_model()
Is this the best practice for referencing the custom user? Or should I just be using settings.AUTH_USER_MODEL in place of where I previously had User?
Using settings.AUTH_USER_MODEL will load the user class lazily after all django apps are loaded. Calling get_user_model() on a module level when your app is initially loaded may result in that the user model app is not loaded and also circular imports.
Update: I read two specific questions:
How to correctly access the user model, contrib or custom.
Djangos get_user_model() is quite simply a call to django.apps get_model() using the settings.AUTH_USER_MODEL. If you are writing apps that might be reused in other projects with other user models, use the get_user_model call. Always. Then it doesn't matter what the user model is.
If you have created your own core.User model and is very confident that your code will only be used in this project, from core.models import User works as well.
When to use the string representation from settings instead of fetching the model.
The string representation will in the end usually call the same django.apps get_model() anyway. By giving a string instead of the class itself in Foreignkeys, OneToOneFields etc you simply don't require the model to be looked up during django app imports, where the user model may not yet be available. So using string representation is simply deferred loading of a model. The same goes for all models.
An also during djangos different major versions this behavior have changed, which is another topic. Notice that get_user_model() have been updated in Django 1.11 for import usage.
https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#referencing-the-user-model
you can go with get_user_model instead User
from django.contrib.auth import get_user_model
User = get_user_model()
get_user_model will Returns the User model that is active in this project.
if you modify(adding new field into it) default User table you need to use get_user_model it will return active User table.
BTW User will return native from django.contrib.auth.models