Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving a extended user profile

I need save additional information about users when they register. I used this: https://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users , but I stuck. Relation are created, but the field key is empty.

models.py

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, unique=True)
    key = models.CharField(max_length=20, null=True, blank=True)

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

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)

post_save.connect(create_user_profile, sender=User)

views.py

def registration(request):
    form = RegistrationForm(request.POST or None)
    if form.is_valid():
        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        email = form.cleaned_data['email']
        password = form.cleaned_data['password']
        user = User.objects.create_user(login, email, password)
        user.first_name = first_name
        user.last_name = last_name
        user.is_active = False
        # I've tried both ways, but it not write anything in to the table
        # user.key = ''.join(random.choice(string.digits) for i in range(12))
        # user.get_profile().key = ''.join(random.choice(string.digits) for i in range(12))

        user.save()

Thanks.

like image 749
vlad Avatar asked Dec 21 '22 02:12

vlad


1 Answers

profile = user.get_profile()
profile.key = ''.join(random.choice(string.digits) for i in range(12))
profile.save()
user.save()

This is the correct way to do it. You have to save the instance of the profile object as well as the user object

like image 126
Timmy O'Mahony Avatar answered Jan 03 '23 14:01

Timmy O'Mahony