In my project I have two users which are client and service provider. I have created an User model in which have given is_client and is_serviceprovider. I have created separate signup forms for both the users. When I signup as a client, I am getting Integrity Error showing duplicate email entry but in the user model I can see the data being stored
As I am a beginner, please guide me
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _
from phonenumber_field.modelfields import PhoneNumberField
# Create your models here.
class User(AbstractUser):
is_client = models.BooleanField(default = False)
is_serviceprovider = models.BooleanField(default = False)
class Client(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
first_name = models.CharField(_("first name"),max_length=30)
last_name = models.CharField(_("last name"),max_length=30)
email = models.EmailField(_("email"),unique=True)
phone_number = PhoneNumberField(_("phone number"),unique=True, region='IN')
gender = models.CharField(_("gender"),max_length=6, choices=GENDER_CHOICES)
date_of_birth = models.DateField(_("date of birth"),default='2000-01-01')
address1 = models.CharField(_("address"), max_length=128)
address2 = models.CharField(_("address cont'd"), max_length=128, blank=True)
location = models.CharField(_("location"), max_length=64)
city = models.CharField(_("city"), max_length=64)
state = models.CharField(_("state"), max_length=64, default="Maharashtra")
pin_code = models.CharField(_("pin code"), max_length=7)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
class ServiceProvider(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
('O', 'Other'),
)
first_name = models.CharField(_("first name"),max_length=30)
last_name = models.CharField(_("last name"),max_length=30)
email = models.EmailField(_("email"),unique=True)
phone_number = PhoneNumberField(_("phone number"),unique=True, region='IN')
gender = models.CharField(_("gender"),max_length=6, choices=GENDER_CHOICES)
date_of_birth = models.DateField(_("date of birth"),default='2000-01-01')
address1 = models.CharField(_("address"), max_length=128)
address2 = models.CharField(_("address cont'd"), max_length=128, blank=True)
location = models.CharField(_("location"), max_length=64)
city = models.CharField(_("city"), max_length=64)
state = models.CharField(_("state"), max_length=64, default="Maharashtra")
pin_code = models.CharField(_("pin code"), max_length=7)
service_name = models.CharField(_("service name"), max_length=20)
experience = models.CharField(_("experience"), max_length=20)
area_choice = models.CharField(_("area choice"), max_length=20)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.db import transaction
from django.forms.utils import ValidationError
from .models import User, Client, ServiceProvider
from phonenumber_field.formfields import PhoneNumberField
class ClientSignUpForm(UserCreationForm):
username = forms.CharField(max_length=150)
email = forms.EmailField()
first_name = forms.CharField(label="First Name", max_length=30)
last_name = forms.CharField(label="Last Name", max_length=30)
phone_number = PhoneNumberField(label="Phone Number", region='IN')
gender = forms.ChoiceField(label="Gender", choices=Client.GENDER_CHOICES)
date_of_birth = forms.DateField(label="Date of Birth", widget=forms.DateInput(attrs={'type': 'date'}))
address1 = forms.CharField(label="Address", max_length=128)
address2 = forms.CharField(label="Address cont'd", max_length=128, required=False)
location = forms.CharField(label="Location", max_length=64)
city = forms.CharField(label="City", max_length=64)
state = forms.CharField(label="State", max_length=64, initial="Maharashtra")
pin_code = forms.CharField(label="Pin Code", max_length=7)
class Meta(UserCreationForm.Meta):
model = User
fields = ['username', 'first_name', 'last_name', 'email']
@transaction.atomic
def save(self, commit=True):
user = super().save(commit=False)
user.is_client = True
if commit:
user.save()
client = Client.objects.create(
user=user,
phone_number=self.cleaned_data['phone_number'],
gender=self.cleaned_data['gender'],
date_of_birth=self.cleaned_data['date_of_birth'],
address1=self.cleaned_data['address1'],
address2=self.cleaned_data['address2'],
location=self.cleaned_data['location'],
city=self.cleaned_data['city'],
state=self.cleaned_data['state'],
pin_code=self.cleaned_data['pin_code'])
client.save()
return user
class ServiceProviderSignUpForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = User
@transaction.atomic
def save(self, commit=True):
user = super().save(commit=False)
user.is_serviceprovider = True
if commit:
user.save()
return user
views/client.py
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.views.generic import CreateView, ListView, UpdateView
from django.db import IntegrityError
from django.http import HttpResponseServerError
from ..forms import ClientSignUpForm, ServiceProviderSignUpForm
from ..models import User, Client, ServiceProvider
class ClientSignUpView(CreateView):
model = User
form_class = ClientSignUpForm
template_name = 'users/registration/client_signup.html'
def get_context_data(self, **kwargs):
kwargs['user_type'] = 'client'
return super().get_context_data(**kwargs)
def form_valid(self, form):
try:
email = form.cleaned_data['email']
if User.objects.filter(email=email).exists():
raise IntegrityError("Email already exists in the User model.")
user = form.save(commit=False)
user.save()
client = Client.objects.create(
user=user,
phone_number=form.cleaned_data['phone_number'],
gender=form.cleaned_data['gender'],
date_of_birth=form.cleaned_data['date_of_birth'],
address1=form.cleaned_data['address1'],
address2=form.cleaned_data['address2'],
location=form.cleaned_data['location'],
city=form.cleaned_data['city'],
state=form.cleaned_data['state'],
pin_code=form.cleaned_data['pin_code'])
login(self.request, user)
return redirect('homepage')
except IntegrityError as e:
# Handle the integrity error
return HttpResponseServerError(f"Error: {e}")
decorators.py
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import user_passes_test
def client_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_client,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
def serviceprovider_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='login'):
actual_decorator = user_passes_test(
lambda u: u.is_active and u.is_serviceprovider,
login_url=login_url,
redirect_field_name=redirect_field_name
)
if function:
return actual_decorator(function)
return actual_decorator
The error
Internal Server Error: /users/client/signup/
Traceback (most recent call last):
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute
return self.cursor.execute(sql, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute
return self.cursor.execute(query, args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute
res = self._query(mogrified_query)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query
db.query(q)
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\connections.py", line 261, in query
_mysql.connection.query(self, query)
MySQLdb.IntegrityError: (1062, "Duplicate entry '' for key 'users_client.email'")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\views\generic\base.py", line 104, in view
return self.dispatch(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\views\generic\base.py", line 143, in dispatch
return handler(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\views\generic\edit.py", line 182, in post
return super().post(request, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\views\generic\edit.py", line 151, in post
return self.form_valid(form)
^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\quickservice\users\views\client.py", line 27, in form_valid
user = form.save()
^^^^^^^^^^^
File "C:\Users\Rajan Gaikwad\AppData\Local\Programs\Python\Python312\Lib\contextlib.py", line 81, in inner
return func(*args, **kwds)
^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\quickservice\users\forms.py", line 37, in save
client = Client.objects.create(
^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\query.py", line 679, in create
obj.save(force_insert=True, using=self.db)
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\base.py", line 822, in save
self.save_base(
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\base.py", line 909, in save_base
updated = self._save_table(
^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\base.py", line 1067, in _save_table
results = self._do_insert(
^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\base.py", line 1108, in _do_insert
return manager._insert(
^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\query.py", line 1847, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\models\sql\compiler.py", line 1823, in execute_sql
cursor.execute(sql, params)
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 122, in execute
return super().execute(sql, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 79, in execute
return self._execute_with_wrappers(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 92, in _execute_with_wrappers
return executor(sql, params, many, context)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 100, in _execute
with self.db.wrap_database_errors:
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute
return self.cursor.execute(sql, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\django\db\backends\mysql\base.py", line 76, in execute
return self.cursor.execute(query, args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\cursors.py", line 179, in execute
res = self._query(mogrified_query)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\cursors.py", line 330, in _query
db.query(q)
File "F:\Shruti projects\Scratch\QuickServiceWebApp\my_venv\Lib\site-packages\MySQLdb\connections.py", line 261, in query
_mysql.connection.query(self, query)
django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'users_client.email'")
[30/Mar/2024 21:42:49] "POST /users/client/signup/ HTTP/1.1" 500 219079