简体   繁体   中英

Issue with custom user registration in django

I am using python and django to develop an web application where I have built a CustomUser model extending the user model and also built a sign up form. But problem is that each time I am registering a new user when I go back to login page and enter the user name and password, it keeps giving the message "Username and Password does not match".

I am pasting the codes here:

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)

voting/urls.py: (Here voting is my application name)

 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 }
)

Can anyone please suggest me the mistake that I am doing here? Thanks in advance.

您覆盖用户模型,但在backend.py中进行了更改,这用于检查用户何时尝试登录此文件,我认为django从用户模型中检查了用户名和密码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM