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