我如何限制用户使用某些特定的网址

时间:2019-03-15 16:58:00

标签: python django

我想通过在地址栏中输入“家庭/商店/结帐/”和“家庭/商店/付款/” 这样的网址来限制用户访问付款和结帐页面 我想仅在buy_now表单有效或items_buy_now表单有效时使这些页面可访问

  

urls.py

path('payment/',views.payment,name='payment'),
path('checkout/', views.checkout, name="checkout"),
  

views.py

def checkout(request):
        request.session.pop('data', None)
        messages.success(request,'Done.Thanks for using our services.')
        return redirect("shop:mycart")

        def payment(request):
            return render(request,'shop/payment.html')

        def buy_now(request,slug):
        if not request.user.is_authenticated:
            messages.info(request, 'You have to logged in first.')
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        product = Product.objects.get(active=True, slug=slug)
        if request.method == "POST":
            form = BuyerDeliveryForm(request.POST)
            if form.is_valid():
                buyer = form.save(commit=False)
                buyer.save()
                return redirect('shop:payment')
        else:
            form = BuyerDeliveryForm()
        return render(request, 'shop/delivery_form.html', {'form': form, 'products': product})


    def items_buy_now(request):
        if not request.user.is_authenticated:
            messages.info(request, 'You have to logged in first.')
            return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path))
        if request.method == "POST":
            form = BuyerDeliveryForm(request.POST)
            if form.is_valid():
                buyer = form.save(commit=False)
                buyer.save()
                return redirect('shop:payment')
        else:
            form = BuyerDeliveryForm()
        return render(request, 'shop/delivery_form.html', {'form': form})

1 个答案:

答案 0 :(得分:0)

最好的方法是:

  1. 创建一个用于管理项目“ item_buy”或“ items_buy”的Mixin
  2. 对于必须处理该限制的所有视图,请从各自的mixin对其进行子类化。
  3. 在子类的get函数中,调用方法以检查用户是否具有访问该页面的权限。