Reputation: 2075
I tried following the example at https://docs.djangoproject.com/en/1.9/topics/auth/customizing/#extending-the-existing-user-model on how to extend the user model. But I cannot retrieve the model data which I attached to the User.
model
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
ip = models.IntegerField(default=0)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
getting my User object
user = auth.authenticate(username=username, password=password)
g = user.UserProfile.ip
print(g)
The user gets fetched properly, and I'm able to get all the data that are with the standard user. But user.UserProfile will result in:
Internal Server Error: /Crowd/login/
Traceback (most recent call last):
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Anaconda3\Lib\site-packages\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Rasmus\workspace\Crowd\src\Cr\views.py", line 35, in login
g = user.UserProfile.ip
AttributeError: 'User' object has no attribute 'UserProfile'
[05/Sep/2016 04:32:46] "POST /Crowd/login/ HTTP/1.1" 500 69185
I checked my database and I can see that there's a row in UserProfile which has a relation with User. So UserProfile is getting created properly(I assume).
Upvotes: 5
Views: 12295
Reputation: 967
use models.OneToOneField(User,related_name='userprofile')
and add AUTH_PROFILE_MODULE = 'app.UserProfile'
in your UserProfile
Class
Upvotes: 0
Reputation: 17003
You should access the user profile of user
with user.userprofile
, not user.UserProfile
. Try looking through the docs for one-to-one relationships. It should make things much clearer as to how Django expects you to use such relationships.
Note also, that from the UserProfile
side, you can access User
with .user
not .User
. You will see that this is naming convention is always used with relationships in Django. Similarly, by default your tables in your database will be named something like myapp_userprofile
rather than myapp_UserProfile
.
Upvotes: 6