Search code examples
pythondjangomodels

Connect to User Model in Django


Quick (probably foolish) question. This is the flow of my site: User logs in and is redirected to a custom admin page. On this admin page they have the ability to make a 'Profile'. I want to associate the Profile they create with their User data such that 1 User associates to 1 Profile.

For some reason the following isn't working (simply trying to associate

UserAdmin.Models

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

class Profile(models.Model):
    username = models.ForeignKey(User)
    firstname = models.CharField(max_length=200)
    lastname = models.CharField(max_length=200)
    email = models.EmailField(max_length=200)

    def __unicode__(self):
        return self.username

UserAdmin.Views

def createprofile(request):

    user = User.objects.get(id=1)
    profile = Profile(username=user, firstname='Joe', lastname='Soe', email='Joe@Soe.com')
    profile.save()

I keep getting: table useradmin_profile has no column named username_id

Any ideas? Appreciated.

EDIT:

Deleted my db and ran a fresh syncdb, changed to username = models.OneToOneField(User). Now I cam getting Cannot assign "u'superuser'": "Profile.username" must be a "User" instance.


Solution

  • UserAdmin.Models

    from django.db import models
    from django.contrib.auth.models import User
    
    class Profile(models.Model):
        user = models.OneToOneField(User)
    
        def __unicode__(self):
            return self.user.get_full_name()
    

    UserAdmin.Views

    def createprofile(request):
    
        user_ = User.objects.get(pk=1)
        profile = Profile(user=user_)
        profile.user.first_name = 'Joe'
        profile.user.last_name = 'Soe'
        profile.user.email = 'Joe@Soe.com'
        profile.user.save()
        profile.save()