Hello,
I want to have two user models in my Django project, one for admin access and the other for customer-specific use. I have created a separate user model and am developing the necessary forms, but I cannot use both at the same time. This means that when one is logged in, the other cannot log in or gives an error. I need to close one or only be logged into one at a time. My guess is that two different cookies will be created for the two models, but I don’t know how to do this and I want to believe there is an easy way. Thank you in advance for your help.
customeruser/models.py
class CustomUserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError("Email is required.")
email = self.normalize_email(email)
user = self.model(user_email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
class CustomerUser(AbstractBaseUser,PermissionsMixin):
first_name = models.CharField(max_length=150, blank=False, null=False)
last_name = models.CharField(max_length=150, blank=False, null=False)
email = models.EmailField(unique=True)
email_is_verify = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
phone_number = PhoneField(null=True, blank=True)
phone_number_is_verify = models.BooleanField(default=False)
account_id = models.PositiveIntegerField(unique=True, default=random.randint(100000, 9999999999),primary_key=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name',]
objects = CustomUserManager()
groups = models.ManyToManyField(
'auth.Group',
related_name='customeruser_groups', # Bu alana özel bir related_name veriyoruz
blank=True
)
user_permissions = models.ManyToManyField(
'auth.Permission',
related_name='customeruser_permissions', # Bu alana özel bir related_name veriyoruz
blank=True
)
def __str__(self):
return self.email
customeruser/forms.py
class CustomerUserCreationForm(forms.ModelForm):
first_name = forms.CharField(
label="Adınız",
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Adınızı giriniz.'})
)
last_name = forms.CharField(
label="Soy adınız",
widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Soy adınızı giriniz.'})
)
email = forms.EmailField(
label="Email",
widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Adresinizi giriniz'})
)
password = forms.CharField(
label="Şifre",
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Şifre'})
)
repeat_password = forms.CharField(
label="Tekrar Şifre Giriniz.",
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Şifre'})
)
class Meta:
model = CustomerUser
fields = ['first_name', 'last_name', 'email', 'password',"repeat_password"]
def save(self, commit=True):
print("selam2")
user = super().save(commit=False)
cleaned_data = super().clean()
password = cleaned_data.get("password")
repeat_password = cleaned_data.get("repeat_password")
print("selam")
# Şifrelerin eşleşip eşleşmediğini kontrol et
if password != repeat_password:
print("şifreler eşleşmedi")
self.add_error('repeat_password', "Şifreler eşleşmiyor.")
user.set_password(self.cleaned_data['password']) # Şifreyi hashleyerek kaydet
if commit:
print(user.account_id)
user.save()
return user
class CustomLoginForm(AuthenticationForm):
username = forms.EmailField(
label="Email",
widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Email Adresiniz'})
)
password = forms.CharField(
label="Şifre",
widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Şifre'})
)
customeruser/views.py
def register_view(request):
if request.user.is_authenticated:
return redirect('profile') # Kullanıcıyı profil sayfasına yönlendir
if request.method == 'POST':
form = CustomerUserCreationForm(request.POST)
print("girdi2")
if form.is_valid():
print("girdi")
user = form.save() # Kullanıcıyı kaydet
login(request, user,backend='customeruser.backends.EmailBackend') # Kullanıcıyı giriş yaptır
return redirect('profile') # Başarılı kayıt sonrası yönlendirme
else:
form = CustomerUserCreationForm()
print("else oldu")
context = {
"Navbar":navbar.objects.filter(navbar_status="Active"),
"Banner":Banner.objects.filter(banner_status="Active"),
"top_navbar":top_page_navbar.objects.filter(top_navbar_status="Active").order_by("top_navbar_order").first(),
"footer":footer.objects.filter(footer_status="Active").order_by("footer_order").first(),
"form":form
}
return render(request, 'maintheme/user/register.html', context=context)
def login_view(request):
if request.user.is_authenticated:
print("kullanıcı otorum açmış")
print(request.user)
return redirect ("profile")
if request.method == "POST":
form = CustomLoginForm(request, data=request.POST)
print(form)
if form.is_valid():
email = form.cleaned_data.get("username") # 'username' yerine e-posta kullanılıyor
password = form.cleaned_data.get("password")
user = EmailBackend.authenticate(self=EmailBackend,request=request, username=email, password=password) # username olarak email giriyoruz
print(user)
if user is not None:
login(request, user, backend="customeruser.backends.EmailBackend")
return redirect("profile")
else:
messages.error(request, "Geçersiz email veya şifre.")
else:
messages.error(request, "Form geçersiz. Lütfen bilgilerinizi kontrol edin.")
else:
form = CustomLoginForm()
context = {
"Navbar":navbar.objects.filter(navbar_status="Active"),
"Banner":Banner.objects.filter(banner_status="Active"),
"top_navbar":top_page_navbar.objects.filter(top_navbar_status="Active").order_by("top_navbar_order").first(),
"footer":footer.objects.filter(footer_status="Active").order_by("footer_order").first(),
"form":form
}
return render(request, 'maintheme/user/login.html', context=context)
@login_required(login_url="login")
def profile_view(request):
return render(request, 'maintheme/profil.html')
def logout_view(request):
customeruser/backends.py
class EmailBackend(BaseBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
try:
# Email üzerinden kullanıcıyı alıyoruz
user = CustomerUser.objects.get(email=username)
except CustomerUser.DoesNotExist:
return None
# Şifreyi kontrol et
if user and check_password(password, user.password):
return user
return None
def get_user(self, account_id):
try:
return CustomerUser.objects.get(pk=account_id)
except CustomerUser.DoesNotExist:
return None