扩展django中的表单?

时间:2012-03-03 08:08:59

标签: python django django-registration

我最近尝试使用以下内容扩展django的注册表单,但我只能看到默认的四个字段。有什么我想念的吗?

或者,如果我要创建自定义表单,我应该创建自己的注册后端吗?

class RegistrationForm(forms.Form):

    username = forms.RegexField(regex=r'^\w+$',
                                max_length=30,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=_(u'Username'))
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
                                                               maxlength=75)),
                             label=_(u'Email address'))
    first_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'First Name')) 
    last_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'Last Name'))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=_(u'Password'))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict, render_value=False),
                                label=_(u'Password (again)'))
    keywords = forms.ModelMultipleChoiceField(queryset=Keyword.objects.all())
    #keywords = forms.ModelChoiceField(queryset=Keyword.objects.all())

    def clean_username(self):
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_(u'This username is already taken. Please choose another.'))

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_(u'You must type the same password each time'))
        return self.cleaned_data

    def save(self, profile_callback=None):
        new_user = RegistrationProfile.objects.create_inactive_user(username=self.cleaned_data['username'],password=self.cleaned_data['password1'],email=self.cleaned_data['email'],profile_callback=profile_callback)
    new_profile = UserProfile(user=new_user,username=self.cleaned_data['username'], keywords_subscribed=self.cleaned_data['keywords'],first_name=self.cleaned_data['first_name'],last_name=self.cleaned_data['last_name'],email=self.cleaned_data['email'])
    new_profile.save()       
        return new_user

添加了模板代码:

添加模板代码以供参考。

它引用了注册模块中的forms.py

<html>
    <body>
        <div id="popupLayer_login" style="visibility: visible; position: fixed;">
            <div id="content-home" style="width: 700px; margin-left: -300px; top: 60px; position: fixed;">
                <br />
                {% block title %}<h2 style="margin: 0px; margin-bottom: 20px; text-align: center">Register for an account</h2>{% endblock %}
                {% block content %}
                <table style="margin-left: 100px; width: 500px;">
                    <tbody>
                        <form method='post' action=''>
                            {% csrf_token %}
                            {{ form }}
                            <tr>
                                <td style="border-width: 0px;"></td>
                                <td style="border-width: 0px;">
                                <input type="submit" value="Send activation email" />
                                </td>
                            </tr>
                        </form>
                    </tbody>
                </table>
                {% endblock %}
            </div>
        </div>
    </body>
</html>

这是我的urls.py

urlpatterns = patterns('',
                       # Activation keys get matched by \w+ instead of the more specific
                       # [a-fA-F0-9]{40} because a bad activation key should still get to the view;
                       # that way it can return a sensible "invalid key" message instead of a
                       # confusing 404.
                       url(r'^activate/(?P<activation_key>\w+)/$',
                           activate,
                           name='registration_activate'),
                       url(r'^login/$',
                           auth_views.login,
                           {'template_name': 'registration/login.html'},
                           name='auth_login'),
                       url(r'^logout/$',
                           auth_views.logout,
                           {'template_name': 'registration/logout.html'},
                           name='auth_logout'),
                       url(r'^password/change/$',
                           auth_views.password_change,
                           name='auth_password_change'),
                       url(r'^password/change/done/$',
                           auth_views.password_change_done,
                           name='auth_password_change_done'),
                       url(r'^password/reset/$',
                           auth_views.password_reset,
                           name='auth_password_reset'),
                       url(r'^password/reset/confirm/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$',
                           auth_views.password_reset_confirm,
                           name='auth_password_reset_confirm'),
                       url(r'^password/reset/complete/$',
                           auth_views.password_reset_complete,
                           name='auth_password_reset_complete'),
                       url(r'^password/reset/done/$',
                           auth_views.password_reset_done,
                           name='auth_password_reset_done'),
                       url(r'^register/$',
                           register,
                           name='registration_register'),
                       url(r'^register/complete/$',
                           direct_to_template,
                           {'template': 'registration/registration_complete.html'},
                           name='registration_complete'),
                       )

和我的views.py

def register(request, success_url=None,
             form_class=RegistrationForm, profile_callback=None,
             template_name='registration/registration_form.html',
             extra_context=None):
    if request.method == 'POST':
        form = form_class(data=request.POST, files=request.FILES)
        if form.is_valid():
            new_user = form.save(profile_callback=profile_callback)
            # success_url needs to be dynamically generated here; setting a
            # a default value using reverse() will cause circular-import
            # problems with the default URLConf for this application, which
            # imports this file.
            return HttpResponseRedirect(success_url or reverse('registration_complete'))
    else:
        form = form_class()

    if extra_context is None:
        extra_context = {}
    context = RequestContext(request)
    for key, value in extra_context.items():
        context[key] = callable(value) and value() or value
    return render_to_response(template_name,
                              { 'form': form },
                              context_instance=context)

1 个答案:

答案 0 :(得分:7)

实际上,你不应该修改外部应用程序的代码,除非你有充分的理由 - 显然这种情况并非如此。因为它被称为fork并需要更多维护:它们会进行更新,您必须反映更新。

您应该始终尝试重用外部应用而不触及其代码。在这种情况下,完全可以在不触及其代码的情况下扩展注册表单。也就是说,它需要一点伏都教。请注意,这适用于任何理智的应用程序:

  1. 检查视图签名中的form_class参数,相关视图具有以下签名:request(request, success_url=None, form_class=RegistrationForm, profile_callback=None, template_name='registration/registration_form.html', extra_context=None)。这非常酷,这意味着您可以使用不同的成功URL,配置文件回调,模板,额外的上下文重用视图,最重要的是在您的情况下:form_class。

  2. 对表单进行子类化,创建另一个继承自RegistrationForm的表单

  3. 覆盖网址以传递表单类,创建另一个传递表单类的网址

  4. 在项目目录中创建forms.py:

    from django import forms
    
    from registration.forms import RegistrationForm
    
    class ProjectSpecificRegistrationForm(RegistrationForm):
        keywords = forms.ModelMultipleChoiceField(queryset=Keyword.objects.all())
        first_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'First Name')) 
        last_name =forms.CharField(widget=forms.TextInput(attrs=attrs_dict),label=_(u'Last Name'))
    

    然后,在你的 urls.py中,你应该有:

    urlpatterns = patterns('',
        url(r'registration/', include('registration.urls'),
    )
    

    使用绝对路径/registration/register/ url覆盖名为“registration_register”的网址:

    import forms
    
    urlpatterns = patterns('',
        url(r'^registration/register/$', 'views.registration.register', {
            'form_class': forms.ProjectSpecificRegistrationForm}, 'registration_register'),
        url(r'^registration/', include('registration.urls'),
    )
    

    这里发生了什么

    url() function有这样的签名:url(regex, view, kwargs=None, name=None, prefix='')。在上面的定义中,我们将带有form_class的dict传递给kwargs。因此,将使用form_class =您的表单类调用该视图。这真的很有趣,因为你还可以添加额外的上下文,如:

        url(r'^registration/register/$', 'views.registration.register', {
            'form_class': forms.ProjectSpecificRegistrationForm,
            # provided that you imported SomeModel
            'extra_context':  {'models': SomeModel.objects.all()}}, 'registration_register'),
    

    无论如何,下次打开/registration/register/时,它会使用您的网址,该网址会传递您的表单类。

    请注意,您还可以创建一个类似 project_specific 的应用,您可以在其中放置所有特定于您的项目的代码,并且无需重复使用。