this is my code
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:
???
i added comment form in detailview
When a user who is not logged in attempts to add a comment, I want to display a login page.
i didn't add LoginRequiredMixin because anyone should be able to see the post.
any advice?
# 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'),
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.