'model with this Email already exists in django
I have made a custom user model. signup and logout are working fine. but I have made a login form using that model. my model name is usersignupmodel. but whenever after signing-up, then I try to log in it gives me an error like that User signup model with this Email already exists.
I can not find the problem, please help.
models.py
from django.db import models
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
class SignUpManager(BaseUserManager):
def create_user(self, email,age,name, username, password=None):
#if not email:
#raise ValueError("insert user")
if not username:
raise ValueError("insert username")
if not name:
raise ValueError("insert name")
if not age:
raise ValueError("insert age")
user = self.model(
email=self.normalize_email(email),
username=username,
age=age,
name=name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,name,age,username, password):
user = self.create_user(
email=self.normalize_email(email),
username=username,
password=password,
age=age,
name=name,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class UserSignupModel(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60,unique=True)
age = models.CharField(max_length=15)
name = models.CharField(max_length=15)
username = models.CharField(max_length=15, unique=True)
date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True)
last_login = models.DateTimeField(verbose_name="last login", auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = "username"
REQUIRED_FIELDS = ['email','name','age']
objects = SignUpManager()
def __str__(self):
return self.name
def has_perm(self, perm, obj=None):
return self.is_admin
def has_module_perms(self, app_label):
return True
#migrate --run-syncdb in case no work
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from diabetes.models import UserSignupModel
from django.contrib.auth import login,authenticate,logout
class UserSignupForm(UserCreationForm):
email=forms.EmailField(max_length=60,help_text="add a valid email address",required=True)
name=forms.CharField(max_length=15,help_text="add a valid name")
age=forms.CharField(max_length=15)
class Meta:
model=UserSignupModel
fields=('email','name',"username",'age',"password1","password2")
class UserLoginForm(forms.ModelForm):
password=forms.CharField(label="password",widget=forms.PasswordInput)
class Meta:
model=UserSignupModel
fields=("email","password")
def clean(self):
if self.is_valid():
email=self.cleaned_data['email']
password=self.cleaned_data['password']
if not authenticate(email=email,password=password):
raise forms.ValidationError("Invalid LOGIN")
views.py
from django.shortcuts import render,redirect
from django.contrib.auth import login,authenticate,logout
from diabetes.forms import UserSignupForm,UserLoginForm
def home(request):
return render(request,'diabetes/home.html')
def signupuser(request):
context={}
if request.POST:
form=UserSignupForm(request.POST)
if form.is_valid():
form.save()
email=form.cleaned_data.get('email')
raw_password=form.cleaned_data.get('password1')
name=form.cleaned_data.get('name')
age=form.cleaned_data.get('age')
username=form.cleaned_data.get('username')
account=authenticate(email=email,password=raw_password,name=name,age=age,username=username) login(request,account) return redirect('home') else: context["reg_form"]=form
else:
form = UserSignupForm()
context["reg_form"] = form
return render (request,'diabetes/signupuser.html',context)
def logoutuser(request):
logout(request)
return redirect('home')
def loginuser(request):
context={}
user=request.user
if user.is_authenticated:
return redirect('home')
if request.method=="POST":
form=UserLoginForm(request.POST)
if form.is_valid():
password=request.POST["password"]
email=request.POST["email"]
user=authenticate(password=password,email=email)
if user:
login(request,user,)
return redirect("home")
else:
form=UserLoginForm()
context['form']=form
return render(request,"diabetes/loginuser.html",context)
loginuser.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }}
{{ field}}
{% if field.help_text %}
<small>{{ field.help_text }}</small>
{% endif %}
{% for field in form %}
{% for error in field.errors %}
<strong>{{ error }}</strong>
{% endfor %}
{% endfor %}
{% if form.non_field_errors %}
<small>{{ form.non_field_errors}}</small>
{% endif %}
</p>
{% endfor %}
<input type="submit">SUBMIT</input>
</form>
</body>
</html>
Solution 1:[1]
You can try to remove following lines:
form=UserLoginForm(request.POST)
if form.is_valid():
You defined login and signup with same model, so is_valid
should fail after signup. The form validates model to create a new instance, this is why you got this error.
Solution 2:[2]
As I suspected, the UserLoginForm was trying to make another registration, that is, create a new user again, instead of authenticate and do the login. That was happening because my form inherited from forms.ModelForm; changing from forms.ModelForm to forms.Form solved the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Deniz Kaplan |
Solution 2 | Oeng Kim Chhay |