Django authentication with modelform

I have two models

from django.contrib.auth.models import User class Vendor(models.MOdel): user = models.ForeignKey(User,related_name = 'vendor') ...................................................... ...................................................... class Customer(models.MOdel): user = models.ForeignKey(User,related_name = 'customer') ........................................................ ....................................................... 

what I want to do is enable the login for the provider and customer. The provider URL is “provider / login” and the client is “client / login”. While the provider submits its credentials, I want to check whether the user is a seller or not and is causing a verification error. I could not find a way to accomplish this with django. What I basically need is something like modelform for a user who checks that the user is a provider using queryset.But django auth has nothing like this.

+4
source share
2 answers

You can use the Django custom model , add a type field, and use it as a factory source to load Vendor / Customer objects. This solution worked very well for me. Where to begin:

models.py

 from django.contrib.auth.models import AbstractUser TYPES = ( ('Vendor', 'Vendor'), ('Customer', 'Customer'), ) class MyUser(AbstractUser): type = models.CharField(max_length=10, choices=TYPES, default='Customer') 

This approach is very flexible and scales well if you need to add other types in the future. A small example of a forwarding approach:

 class Base(): def __init__(self, auth_user): self.user = auth_user def redirect_to(self): return "" class Vendor(Base): def redirect_to(self): return "/login/vendor" class Customer(Base): def redirect_to(self): return "/login/customer" 

Then, in the login view, you simply dynamically create a user object:

 auth_user = form.get_user() cls = globals()[auth_user.type] user = cls(auth_user) # This will return either Vendor or Customer object return HttpResponseRedirect(user.redirect_to()) 

You can easily create other types of users by simply adding a new class and applying the necessary methods without even touching the rest of the code.

+2
source

The best strategy for me is to record two Authentication Backends, one of which allows authentication of the provider, and the other for the client.

AUTHENTICATION_BACKENDS is a settings constant that provides the root authorization code. here you can check the authentication documentation.

Declare your capabilities with a parameter parameter. When ordering, django will try to use all the backends until it is successful.

+2
source

Source: https://habr.com/ru/post/1490723/


All Articles