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='[email protected]')
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.
Referencing the User model Instead of referring to User directly, you should reference the user model using django.contrib.auth.get_user_model() . This method will return the currently active user model – the custom user model if one is specified, or User otherwise.
Join can be done with select_related method: Django defines this function as Returns a QuerySet that will “follow” foreign-key relationships, selecting additional related-object data when it executes its query.
from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid ...
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 = '[email protected]'
profile.user.save()
profile.save()
You syncdb'ed the Profile model before you had a username
ForeignKey field. Django will only create tables but will not alter them once they have been created. Here an answer listing your options:
https://stackoverflow.com/a/7693297/990224.
And you should think about renaming username
to user
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With