注册不起作用

时间:2016-02-18 20:47:47

标签: python django

您好我创建了RegistrationForm,查看等 - 我想我需要给用户注册的一切。但是当我在注册网站上时,我填写表格并点击"注册"该网站刷新,没有任何反应,我得到同样的空白表格。有什么问题?我的django版本是1.9.1。

from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class MyregistrationForm(UserCreationForm):
        email = forms.EmailField(required=True)

    def __init__(self, *args, **kwargs):
        super(MyregistrationForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')

    def save(self, commit=True):
        user = super(MyregistrationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

视图:

from .forms import *
from django.contrib import auth
from django.core.context_processors import csrf
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render, render_to_response


    def register(request):
        if request.method == 'POST':
            form = MyregistrationForm(request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect('congratulations')

        args = {}
        args.update(csrf(request))

        args['form'] = MyregistrationForm()
        return render_to_response('page/register.html', args)

    def congratulations(request):
        return render_to_response('page/congratulations.html')

urls.py

url(r'^register/$', views.register, name='register'),
url(r'^congratulations/$', views.congratulations, name='congratulations')

注册模板:

<form action="/register/" method="post">{%csrf_token %}
            {{form}}
            <input type="submit" value="Register" />
        </form>

1 个答案:

答案 0 :(得分:1)

当表单无效时,您当前正在为POST请求创建新表单。这意味着您没有看到表单错误。

相反,您可以将MyregistrationForm()移动到else语句中,以便它仅针对GET请求运行。为此,您需要稍微重新排列视图。我已经从render_to_response切换到render,以便更轻松。

def register(request):
    if request.method == 'POST':
        form = MyregistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('congratulations')
    else:
        form = MyregistrationForm()
    return render(request, 'page/register.html', {'form': form})

使用新视图,您应该会在模板中看到表单错误。这将为您提供表格无效的线索。