form.is_valid未验证

时间:2016-12-09 02:37:02

标签: python django django-forms django-views

我正在尝试在主页上进行注册(注册框出现在onclick上),所以我没有单独的URL来处理注册。我正在尝试通过get_context_data发送表单,但它不起作用。这是我的代码:

forms.py

class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    class Meta:
        model = User

        fields = [
            'username',
            'password',
            'confirm_password',
        ]

views.py

class BoxesView(ListView):
    template_name = 'polls.html'

    def get_context_data(self):
        context = super(BoxesView, self).get_context_data()

    # login
    form = UserRegistrationForm(self.request.POST or None)
    context['form'] = form
    if form.is_valid(): 
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user = User.objects.create_user(username, password)
        user.save()
        return redirect('/')

    return context

        return context

    def get_queryset(self):
        pass

base.html文件

<form action="" enctype="multipart/form-data" method="post">{% csrf_token %}
    <div class="registerBox">
        {{ form.username }}
        {{ form.password }}
        <input type="submit" value="register"/>
    </div>
</form>

字段显示但在提交表单后,它不会创建用户,因为我的form.is_valid为False。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您不应该从get_context_data()返回回复。相反,在post()方法中执行此操作:

class BoxesView(ListView):
    template_name = 'polls.html'

    def post(self, request, *args, **kwargs):
        form = UserRegistrationForm(request.POST)

        if form.is_valid(): 
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = User.objects.create_user(username, password=password)
            return redirect('/')
        else:
            return self.get(request, *args, **kwargs)

    def get_context_data(self):
        context = super(BoxesView, self).get_context_data()
        context['form'] = UserRegistrationForm()
        return context

答案 1 :(得分:0)

看起来您的表单希望提交confirm_password,但这不是您的HTML表单的一部分。