2016-03-02 101 views
0

我正在使用python和django開發一個Web應用程序,其中我構建了一個CustomUser模型,用於擴展用戶模型並構建註冊表單。但問題是,當我回到登錄頁面並輸入用戶名和密碼時,每當我註冊一個新用戶時,它都會一直給出消息「用戶名和密碼不匹配」。django中的自定義用戶註冊問題

我在這裏粘貼代碼:

forms.py

 import re 
     from django.utils.translation import ugettext_lazy as _ 
     from django import forms 
     from django.contrib.auth.models import User 
     from django.contrib.auth.forms import UserCreationForm, UserChangeForm 
     from models import CustomUser 
     import pdb 

     class RegistrationForm(UserCreationForm): 
     """A form for creating new users. Includes all the required 
fields, plus a repeated password.""" 

     first_name = forms.RegexField(regex=r'^\w+$',  widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("First name"), error_messages={ 'invalid': _("This value must contain only letters") }) 
     last_name = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Last name"), error_messages={ 'invalid': _("This value must contain only letters") }) 
     password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password")) 
     password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)")) 
     date_of_birth = forms.DateField(widget=forms.TextInput(attrs= {'class':'datepicker'})) 
     sex = forms.ChoiceField(choices=(('M', 'MALE'), ('F', 'FEMALE')), label=_("Sex")) 
     voter_id = forms.CharField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Voter Id")) 
     is_election_staff = forms.BooleanField(initial=False, required=False) 

class Meta: 
    model = CustomUser 
    fields = ['first_name', 'last_name', 'voter_id', 'date_of_birth', 'sex', 'is_election_staff'] 


def clean_username(self): 
    try: 
     user = User.objects.get(voter_id__iexact=self.cleaned_data['voter_id']) 
    except User.DoesNotExist: 
     return self.cleaned_data['voter_id'] 
    raise forms.ValidationError(_("The user with given voter id already exists. Please try another one.")) 



def clean(self): 
    if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data: 
     if self.cleaned_data['password1'] != self.cleaned_data['password2']: 
      raise forms.ValidationError(_("The two password fields did not match.")) 
    return self.cleaned_data 


def save(self, commit=True): 
    # Save the provided password in hashed format 
    user = super(RegistrationForm, self).save(commit=False) 
    user.first_name = self.cleaned_data['first_name'] 
    user.last_name = self.cleaned_data['last_name'] 
    user.date_of_birth = self.cleaned_data['date_of_birth'] 
    user.sex = self.cleaned_data['sex'] 
    user.voter_id = self.cleaned_data['voter_id'] 
    user.is_election_staff = self.cleaned_data['is_election_staff'] 
    user.username = user.voter_id 
    user.set_password(self.cleaned_data['password1']) 

    if commit: 
     user.save() 
    return user 

models.py

from __future__ import unicode_literals 

    from django.db import models 
    from django.contrib.auth.models import (
AbstractBaseUser) 

class Party(models.Model): 
    name = models.CharField(max_length=200) 
    num_seats_won = models.IntegerField(default=0) 

SEX = (('M', 'MALE'), ('F', 'FEMALE')) 

class CustomUser(AbstractBaseUser): 
    first_name = models.CharField(max_length=30) 
    last_name = models.CharField(max_length=30) 
    date_of_birth = models.DateField() 
    sex = models.CharField(choices=SEX, max_length=10) 
    is_election_staff = models.BooleanField(default=True) 
    voter_id = models.CharField(max_length=40, unique=True) 

USERNAME_FIELD = 'voter_id' 

def __str__(self): 
    return "%s %s" % (self.first_name, self.last_name) 

表決/ urls.py:(這裏的投票是我的應用程序的名稱)

urlpatterns = [ 
# url(r'^$', views.index, name='index'), 
url(r'^$', 'django.contrib.auth.views.login'), 
url(r'^logout/$', logout_page), 
url(r'^register/$', register), 
url(r'^register/success/$', register_success), 
url(r'^home/$', home), 

]

views.py

from .forms import * 
from django.contrib.auth.decorators import login_required 
from django.contrib.auth import logout 
from django.views.decorators.csrf import csrf_protect 
from django.shortcuts import render_to_response 
from django.http import HttpResponseRedirect 
from django.template import RequestContext 
import pdb 

@csrf_protect 
def register(request): 
if request.method == 'POST': 
    form = RegistrationForm(request.POST) 
    if form.is_valid(): 
     print "In register request = "+ str(request.POST) 
     form.save() 
     return HttpResponseRedirect('/voting/register/success/') 
else: 
    form = RegistrationForm() 
variables = RequestContext(request, { 
'form': form 
}) 
return render_to_response(
'registration/register.html', 
variables, 
) 

def register_success(request): 
print "In success request = "+ str(request) 
return render_to_response(
'registration/success.html', 
) 

def logout_page(request): 
logout(request) 
return HttpResponseRedirect('/voting/') 

@login_required 
def home(request): 
return render_to_response(
'home.html', 
{ 'user': request.user } 
) 

任何人都可以請建議我說,我在這裏做什麼錯誤?提前致謝。

+0

你的意思是顯示'「兩個密碼字段不匹配。」'錯誤?只是嘗試打印出'self.cleaned_data ['password1']'和'self.cleaned_data ['password2']' –

+0

'的值。當我要登錄用戶的頁面時輸入用戶名和密碼,然後輸入消息即將到來「用戶名和密碼不匹配」 – Joy

+0

不,我沒有集成任何管理員。 – Joy

回答

0

Your Override the user model but but has change in backend.py which is used to check when when try to login in this file i think django checking username and password from user model。

+0

你是否建議添加backend.py來處理認證後端? – Joy

+0

登錄使用此功能的嘗試: USER_OBJ = CustomUser.objects.get(voter_id =用戶名) 不同的是: 回報無 用戶認證=(用戶名= user_obj.voter_id,密碼=密碼) 如果用戶: 回報用戶 返回無 –