开发者

adding extra field to django-registration using signals

开发者 https://www.devze.com 2023-01-16 21:06 出处:网络
I want to add a locale selection to the default django-registration. I tried to follow this tutorial from dmitko. The form shows up correctly but the additional data (locale) is not saved.

I want to add a locale selection to the default django-registration. I tried to follow this tutorial from dmitko. The form shows up correctly but the additional data (locale) is not saved.

I defined a custom model:

class AnymalsProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    locale = models.CharField(max_length=2)

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

and the form:

from models import AnymalsProfile
from registration.forms import RegistrationFormTermsOfService

class UserRegistrationForm(RegistrationFormTermsOfService):
    locale = forms.CharField(max_length=3, widget=forms.Select(choices=LOCALE_CHOICES),label='Language:')

The fields show up correctly, but the locale data (profile) is not saved. I assume that the regbackend.py is my problem:

from anysite.models import AnymalsProfile

def user_created(sender, user, request, **kwargs):
        form = UserRegistrationForm(request.POST)
        data = AnymalsProfile(user=user)
        data.locale = form.cleaned_data["locale"]
        data.save()

from registration.signals import user_registered
user_registered.connect(user_created)

* EDIT * I tried moving into production - just for a test - and it raised some errors. I altered the code, but still the profile is not sa开发者_如何学Cved. Here is what I tried:

from anysite.models import AnymalsProfile
from anysite.forms import UserRegistrationForm

def user_created(sender, user, request, **kwargs):
        form = UserRegistrationForm(request.POST)
        if form.is_valid():
                ProfileData = form.cleaned_data
                profile = AnymalsProfile(
                user = user.id,
                locale = ProfileData["locale"]
                        )
                profile.save()

from registration.signals import user_registered
user_registered.connect(user_created)


Do you have somewhere in your code import regbackend. That should be done in order to the following strings being executed.

from registration.signals import user_registered
user_registered.connect(user_created)

I my example I have import regbackend in urls.py. Do you have this line as well?


I don't know why, but it didn't like cleaned_data. It now works using the following:

def user_created(sender, user, request, **kwargs):
        form = UserRegistrationForm(request.POST)
        data = AnymalsProfile(user=user)
        data.locale = form.data["locale"]
        data.save()

Thanks @dmitko for the code and the support. keep it up!

0

精彩评论

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