I'm coding a news website,in the detail news page ,there is a comment fountain,if people want to post comment they need to login first.And I want to make it that,after they login in successfully ,the page can return to previous news page.
Here is my views.py:
def newsDetailView(request, news_pk):
news = News.objects.get(id=news_pk)
title = news.title
author = news.author_name
add_time = news.add_time
content = news.content
category = news.category
tags = news.tag.annotate(news_count=Count('news'))
all_comments = NewsComments.objects.filter(news=news)
comment_form = CommentForm(request.POST or None)
if request.method == 'POST' and comment_form.is_valid():
comments = comment_form.cleaned_data.get("comment")
comment = NewsComments(user=request.user, comments=comments, news=news)
comment.save()
return render(request, "news_detail.html", {
'title': title,
'author': author,
'add_time': add_time,
'content': content,
'tags': tags,
'category': category,
'all_comments': all_comments,
'comment_form': comment_form
})
Here is my news_detail.html:
{% if user.is_authenticated %}
<form method="POST" action="">{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"><h5>评论 <i class="fa fa-comments"></i></h5>
</label>
<textarea id="js-pl-textarea" class="form-control" rows="4"
placeholder="我就想说..." name="comment"></textarea>
<div class="text-center mt-3">
<input type="submit" id='js-pl-submit' class="btn btn-danger comment-submit-button" value="Submit Comemmt">
</input>
</div>
</div>
</form>
{% else %}
<span>Please Login or register first</span>
<a class="btn btn-primary mb-5"
href="{% url 'login' %}?next={{ request.path }}">登录</a>
<a class="btn btn-danger mb-5" href="{% url 'register' %}?next={{ request.path }}">注册</a>
{% endif %}
Here is my LoginView:
class LoginView(View):
def get(self, request):
return render(request, "login.html", {})
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
user = authenticate(username=user_name, password=pass_word)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
else:
return render(request, "login.html", {"msg": "用户未激活!"})
else:
return render(request, "login.html", {"msg": "用户名或密码错误!"})
else:
return render(request, "login.html", {"login_form": login_form})
And I have a login.html and register.html.They works very well.
Anybody know how to make it in my particular case?Thank you so much!