![](/img/trans.png)
[英]Python, django, html: I made a booking form and I would like to set this page to login access only without inheriting 'LoginRequiredMixin'
[英]Show a login page to a user who is not logged in without LoginRequiredMixin / django
這是我的代碼
class PostDetail(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if request.user.is_authenticated:
if form.is_valid():
comment = form.save(commit=False)
comment.comment_owner = request.user
comment.post = Post.objects.get(pk=kwargs['pk'])
comment.save()
return redirect('blog:detail', pk=kwargs['pk'])
else:
return redirect('blog:detail', pk=kwargs['pk'])
else:
???
我在詳細視圖中添加了評論表單
當未登錄的用戶嘗試添加評論時,我想顯示一個登錄頁面。
我沒有添加 LoginRequiredMixin 因為任何人都應該能夠看到這個帖子。
有什么建議嗎?
# You just need to redirect to login page
views.py
from django.shortcuts import render, redirect
class PostDetail(DetailView):
model = Post
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['form'] = CommentForm()
return context
def post(self, request, *args, **kwargs):
form = CommentForm(request.POST)
if request.user.is_authenticated:
if form.is_valid():
comment = form.save(commit=False)
comment.comment_owner = request.user
comment.post = Post.objects.get(pk=kwargs['pk'])
comment.save()
return redirect('blog:detail', pk=kwargs['pk'])
else:
return redirect('blog:detail', pk=kwargs['pk'])
else:
return redirect('login-user')
# add a namespace in your urls, so that the user can redirect to that namespace 'login-user'
urls.py
re_path(r'^login-admin/$', LoginView.as_view(), name='login-user'),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.