简体   繁体   中英

Login redirect url in django

I am building a website that have customer and merchant. Each of them have different login. what i want is each user to login to his own view.

models.py

class User(AbstractUser):
    is_customer=models.BooleanField(default=False)
    is_merchant=models.BooleanField(default=False)



class Customer(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True)

class Merchant(models.Model):
    #user = models.ForeignKey(User, on_delete=models.CASCADE)
user=models.OneToOneField(User,on_delete=models.CASCADE, primary_key=True)

views.py

#merchant view
def users_homepage(request):
    product = Product.objects.filter(merchant=request.user.merchant).order_by('date_added')
    itemsordered=OrderItem.objects.filter(merchant=request.user.merchant)
#customer view
def index(request):
    listing=Category.objects.all()
    product=Product.objects.all()[:8]

setings.py

LOGIN_REDIRECT_URL='/users'

please show me how i can do it. thanks beforehand.

You have to use @login_required decorator on the function base view and

if you are going to use class base view there is two way

  1. Through LoginRequiredMixin using inheritance
  2. Through @login_required on the method or class level as well

Here give an example

  • The first use function base view illustrating the login required
from django.contrib.auth.decorators import login_required

@login_required
def my_first_view(request):
    return HttpResponse("Welcome")

# if not define in settings.py 
from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def my_second_view(request):
    return HttpResponse("Welcome")

See this blog decorator login required

  • The second use class base view with LoginRequiredMixin
from django.contrib.auth.mixins import LoginRequiredMixin

 class ProfileCBV(LoginRequiredMixin, View):
    login_url = '/cbs/login' # if not define in settings.py
    def get(self, request, *args, **kwargs):
        return HttpResponse("Welcome")
  • The third is login required in the class base view
from django.contrib.auth.decorators import login_required
 url(r'^profile/$', login_required(views.ProfileCBV.as_view()))

# if use in views.py
from django.contrib.auth.decorators import login_required
from django.utils.decorators        import method_decorator

@method_decorator([login_required], name='dispatch')
class ProfileCBV(View):
    def get(self, request, *args, **kwargs):
        return HttpResponse("Welcome")

There is lots of views and mixin available like UserPassTestMixin , PermissionRequiredMixin etc Here give a link Views and mixin

let me know in a comment if you face any problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM