Adding data to related model (custom user model) - python
I have a custom User Model. I can successfully add user to it and want to add the relationship to a related model. It gives me no errors but does not link the user to the related field compusers in the company model. Basically I need it to after creating a user, also add the user to the related compusers field.
This is the code I am trying in the view:
self.object.compusers.add(self.object.id)
The Model
class Company(models.Model):
user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='compusers')
name = models.CharField(max_length=265, blank=True)
tel = models.IntegerField(blank=True, null=True)
email = models.EmailField(max_length=265,blank=True)
address = models.TextField(blank=True)
postal = models.TextField(blank=True)
regno = models.CharField(max_length=265,blank=True)
vatno = models.CharField(max_length=265,blank=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('nodisoapp:home')
The View
class AddStaffView(CreateView):
form_class = forms.AddStaffMember
success_url = reverse_lazy('nodisoapp:home')
template_name = "scrty/addstaff.html"
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.password = get_random_string(length=8)
self.object.save()
self.object.compusers.add(self.object.id)
return super(AddStaffView, self).form_valid(form)
The form
Class AddStaffMember(forms.ModelForm):
usrtype = forms.ChoiceField(choices=[('Admin','Admin'),('Manager','Manager'),('Employee','Employee')],label="User Type: See below for descriptions" )
class Meta:
model = get_user_model()
fields = ("firstname","lastname","email","usrtype")
labels = {
"firstname": _("First Name"),
"lastname": _("Last Name"),
"email": _("E-mail"),
}
I recently went through this same process. It's not finalized, but it should help. With this project, I create a user, and that user (customer) has obvious attributes that are required (e.g. first name, last name, phone, email, company, and site). There was a lot of problems in just simply trying to extend the django User model and add relationships that work well, so I went with having my own user model. This model retains the use of Username. I can provide projects that uses email instead of username. This project also uses some styling widgets on the login form. I have other projects that style other parts of auth as well.
main/models.py
from django.contrib.auth.models import (
AbstractBaseUser,
PermissionsMixin,
BaseUserManager,
)
from django.core.mail import send_mail
from django.db import models
from django.utils.translation import ugettext_lazy as _
from customers import models as customers_models
class TravelModel(models.Model):
mileageRate = models.DecimalField(max_digits=4, decimal_places=3)
def __str__(self):
return '%s' % (self.mileageRate)
class Meta:
verbose_name = "Current Federal Milage Rate"
#verbose_name_plural = "Milage"
class UserManager(BaseUserManager):
def create_user(self, username, email, firstName, lastName, company, phone, password=None, **kwargs):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
username = userName,
email=self.normalize_email(email),
firstName = firstName,
lastName = lastName,
company = company,
phone = phone
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email, firstName, lastName, password=None, **kwargs):
user = self.model(
username = username,
email = self.normalize_email(email),
firstName = firstName,
lastName = lastName,
)
user.set_password(password)
user.is_superuser = True
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser, PermissionsMixin):
username = models.CharField(_('Username'), max_length=150, unique=True, null=False, blank=False)
email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
firstName = models.CharField(_('First Name'),max_length=50, blank=False, null=False)
lastName = models.CharField(_('Last Name'),max_length=50, blank=False, null=False)
company = models.ForeignKey(customers_models.CompanyModel, on_delete=models.PROTECT, null=False)
phone = models.ForeignKey(customers_models.PhoneModel, on_delete=models.PROTECT, null=False)
is_admin = models.BooleanField(
_('staff status'),
default=False,
help_text=_(
'Designates whether the user can log into this admin '
'site.'
)
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'
)
)
objects = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','firstName', 'lastName']
class Meta(object):
ordering = ['firstName']
verbose_name = _('Contact')
verbose_name_plural = _('Contacts')
def __str__(self):
return '%s - %s %s - %s - %s' % (self.company, self.firstName, self.lastName, self.email, self.phone)
def get_full_name(self):
return self.email
def get_short_name(self):
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
def email_user(self, subject, message, from_email=None, **kwargs):
send_mail(subject, message, from_email, [self.email], **kwargs)
#property
def is_staff(self):
return self.is_admin
main/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib import messages
from django.contrib.auth import logout, login, authenticate, update_session_auth_hash
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.forms import PasswordChangeForm
from django.core.mail import send_mail
from .models import MyUser
from .forms import RegistrationForm, LoginForm, ResetPasswordForm
def IndexView(request):
return render(request, 'main/index.html')
def ContactView(request):
return render(request, 'main/contact.html')
def LoginView(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
return redirect('home')
else:
form = LoginForm()
args={ 'form': form }
return render(request, 'main/login.html', args)
def LogoutView(request):
logout(request)
#login_required
def PasswordChangeView(request):
if request.method == 'POST':
form = PasswordChangeForm(request.user, request.POST)
if form.is_valid():
user = form.save()
update_session_auth_hash(request, form.user) # Important!
messages.success(request, 'Your password was successfully updated!')
return redirect('change_password_done')
else:
messages.error(request, 'Please correct the error below.')
else:
form = PasswordChangeForm(request.user)
return render(request, 'main/change_password_form.html', {
'form': form
})
#permission_required(['auth.add_customuser', 'auth.change_customuser'], raise_exception=True)
def RegisterView(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('main')
else:
form = RegistrationForm()
args = {'form': form}
return render(request, 'main/register.html', args)
main/urls.py
from django.conf.urls import url, include
from django.urls import reverse_lazy
from .views import IndexView, RegisterView, ContactView, PasswordChangeView
from .forms import LoginForm
from django.contrib.auth.views import (
LogoutView,
login,
PasswordChangeView,
PasswordChangeDoneView,
PasswordResetView,
PasswordResetDoneView,
PasswordResetConfirmView,
PasswordResetCompleteView,
)
# main app URLS extend from the base url i.e. www.website.com/*
urlpatterns = [
url(r'^$', IndexView, name='main'),
url(r'^register/$', RegisterView, name='register'),
url(r'^contact/$', ContactView, name='contact'),
url(r'^logout/$', LogoutView.as_view(next_page=reverse_lazy('main')),
name='logout'
),
url(r'^service/', include('service.urls')),
url(r'^consultation/', include('consultation.urls')),
# successful logins are redirected to the settings.LOGIN_REDIRECT_URL
url(r'^login/$', login, name='login', kwargs={'template_name':'main/login.html', 'authentication_form':LoginForm},
),
url(r'^change_password/$',
PasswordChangeView.as_view(
template_name='main/change_password_form.html'
),
name='password_change'),
url(r'^change_password/done/$',
PasswordChangeDoneView.as_view(
template_name='main/change_password_done.html'
),
name='password_change_done'),
url(r'^password_reset/$',
PasswordResetView.as_view(template_name='main/reset_password_form.html'),
name='password_reset'),
url(r'^password_reset/done/$',
PasswordResetDoneView.as_view(template_name='main/reset_password_done.html'),
name='password_reset_done'),
url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
PasswordResetConfirmView.as_view(template_name='main/reset_password_confirm.html'),
name='password_reset_confirm'),
url(r'^reset/done/$',
PasswordResetCompleteView.as_view(template_name='main/reset_password_complete.html'),
name='password_reset_complete'),
]
main/forms.py
from django import forms
from django.contrib.auth.forms import (
AuthenticationForm,
UserCreationForm,
UserChangeForm,
PasswordResetForm,
)
from .models import MyUser
class ResetPasswordForm(PasswordResetForm):
pass
class LoginForm(AuthenticationForm):
username = forms.CharField(label='Username',
widget=forms.TextInput(attrs={'placeholder':'Username'}))
password = forms.CharField(label='Password',
widget=forms.PasswordInput(attrs={'placeholder':'Password'}))
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = MyUser
fields = (
'username',
'firstName',
'lastName',
'email',
'password1',
'password2'
)
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.first_name = self.cleaned_data['firstName']
user.last_name = self.cleaned_data['lastName']
user.email = self.cleaned_data['email']
if commit:
user.save()
return user
customers/models.py
from django.db import models
from django.core.validators import RegexValidator
from main import models as main_models
from django.utils.translation import ugettext_lazy as _
class PhoneModel(models.Model):
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
phone_number = models.CharField(_('Phone Number'),validators=[phone_regex],
max_length=15, blank=True
) # validators should be a list
def __str__(self):
return '%s' % (self.phone_number)
class Meta:
verbose_name = "Phone Number"
#verbose_name_plural = "Phone Numbers"
class CompanyModel(models.Model):
name = models.CharField(_('Company Name'),max_length=255)
since = models.DateField(auto_now_add=True)
def __str__(self):
return '%s - Customer since %s' % (self.name, self.since)
class Meta:
ordering = ['name']
verbose_name = "Company Name"
#verbose_name_plural = "Companies"
class DetailsModel(models.Model):
company = models.OneToOneField(CompanyModel, on_delete=models.CASCADE, primary_key=True)
distance = models.SmallIntegerField(blank=True)
rate = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return '%s - Distance: %s - Rate: %s' % (self.company, self.distance, self.rate)
class Meta:
ordering = ['company']
verbose_name = "Customer Agreement Information"
#verbose_name_plural = "Details"
class SiteModel(models.Model):
company = models.ForeignKey(CompanyModel, on_delete=models.CASCADE)
#contact = models.ForeignKey(main_models.User.email, on_delete=models.CASCADE)
details = models.ForeignKey(DetailsModel, on_delete=models.CASCADE)
street1 = models.CharField(max_length=255)
street2 = models.CharField(max_length=255, blank=True)
city = models.CharField(max_length=50)
state = models.CharField(max_length=2)
zipcode = models.IntegerField()
country = models.CharField(max_length=50)
def __str__(self):
return '%s - %s, %s' % (self.company, self.city, self.state)
class Meta:
ordering = ['company']
verbose_name = "Customer Site Information"
#verbose_name_plural = "Sites"
class ContactModel(models.Model):
company = models.ForeignKey(CompanyModel, on_delete=models.PROTECT, null=True)
first_name = models.CharField(_('First Name'),max_length=255)
last_name = models.CharField(_('First Name'),max_length=255)
email = models.EmailField(_('E-mail Address'), max_length=255, unique=True)
phone = models.ForeignKey(PhoneModel, on_delete=models.PROTECT, null=True)
def __str__(self):
return '%s %s of %s' % (self.first_name, self.last_name, self.company)
I found the answer, the many to many field needs a company reference, therefore instead of adding a user instance you just add a company instance
Related
User Level Registration in Django
I am trying to create two user levels in Django. When they register, they will see a dropdown field where they can choose whether they are a customer or a driver. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_customer = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) address = models.CharField(max_length=300) contact_no = models.CharField(max_length=11) profile_pic = models.ImageField(blank=True, null=True) def __str__(self): return self.user.username views.py def RegisterPage(request): form = RegisterForm() if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() context = {'form':form} return render(request, 'accounts/register.html', context) forms.py from django.contrib.auth.forms import UserCreationForm from .models import * from django import forms from django.db import transaction class RegisterForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=60) last_name = forms.CharField(max_length=150) address = forms.CharField(max_length=300) contact_no = forms.CharField(max_length=11) profile_pic = forms.ImageField(required=False) LEVELS = ( ('Customer', 'Customer'), ('Driver', 'Driver'), ) user_level = forms.ChoiceField(choices=LEVELS) class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'first_name', 'last_name', 'password1', 'password2', 'address', 'contact_no', 'profile_pic', 'user_level'] #transaction.atomic def save(self, commit=True): user = super().save(commit=False) level = self.cleaned_data.get('user_level') if level == 'Customer': user.is_customer = True if commit: user.save() elif level == 'Driver': user.is_driver = True if commit: user.save() profile = Profile.objects.create(user=user) profile.address = self.cleaned_data.get('address') profile.contact_no = self.cleaned_data.get('contact_no') profile.profile_pic = self.cleaned_data.get('profile_pic') profile.save() return user I have registered my user model to the Django settings already. My problem is that it doesn't save to the User model when I check it in the admin page. What seems to be the problem?
table services_parceiros has no column named user_id, DJANGO
thanks for your time. i've been trying to set a model to his creator user. although i'm getting this error and would like to know if am'i doing anything wrong before try a AbstractUser. i'did my user app just in the forms.py i don't know if thats the reason. Error: table services_parceiros has no column named user_id accounts/forms.py: from django import forms from django.contrib.auth import get_user_model, authenticate User = get_user_model() class LoginForm(forms.Form): username = forms.CharField() password = forms.CharField(widget=forms.PasswordInput()) def clean (self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError('usuario não encontrado') if not user.check_password(password): raise forms.ValidationError('senha incorreta') if not user.is_active: raise forms.ValidationError('usuario desativado') return super(LoginForm, self).clean(*args, **kwargs) class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=100) last_name = forms.CharField(max_length=100) email = forms.EmailField(label='Email address') email2 = forms.EmailField(label='Confirm Email') password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'first_name', 'last_name', 'username', 'email', 'email2', 'password' ] def clean(self, *args, **kwargs): email = self.cleaned_data.get('email') email2 = self.cleaned_data.get('email2') if email != email2: raise forms.ValidationError("Emails must match") email_qs = User.objects.filter(email=email) if email_qs.exists(): raise forms.ValidationError( "This email has already been registered") return super(RegisterForm, self).clean(*args, **kwargs) services/models.py: from django.db import models from phone_field import PhoneField from datetime import datetime from django.contrib.auth import get_user_model from django.template.defaultfilters import slugify from accounts.forms import User get_user_model = User class Parceiros (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) nome = models.CharField(max_length=200) endereco = models.TextField(max_length=400, blank=True) responsavel = models.CharField(max_length=100) tel = PhoneField(max_length=12) created_at = models.DateTimeField(auto_now=True) updated_at = models.DateTimeField(auto_now_add=True, blank=True) ativo = models.BooleanField(default=False) def __str__(self): return '%s %s' % (self.user, self.nome) and services/views.py: from django.shortcuts import render, redirect from .models import Servicos, Parceiros, Imagens from django.views.generic import UpdateView, DetailView, ListView from .forms import ParceirosForm, ServicosForm, ImagensForm from django.contrib.auth.decorators import login_required from django.contrib.auth.context_processors import auth def home_view(request): serv = Servicos.objects.all() context = {'serv': serv } return render (request, 'home.html', context) #login_required def parceiros_create(request): if request.method == 'POST': form = ParceirosForm(request.POST) if form.is_valid(): parceiro = form.save(commit=False) parceiro.user = request.user # assuming user is a FK field on Parceiros# parceiro.save() return redirect('home2') else: form = ParceirosForm() context = { 'form': form, } return render (request, 'parceiroform.html', context) def get_queryset(self): return super().get_queryset().filter(parceiro__user=self.request.user) services/forms.py: if i specify the user on fields of my ParceirosForm i'll get the field displayed and still gets the same error when submit. from django import forms from .models import Servicos, Imagens, Parceiros from phone_field import PhoneField class ParceirosForm(forms.ModelForm): nome = forms.CharField(max_length=200) endereco = forms.TextInput() responsavel = forms.CharField(max_length=100) tel = PhoneField(max_length=12) class Meta: prefix = 'parceiro' model = Parceiros fields = ['nome', 'endereco', 'responsavel', 'tel'] 0001_initial.py: from django.conf import settings from django.db import migrations, models import django.db.models.deletion import phone_field.models import services.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Parceiros', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=200)), ('endereco', models.TextField(blank=True, max_length=400)), ('responsavel', models.CharField(max_length=100)), ('tel', phone_field.models.PhoneField(max_length=12)), ('created_at', models.DateTimeField(auto_now=True)), ('updated_at', models.DateTimeField(auto_now_add=True)), ('ativo', models.BooleanField(default=False)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ),
form_invalid() missing 1 required positional argument: 'form'
Hi how are I having a problem with my django user authentication since I am using AbstractBaseUser Model from Apps.grupo.models import Grupo from Apps.empresa_area.models import Empresa_area from Apps.archivos.models import Archivos from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, Group, ) class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("Usuuario tiene email") if not password: raise ValueError("usuario debe tener contraseña") user_obj = self.model( email =self.normalize_email(email) ) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True, ) return user class User(AbstractBaseUser): email = models.EmailField(max_length=200, unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) celular = models.CharField(max_length=20) saludo = models.CharField(max_length=10) grupo = models.ForeignKey(Grupo, null=True, blank=True, on_delete=models.CASCADE) archivo = models.ForeignKey(Archivos, null=True, blank=True, on_delete=models.CASCADE) fec_creacion = models.DateTimeField(auto_now=False, auto_now_add=False) empresa_area_id = models.ForeignKey(Empresa_area, null=True, blank=True, on_delete=models.CASCADE) cargo = models.ManyToManyField(Group) USERNAME_FIELD = 'email' REQUIRED_FILES = [] objects = UserManager() class Meta: verbose_name = ('user') verbose_name_plural = ('users') def __str__(self): return self.email def get_full_name(self): return self.email def get_short_name(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True #property def is_staff(self): return self.staff #property def is_admin(self): return self.admin #property def is_active(self): return self.active In this model is giving the permissions to validate me by email also I have in this view where user authentication is generated view from django.contrib.auth import ( get_user_model, authenticate, login, logout, ) from django.views.generic import CreateView, FormView from django.utils.http import is_safe_url from django.shortcuts import render, redirect from .forms import Login User = get_user_model() class LoginView(FormView): form_class = Login succes_url = '/' template_name = 'Login.html' def form_valid(self, form): request = self.request next_post = request.POST.get('next') next_ = request.GET.get('next') password = form.cleaned_data.get("password") email = form.cleaned_data.get("email") user = authenticate(request, username=email, password=password) if user is not None: login(request, user) try: del request.session['email'] except: pass return super(LoginView, self).form_invalid() It is validating but it is generating the following error form_invalid() missing 1 required positional argument: 'form'
You need to pass the form parameter to the super class call to form_invalid i.e return super(LoginView, self).form_invalid(form)
Django extra registration details not saving
I have form.py with class RegistrationForm and everything works fine but the extra details like email, first and last name, roles is not saved to my account/User profiles but first and last name + emails is saved under AUTHENTICATION AND AUTHORIZATION/Users I been trying to figure our if I made some mix up with model, form or views. What could be the problem? Using python 3 with latest django 2nd 3rd Models.py class UserProfile(models.Model): STUDENT = 1 TOURIST = 2 BUSINESS = 3 ADMIN = 4 ROLE_CHOICES = ( (STUDENT, 'Student'), (TOURIST, 'Tourist'), (BUSINESS, 'Business'), (ADMIN, 'Admin'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) # first_name = models.CharField(max_length=100, default='') # last_name = models.CharField(max_length=100, default='') email = models.EmailField() phone = models.IntegerField(default=0) image = models.ImageField(upload_to='image_profile', blank=True) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, null=True, blank=True) # admin = UserProfileManager() def __str__(self): return self.user.username def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) forms.py ROLES = ((0, 'Student'), (1, 'Tourist'), (2, 'Business')) class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True) role = forms.ChoiceField(choices=ROLES) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'role', 'password1', 'password2' ) def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.role = self.cleaned_data['role'] user.email = self.cleaned_data['email'] if commit: user.save() return user views.py def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Your account has been created!') return redirect(reverse('city:home')) else: form = RegistrationForm() args = {'form': form} return render(request, 'account/register_form.html', args) Admin.py class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'role', 'email') def user_info(self, obj): return obj.role def get_queryset(self, request): queryset = super(UserProfileAdmin, self).get_queryset(request) queryset = queryset.order_by('email') return queryset role.short_description = 'User Type' admin.site.register(UserProfile, UserProfileAdmin)
By given screen shots i think you are using allauth library. If you want to use allauth and modify user model then you have to import AbstractUser class of allauth from django.contrib.auth.models import AbstractUser class User(AbstractUser): phone = models.CharField(_('Telephone'), blank=True, max_length=20) address = models.CharField(_('Address'), blank=True, max_length=255)
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.
Your Override the user model but have make change in backend.py which is use to check when user try to login in this file i think django checking username and password from user model.