我编写了一个基本的论坛模型,允许用户创建其他人可以回复的帖子。在用户提交对论坛帖子的回复表单后,该站点显示一个空白的 CommentForm,但相反,我希望用户被重定向到他们回复的唯一论坛帖子。 这是我到目前为止所拥有的:
# views.py
from django.shortcuts import render, get_object_or_404
from .models import Forum
from .forms import CommentForm, ForumForm
from django.contrib.auth.decorators import login_required
# this is the view for the response form
@login_required
def newcomment(request):
form = CommentForm
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
post = form.save(commit = True)
post.save()
form = CommentForm
else:
form = CommentForm
return render(request, 'myapp/newcomment.html', {'form' : form})
# this is the view for a specific forum
def forumdetail(request, id):
forum = get_object_or_404(Forum, pk = id)
responses=[]
responses.append(forum.comment_set.all())
context={'forum' : forum,
'responses' : responses}
return render(request, 'myapp/forumdetail.html', context)
这是回复表单的网页
<!-- myapp/newcomment.html -->
{% extends 'base.html' %}
{% block content %}
<h2 style="font-family: Impact; letter-spacing: 3px;">New Comment</h2>
<table class = 'table'>
<form method = "POST" class = "post-form">
{% csrf_token %}
{{form.as_table}}
</table>
<button type = 'submit' class = "save btn btn_default">
Save
</button>
</form>
{% endblock %}
这是特定论坛的网页
<!-- myapp/forumdetail.html -->
{% extends 'base.html' %}
{% block content %}
<h2 style="font-family: Impact; letter-spacing: 3px;">{{forum.topic}}</h2>
<p style = "border-bottom: solid; border-width: 1px; padding-bottom: 15px;">{{forum.description}}
<br>
<small>Posted by {{forum.userID}} on {{forum.date_created}}</small>
</p>
<button style = "background-color: gray;">
<a href = "{% url 'newcomment' %}" style = "color: white;">Comment</a>
</button>
<h3>Comments:</h3>
<ul>
<li style = "list-style-type: none;">
{% for response in responses %}
{% for objs in response %}
{% if objs.forum == forum %}
{{ objs.response }}
<br>
<small style = "list-style-type: none; border-bottom: solid; border-width: 1px; padding-bottom: 15px;">
{{ objs.userID }} on {{ objs.date_created }}</small>
<br>
<br>
{% endif %}
{% endfor %}
{% endfor %}
</li>
</ul>
{% endblock%}
答案 0 :(得分:0)
这是你能做的
from django.shortcuts import redirect
def newcomment(request):
form = CommentForm
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
post = form.save(commit = True)
post.save()
form = CommentForm
else:
form = CommentForm
return redirect('forumdetail', post.forum.id)
答案 1 :(得分:0)
尝试使用这个:-
从 django.shortcuts 导入重定向
def newcomment(request,id):
form = CommentForm
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
post = form.save(commit = True)
post.save()
form = CommentForm
else:
form = CommentForm
return redirect('forumdetail',id=id)
urls.py
path ('newcomment/<int:id>/', views.newcomment,name='newcomment'),