开发者

Django User Authentication

开发者 https://www.devze.com 2023-03-01 06:11 出处:网络
I am trying to set up user authentication for my django project but I keep getting a database error UserProfile_User does not exist. I have tried most of the examples online but none have solved the i

I am trying to set up user authentication for my django project but I keep getting a database error UserProfile_User does not exist. I have tried most of the examples online but none have solved the issue. Below is the code I'm currently trying out. Any relevant pointers would be greatly appreciated. user profile model that I'm currently trying out.

    from datetime import datetime
    from 开发者_如何学编程django.db import models
    from django.contrib.auth.models import User


    class UserProfile(models.Model):
        user = models.OneToOneField(User)    
        dob = models.DateField(default=datetime.today().year - 18)

        def __unicode__(self):
            return ('%s' % (self.user.username))


Using a OneToOneField is fine in this case but that doesn't mean that the profile will be created for you. It's fairly simple to have the profile created by a signal:

from django.contrib.auth.models import User
from django.db.models.signals import post_save

def user_post_save(sender, instance, created, **kwargs):
    # Creates user profile
    if created:
        profile, new = UserProfile.objects.get_or_create(user=instance)

post_save.connect(user_post_save, sender=User)

This would be included in your models.py just below the UserProfile definition and will ensure that all of your users have a profile associated with them.


I never use OneToOneField, but my guess is, that its is requiring a bidirectional existence of both (user and its profile). If one of both does not exist it will raise an Exception. Maybe you are better of with a ForeignKey.

0

精彩评论

暂无评论...
验证码 换一张
取 消