私は初心者で、Django プロジェクトを開発しています。独自の電子メール ベースの認証モデルを作成しようとしています。私はいくつかの作業を行い、django admin プラットフォームを介してスーパーユーザーとユーザーを作成し、ログイン フォーム ビューを介してログインすることに成功しましたが、ユーザー登録フォームを介してユーザーを作成できません。「有効なメール アドレスを入力してください」のようなエラーが表示されます.' 「名前」のフィールド(CharField)。私のコード:
models.py
from __future__ import unicode_literals
from ca_portal import settings
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser, BaseUserManager, PermissionsMixin)
from django.db.models.signals import post_save
from django.contrib.auth.models import UserManager
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
class CampusAmbassadorManager(BaseUserManager):
def _create_user(self, email,name,college,password, is_staff,
is_superuser, **extra_fields):
now = timezone.now()
if not email:
raise ValueError('Campus Ambassadors must have an email address')
email = self.normalize_email(email)
user = self.model(email = email,
name = name,
college = college,
is_staff = is_staff,
is_superuser = is_superuser,
last_login = now,
date_joined = now,
**extra_fields)
user.set_password(password)
user.save(using = self._db)
return user
def create_user(self, email, name, college, password=None, **extra_fields):
user = self._create_user(email, name, college, password, False, False, **extra_fields)
return user
def create_superuser(self, email, name, college, password, **extra_fields):
user = self._create_user(email, name, college, password, True, True, **extra_fields)
return user
class CampusAmbassador(AbstractBaseUser,PermissionsMixin):
"""My own custom user class"""
email = models.EmailField(_('email address'),max_length=255,
unique=True, db_index=True)
name = models.CharField(_('name'),max_length = 100)
college = models.CharField(_('college name'),max_length = 140)
date_joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = CampusAmbassadorManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('Campus Ambassador')
verbose_name_plural = _('Campus Ambassdors')
# abstract = True
def get_full_name(self):
"""Return the email."""
return self.email
def get_short_name(self):
"""Return the email."""
return self.email
def email_user(self, subject, message, from_email=None):
send_mail(subject, message, from_email,[self.email])
#sends an email to this user.
backends.py :
from django.conf import settings
#from django.contrib.auth.models import *
from django.contrib.auth.hashers import check_password #important to note that is resides in hashers
from .models import CampusAmbassador
class EmailAuthBackend(object):
def authenticate(self, email=None, password=None):
"""
authentication method, check the email/password and return user.
"""
try:
user = CampusAmbassador.objects.get(email = email)
if user.check_password(password):
return user
except CampusAmbassador.DoesNotExist:
return None
def get_user(self, user_id):
try:
user = CampusAmbassador.objects.get(pk = user_id)
if user.is_active:
return user
return None
except CampusAmbassador.DoesNotExist:
return None
フォーム.py:
from django import forms
from .models import CampusAmbassador
#http://blackglasses.me/2013/09/17/custom-django-user-model/
# Form for registring a new CampusAmbassador
class RegistrationForm(forms.ModelForm):
email = forms.EmailField(widget=forms.TextInput(attrs=
{'class': 'form-control','type':'text','name': 'email'}), label="Email")
name = forms.EmailField(widget=forms.TextInput(attrs=
{'class': 'form-control','type':'text','name': 'name'}), label="Name")
college = forms.EmailField(widget=forms.TextInput(attrs=
{'class': 'form-control','type':'text','name': 'college'}), label="College")
password1 = forms.CharField(widget=forms.PasswordInput(attrs=
{'class':'form-control','type':'password', 'name': 'password1'}),label="Password")
password2 = forms.CharField(widget=forms.PasswordInput(attrs=
{'class':'form-control','type':'password', 'name': 'password2'}),label="Password (again)")
class Meta:
model = CampusAmbassador
fields = ['email','name','password1','password2']
field_order = ['name','college','email','password1','password2']
# def __init__(self, *args, **kwargs):
# super(RegistrationForm,self).__init__(*args, **kwargs)
# self.fields['email'].required = True
#
def clean(self):
"""
Verifies that the values entered into the password fields match
NOTE : errors here will appear in 'non_field_errors()'
"""
cleaned_data = super(RegistrationForm, self).clean()
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError("Passwords don't match. Please try again!")
return self.cleaned_data
def save(self, commit=True):
user = super(RegistrationForm,self).save(commit=False)
user.set_password(self.cleaned_data['password1'])
if commit:
user.save()
return user
#The save(commit=False) tells Django to save the new record, but dont commit it to the database yet
class AuthenticationForm(forms.Form): #forms.Form Not forms.ModelForm
email = forms.EmailField(widget=forms.TextInput(attrs=
{'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}), label="Email")
password = forms.CharField(widget=forms.PasswordInput(attrs=
{'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}),label="Password")
class Meta:
fields = ['email', 'password']
views.py :
# encoding=utf8
from django.shortcuts import render_to_response, redirect, render, HttpResponse
from django.template import RequestContext
from django.contrib.auth import login as django_login, logout as django_logout, authenticate as django_authenticate
from django.contrib.auth.decorators import login_required
from .forms import AuthenticationForm, RegistrationForm
def login(request):
if request.method == 'POST':
form = AuthenticationForm(data = request.POST)
if form.is_valid():
email = request.POST['email']
password = request.POST['password']
user = django_authenticate(email=email, password=password)
if user is not None:
if user.is_active:
django_login(request,user)
return redirect('/dashboard')
else:
form = AuthenticationForm()
return render_to_response('own/index.html',{'form':form,}, context_instance = RequestContext(request))
def register(request):
if request.method == 'POST':
form = RegistrationForm(data = request.POST)
if form.is_valid():
user = form.save()
# messages.success(request, "Thank you for signing up")
return redirect('/dashboard')
else:
form = RegistrationForm()
return render_to_response('own/signup.html',{'form':form,}, context_instance=RequestContext(request))
def logout(request):
django_logout(request)
return redirect('/')
@login_required(login_url ="/")
def dashboard(request):
return render(request, 'own/dashboard.html',{})
admin.py :
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from ca.models import CampusAmbassador
from django.contrib.auth.models import Group
class CampusAmbassadorAdmin(BaseUserAdmin):
list_display = ('email','name','college','is_staff')
list_filter = ('is_staff',)
fieldsets = (
(None,{'fields':('email','password')}),
('Personal info',{'fields':('name','college')}),
('Permissions',{'fields':('is_staff',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'name','college', 'password1', 'password2')}
),
)
search_fields =('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(CampusAmbassador, CampusAmbassadorAdmin)
admin.site.unregister(Group)
エラー :
注:「名前」を電子メールIDとして入力すると機能しますが、大学のフィールドでわかるように機能しません。
助けてください。