0

我正在使用 Django 注册(https://bitbucket.org/ubernostrum/django-registration/),我需要在用户注册中添加一些字段。

我已经创建了RegistrationForm 的子类。我的“forms.py”如下:

from django.contrib.auth.models import User
from myproject.apps.userprofile.models import Gender, UserProfile
from myproject.apps.location.models import Country, City
from django import forms
from registration.forms import RegistrationForm
from registration.models import RegistrationManager


class RegistrationFormExtend(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which adds the fiedls in the userprofile app
    """   
    gender              = forms.ModelChoiceField(queryset=Gender.objects.all(), empty_label="(Nothing)")
    country             = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="(Nothing)")
    city                = forms.ModelChoiceField(queryset=City.objects.all(), empty_label="(Nothing)")
    #profile_picture     = 

为了使它工作,我通过将“form_class”参数添加到“注册”视图来更改“urls.py”以显示“RegistrationFormExtend”表单:

from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template

from registration.views import activate
from registration.views import register

from myproject.apps.registrationextend.forms import RegistrationFormExtend


urlpatterns = patterns('',
               ...
                   url(r'^registar/$',
                       register,
                       {'backend': 'registration.backends.default.DefaultBackend', 'form_class': RegistrationFormExtend,},
                       name='registration_register'),
                   ...
                   )

在那之后,我已经测试并且表格正在工作。用户注册成功,但“RegistrationFormExtend”中的所有额外字段(性别、国家、城市)均未存储在数据库中。

阅读文档http://docs.b-list.org/django-registration/0.8/views.html#registration.views.register似乎我必须将参数“extra_context”传递给视图。

我的问题是如何将字典传递给“extra_context”参数。如何引用变量“性别”、“国家”和“城市”?

提前致谢。

4

1 回答 1

0

您忘记了save扩展注册表中的方法。你必须做这样的事情:

class RegistrationFormExtend(RegistrationForm):
    """
    Subclass of ``RegistrationForm`` which adds the fiedls in the userprofile app
    """   
    gender = forms.ModelChoiceField(queryset=Gender.objects.all(), empty_label="(Nothing)")
    country = forms.ModelChoiceField(queryset=Country.objects.all(), empty_label="(Nothing)")
    city = forms.ModelChoiceField(queryset=City.objects.all(), empty_label="(Nothing)")
    #profile_picture

    def __init__(self, *args, **kw):
       super(RegistrationFormExtend, self).__init__(*args, **kw)

    def save(self):
        #first save the parent form
        profile = super(RegistrationFormExtend, self).save()
        #then save the custom fields
        #i am assuming that the parent form return a profile
        profile.gender = self.cleaned_data['gender']
        profile.country = self.cleaned_data['country']
        profile.city = self.cleaned_data['city']
        profile.save()
        return profile
于 2012-11-17T19:00:44.783 回答