22

我创建了一个注册应用程序,用户可以在其中注册提供用户名、电子邮件和密码。我所做的是确保电子邮件字段是唯一的(如您在下面的代码中所见)。但我不知道如何在用户输入已在使用的电子邮件地址时显示错误。

看法

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf

from forms import RegistrationForm

# Create your views here.
def register_user(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('../../membership/register_success')
        else:
            return HttpResponseRedirect('../../membership/register_failed')

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

    args['form'] = RegistrationForm()

    return render(request,'registration/registration_form.html', args)

def register_success(request):
    return render_to_response('registration/registration_success.html')

def register_failed(request):
    return render_to_response('registration/registration_failed.html')

形式

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _

    # forms.py
    class RegistrationForm(UserCreationForm):
        email = forms.EmailField(required=True)

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

        def clean_email(self):
            email = self.cleaned_data.get('email')
            username = self.cleaned_data.get('username')

            if email and User.objects.filter(email=email).exclude(username=username).count():
                raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
            return email

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

注册.html

    {% extends "base.html" %}
    {% block title %}Registration{% endblock %}

    {% block content %}

            <h1>Registration</h1>

            {% if form.errors %}
            <h1>ERRORRRRRR same email again???</h1>
            {% endif %}

            {% if registered %}
            <strong>thank you for registering!</strong>
            <a href="../../">Return to the homepage.</a><br />
            {% else %}
            <strong>register here!</strong><br />

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

    {% endblock %}
4

4 回答 4

21

您正在{{ form }}模板上显示表单。默认情况下,它本身应该显示所有验证错误,但在您的情况下,如果表单无效,您将重定向到其他页面。因此,除非您使用 GET 参数传递错误,否则您永远无法显示错误。您可以将视图更改为此以获取注册页面本身的错误 -

def register_user(request):
    args = {}
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('../../membership/register_success')
    else:
        form = RegistrationForm()
    args['form'] = form

    return render(request,'registration/registration_form.html', args)

它的工作原理是,如果请求方法是 POST,则使用 POST 数据启动表单,然后通过is_valid()调用对其进行验证,因此如果表单对象无效,则表单对象现在具有验证错误消息。如果有效,则保存并重定向。如果无效,则涉及将args['form'] = form带有错误消息的表单对象设置为上下文然后传递给渲染的部分。

如果请求方法不是 POST,则实例化一个没有数据的表单对象并传递给render().

现在,如果有任何错误,您的模板应该在每个字段下方显示所有错误消息。

于 2014-03-19T17:44:04.307 回答
12

表格.py

from django import forms

class RegistForm(forms.Form):

    name = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True)

视图.py

from django.shortcuts import render
from django.views.generic import TemplateView
import forms

class Register(TemplateView):

    def get(self, request):
        return render(request, 'register.html', {})

    def post(self, request):
        form = forms.RegistForm(request.POST)
        if form.is_valid():
            print(1)
        else:
            print(form.errors)
        content = {'form':form};
        return render(request, 'register.html', content)

注册.html

    <form action="{% url 'register' %}" method="post">

        {% csrf_token %}

        <fieldset>
          <label for="name">Name:</label>
          <input type="text" id="name" name="name" value="">
          {{ form.errors.name }}

          <label for="mail">Email:</label>
          <input type="text" id="mail" name="email">
          {{ form.errors.email }}

          <label for="password">Password:</label>
          <input type="password" id="password" name="password">
          {{ form.errors.password }}
        </fieldset>

        <button type="submit">Sign Up</button>

        <p class="message">Already registered? <a href="{% url 'login' %}">Login</a></p>

    </form>

**随意复制代码并享受!**

于 2016-06-11T19:56:49.817 回答
6

为什么不这样做:

...
if User.objects.filter(email=email):
    raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return email
...

如果用户已经注册,让它引发验证错误。如果您不希望它这样做,您可以执行以下操作:

...
email_exists = User.objects.filter(email=email):
if email_exists and email_exists.username != username:
    raise forms.ValidationError(_("This email address is already in use. Please supply a different email address."))
return email
...

要显示表单错误,请使用form.is_valid()以确保它通过验证。Django 对自定义验证说以下内容:

Note that any errors raised by your Form.clean() override will not be associated with any field in particular. They go into a special “field” (called __all__), which you can access via the non_field_errors() method if you need to. If you want to attach errors to a specific field in the form, you need to call add_error().

然后在你的模板中你可以使用类似的东西{{ form.non_field_errors }},等等。

请参阅 Django 文档中的此部分,位于Using a form in a viewCustomizing the form template
https ://docs.djangoproject.com/en/dev/topics/forms/

于 2014-03-18T04:55:23.247 回答
0

基于类的视图更容易。

from django.views import generic
from .forms import RegistrationForm

class RegistrationView(generic.CreateView):
    template_class = 'registration/registration_form.html'
    form_class = RegistrationForm
    success_url = '/success/url'

    def form_valid(self, form):
        # add a log after save or whatever
        super(RegistrationView, self).form_valid(self, form)

干净的方法是自动的,表单和消息这样呈现,基于类的视图让生活更轻松,你的代码更干燥。

于 2015-04-07T20:53:34.900 回答