Django-registration - 如何从子类Form传递“extra_context”参数

时间:2012-11-17 13:07:52

标签: django django-registration

我正在使用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”参数添加到“register”视图来更改“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”参数。如何引用变量“性别”,“国家”和“城市”?

提前致谢。

1 个答案:

答案 0 :(得分: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