编辑 post 后在同一个 post_id 上重定向
redirect on the same post_id after edit post
我在 Django 中创建了一个论坛网站,用户可以在其中 post Questions/Answers 和编辑它们。
编辑回复后,我想将用户重定向到当前编辑的 post 页面。就像用户
编辑已对 ID 为 4 的问题进行 post 编辑的回复(url 为 (http://127.0.0.1:8000/discussion/4)),然后在编辑后应重定向到相同的 URL。编辑并删除回复后,我将用户重定向到论坛主页,但我想重定向到 /discussion/{post_id}
URL(即特定 post 上的 URL正在编辑和删除的回复)
urls.py
app_name = "dashboard"
urlpatterns = [
path('', views.index, name="index"),
path('user_home', views.user_home, name="user_home"),
path('admin_home', views.admin_home, name="admin_home"),
path("forum", views.forum, name="forum"),
path("discussion/<int:myid>", views.discussion, name="discussion"),
path("showallusers", views.show_all_users, name="showallusers"),
path('delete_user/<int:pk>', views.delete_user, name="delete_user"),
path('delete_post/<int:pk>', views.delete_post, name="delete_post"),
path('delete_reply/<int:pk>', views.delete_reply, name="delete_reply"),
path('upload_notes', views.upload_notes, name='upload_notes'),
path('view_mynotes', views.view_mynotes, name='view_mynotes'),
path('delete_mynotes/<int:pk>/', views.delete_mynotes, `name='delete_mynotes'), `
path('pending_notes', views.pending_notes, name='pending_notes'),
path('assign_status/<int:pk>', views.assign_status, name='assign_status'),
path('accepted_notes', views.accepted_notes, name='accepted_notes'),
path('rejected_notes', views.rejected_notes, name='rejected_notes'),
path('all_notes', views.all_notes, name='all_notes'),
path('delete_notes/<int:pk>', views.delete_notes, name='delete_notes'),
path('delete-records/', views.delete_notes, name='delete_notes'),
path('view_allnotes', views.view_allnotes, name='view_allnotes'),
path('notessharing', views.notessharing, name='notessharing'),
path('edit_post/<int:pk>/', views.edit_post, name='edit_post'),
path('edit_reply/<int:pk>/', views.edit_reply, name='edit_reply'),
]
delete_reply代码
def delete_reply(request, pk=None):
reply = Replie.objects.filter(id=pk)
reply.delete()
return redirect('/forum')
删除 post 的回复后,我想重定向到同一个 post。
models.py
class Post(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
post_id = models.AutoField
post_content = models.TextField(max_length=5000,verbose_name="")
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
class Replie(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
reply_id = models.AutoField
reply_content = models.TextField(max_length=5000,verbose_name="")
post = models.ForeignKey(Post, on_delete=models.CASCADE, default='')
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
views.py
def forum(request):
user = request.user
profile = Profile.objects.all()
if request.method=="POST":
form=PostContent(request.POST)
if form.is_valid():
user = request.user
image = request.user.profile.image
content = request.POST.get('post_content','')
post = Post(user1=user, post_content=content, image=image)
post.save()
messages.success(request, f'Your Question has been posted successfully!!')
return redirect('/forum')
else:
form=PostContent()
posts = Post.objects.filter().order_by('-timestamp')
form= PostContent()
context={
'posts':posts,
'form':form
}
return render(request, "forum.html",context)
def discussion(request, myid):
post = Post.objects.filter(id=myid).first()
replies = Replie.objects.filter(post=post)
if request.method=="POST":
form=ReplyContent(request.POST)
if form.is_valid():
user = request.user
image = request.user.profile.image
desc = request.POST.get('reply_content','')
post_id =request.POST.get('post_id','')
reply = Replie(user = user, reply_content = desc, post=post, image=image)
reply.save()
messages.success(request, f'Your Reply has been posted successfully!!')
return redirect(f'/discussion/{post_id}')
else:
form=ReplyContent()
form= ReplyContent()
return render(request, "discussion.html", {'post':post, 'replies':replies,'form':form})
def edit_reply(request, pk):
reply = Replie.objects.get(id=pk)
if request.method == 'POST':
form = UpdateReplyForm(request.POST, instance=reply)
if form.is_valid():
form.save()
messages.success(request,"Reply updated successfully!")
return redirect('/forum')
else:
form = UpdateReplyForm(instance=reply)
context = {
'form': form
}
return render(request, 'edit_reply.html', context)
edit_post 查看
def edit_post(request, pk):
post = Post.objects.get(id=pk)
if request.method == 'POST':
form = UpdatePostForm(request.POST, instance=post)
if form.is_valid():
form.save()
messages.success(request, "Post updated successfully!")
return redirect('/forum')
else:
form = UpdatePostForm(instance=post)
context = {
'form': form
}
return render(request, 'edit_post.html', context)
目前,在编辑回复后,我将用户重定向到 post 主页,但我想重定向到 /discussion/{post_id}
。
模板代码:
edit_reply.html
{% load static %}
{% block body %}
{% load crispy_forms_tags %}
<div class="container ">
<form method="POST">
<div class="form-group">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 mt-4 f2" >Update Reply</legend>
</fieldset>
<label style="font-size:1rem; font-weight:bold;">Reply Content</label>
{{form|crispy}}
<input type="hidden" name="post_id" value="{{post_id}}">
<div class="form-group">
<button href="" class="btn btn-primary" type="Update">
Update
</button>
</div>
</div>
</form>
</div>
{% endblock body %}
您可以通过在 edit_reply
视图中传递 args=[reply.post.id]
将其重定向到带有 pk
的 discussion
视图。
试试这个:
views.py
from django.shortcuts import render, redirect
from django.urls import reverse
def edit_reply(request, pk):
reply = Replie.objects.get(id=pk)
if request.method == 'POST':
form = UpdateReplyForm(request.POST, instance=reply)
if form.is_valid():
form.save()
messages.success(request, "Reply updated successfully!")
return redirect(reverse('dashboard:discussion', args=[reply.post.id]))
else:
form = UpdateReplyForm(instance=reply)
context = {
'form': form
}
return render(request, 'home/edit_reply.html', context)
Note:
Forms in django required Form
to be the suffix, so it will be better if it changed to PostContentForm
and ReplyContentForm
from PostContent
and ReplyContent
respectively.
一定是
return f'{self.user} Post'
不是
return f'{self.user`} Post'
因为它不是 Replie
模型中的任何字段。
Note:
ForeignKey's names are generally written in its own name and that too in snake_case
, it will be better if you change user1
to user
in Post
model.
为了更好地理解:
如果 table 名称是 PizzaTopingCategory
那么在创建 ForeignKey 时你应该将其命名为
pizza_toping_category=models.ForeignKey(PizzaTopingCategory, on_delete=models.CASCADE)
编辑:
你需要找到post_id
,所以你可以通过:
发送
在 delte_reply
视图中试试这个:
def delete_reply(request, pk=None):
reply = Replie.objects.filter(id=pk)
reply_instance = get_object_or_404(Replie,id=pk)
post_pk=reply_instance.post.id
reply.delete()
return redirect(reverse('dashboard:discussion', args=[post_pk]))
为了在 discussion
视图中传递 pk
,您应该在 edit_post
视图中编写 return redirect(reverse('dashboard:discussion', args=[reply.post.id]))
:
views.py
def edit_post(request, pk):
post = Post.objects.get(id=pk)
if request.method == 'POST':
form = UpdatePostForm(request.POST, instance=post)
if form.is_valid():
form.save()
messages.success(request, "Post updated successfully!")
return redirect(reverse('dashboard:discussion', args=[post.id]))
else:
form = UpdatePostForm(instance=post)
context = {
'form': form
}
return render(request, 'home/edit_post.html', context)
我在 Django 中创建了一个论坛网站,用户可以在其中 post Questions/Answers 和编辑它们。
编辑回复后,我想将用户重定向到当前编辑的 post 页面。就像用户
编辑已对 ID 为 4 的问题进行 post 编辑的回复(url 为 (http://127.0.0.1:8000/discussion/4)),然后在编辑后应重定向到相同的 URL。编辑并删除回复后,我将用户重定向到论坛主页,但我想重定向到 /discussion/{post_id}
URL(即特定 post 上的 URL正在编辑和删除的回复)
urls.py
app_name = "dashboard"
urlpatterns = [
path('', views.index, name="index"),
path('user_home', views.user_home, name="user_home"),
path('admin_home', views.admin_home, name="admin_home"),
path("forum", views.forum, name="forum"),
path("discussion/<int:myid>", views.discussion, name="discussion"),
path("showallusers", views.show_all_users, name="showallusers"),
path('delete_user/<int:pk>', views.delete_user, name="delete_user"),
path('delete_post/<int:pk>', views.delete_post, name="delete_post"),
path('delete_reply/<int:pk>', views.delete_reply, name="delete_reply"),
path('upload_notes', views.upload_notes, name='upload_notes'),
path('view_mynotes', views.view_mynotes, name='view_mynotes'),
path('delete_mynotes/<int:pk>/', views.delete_mynotes, `name='delete_mynotes'), `
path('pending_notes', views.pending_notes, name='pending_notes'),
path('assign_status/<int:pk>', views.assign_status, name='assign_status'),
path('accepted_notes', views.accepted_notes, name='accepted_notes'),
path('rejected_notes', views.rejected_notes, name='rejected_notes'),
path('all_notes', views.all_notes, name='all_notes'),
path('delete_notes/<int:pk>', views.delete_notes, name='delete_notes'),
path('delete-records/', views.delete_notes, name='delete_notes'),
path('view_allnotes', views.view_allnotes, name='view_allnotes'),
path('notessharing', views.notessharing, name='notessharing'),
path('edit_post/<int:pk>/', views.edit_post, name='edit_post'),
path('edit_reply/<int:pk>/', views.edit_reply, name='edit_reply'),
]
delete_reply代码
def delete_reply(request, pk=None):
reply = Replie.objects.filter(id=pk)
reply.delete()
return redirect('/forum')
删除 post 的回复后,我想重定向到同一个 post。
models.py
class Post(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
post_id = models.AutoField
post_content = models.TextField(max_length=5000,verbose_name="")
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
class Replie(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=1)
reply_id = models.AutoField
reply_content = models.TextField(max_length=5000,verbose_name="")
post = models.ForeignKey(Post, on_delete=models.CASCADE, default='')
timestamp= models.DateTimeField(default=now)
image = models.ImageField(upload_to="images",default="")
def __str__(self):
return f'{self.user1} Post'
views.py
def forum(request):
user = request.user
profile = Profile.objects.all()
if request.method=="POST":
form=PostContent(request.POST)
if form.is_valid():
user = request.user
image = request.user.profile.image
content = request.POST.get('post_content','')
post = Post(user1=user, post_content=content, image=image)
post.save()
messages.success(request, f'Your Question has been posted successfully!!')
return redirect('/forum')
else:
form=PostContent()
posts = Post.objects.filter().order_by('-timestamp')
form= PostContent()
context={
'posts':posts,
'form':form
}
return render(request, "forum.html",context)
def discussion(request, myid):
post = Post.objects.filter(id=myid).first()
replies = Replie.objects.filter(post=post)
if request.method=="POST":
form=ReplyContent(request.POST)
if form.is_valid():
user = request.user
image = request.user.profile.image
desc = request.POST.get('reply_content','')
post_id =request.POST.get('post_id','')
reply = Replie(user = user, reply_content = desc, post=post, image=image)
reply.save()
messages.success(request, f'Your Reply has been posted successfully!!')
return redirect(f'/discussion/{post_id}')
else:
form=ReplyContent()
form= ReplyContent()
return render(request, "discussion.html", {'post':post, 'replies':replies,'form':form})
def edit_reply(request, pk):
reply = Replie.objects.get(id=pk)
if request.method == 'POST':
form = UpdateReplyForm(request.POST, instance=reply)
if form.is_valid():
form.save()
messages.success(request,"Reply updated successfully!")
return redirect('/forum')
else:
form = UpdateReplyForm(instance=reply)
context = {
'form': form
}
return render(request, 'edit_reply.html', context)
edit_post 查看
def edit_post(request, pk):
post = Post.objects.get(id=pk)
if request.method == 'POST':
form = UpdatePostForm(request.POST, instance=post)
if form.is_valid():
form.save()
messages.success(request, "Post updated successfully!")
return redirect('/forum')
else:
form = UpdatePostForm(instance=post)
context = {
'form': form
}
return render(request, 'edit_post.html', context)
目前,在编辑回复后,我将用户重定向到 post 主页,但我想重定向到 /discussion/{post_id}
。
模板代码: edit_reply.html
{% load static %}
{% block body %}
{% load crispy_forms_tags %}
<div class="container ">
<form method="POST">
<div class="form-group">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4 mt-4 f2" >Update Reply</legend>
</fieldset>
<label style="font-size:1rem; font-weight:bold;">Reply Content</label>
{{form|crispy}}
<input type="hidden" name="post_id" value="{{post_id}}">
<div class="form-group">
<button href="" class="btn btn-primary" type="Update">
Update
</button>
</div>
</div>
</form>
</div>
{% endblock body %}
您可以通过在 edit_reply
视图中传递 args=[reply.post.id]
将其重定向到带有 pk
的 discussion
视图。
试试这个: views.py
from django.shortcuts import render, redirect from django.urls import reverse def edit_reply(request, pk): reply = Replie.objects.get(id=pk) if request.method == 'POST': form = UpdateReplyForm(request.POST, instance=reply) if form.is_valid(): form.save() messages.success(request, "Reply updated successfully!") return redirect(reverse('dashboard:discussion', args=[reply.post.id])) else: form = UpdateReplyForm(instance=reply) context = { 'form': form } return render(request, 'home/edit_reply.html', context)
Note:
Forms in django requiredForm
to be the suffix, so it will be better if it changed toPostContentForm
andReplyContentForm
fromPostContent
andReplyContent
respectively.
一定是
return f'{self.user} Post'不是
return f'{self.user`} Post'
因为它不是 Replie
模型中的任何字段。
Note:
ForeignKey's names are generally written in its own name and that too insnake_case
, it will be better if you changeuser1
touser
inPost
model.
为了更好地理解:
如果 table 名称是 PizzaTopingCategory
那么在创建 ForeignKey 时你应该将其命名为
pizza_toping_category=models.ForeignKey(PizzaTopingCategory, on_delete=models.CASCADE)
编辑:
你需要找到post_id
,所以你可以通过:
在 delte_reply
视图中试试这个:
def delete_reply(request, pk=None):
reply = Replie.objects.filter(id=pk)
reply_instance = get_object_or_404(Replie,id=pk)
post_pk=reply_instance.post.id
reply.delete()
return redirect(reverse('dashboard:discussion', args=[post_pk]))
为了在 discussion
视图中传递 pk
,您应该在 edit_post
视图中编写 return redirect(reverse('dashboard:discussion', args=[reply.post.id]))
:
views.py
def edit_post(request, pk): post = Post.objects.get(id=pk) if request.method == 'POST': form = UpdatePostForm(request.POST, instance=post) if form.is_valid(): form.save() messages.success(request, "Post updated successfully!") return redirect(reverse('dashboard:discussion', args=[post.id])) else: form = UpdatePostForm(instance=post) context = { 'form': form } return render(request, 'home/edit_post.html', context)