I have created a forum website in Django where users can post Questions/Answers and edit them.
After editing the reply I want to redirect the user to the currently edited post page. like if user
edit reply which has been posted on the question with id 4 (which url is (http://127.0.0.1:8000/discussion/4)) then after edited it should redirect to the same URL. After editing, and deleting the reply I am redirecting the user to the forum homepage but I want to redirect to the /discussion/{post_id}
URL(which is URL of the particular post on which reply being edited and deleted)
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 code
def delete_reply(request, pk=None):
reply = Replie.objects.filter(id=pk)
reply.delete()
return redirect('/forum')
After deleting a reply from a post I want to redirect to the same 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 view
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)
Currently, after editing the reply, I am redirecting the user to the post home page but I want to redirect to /discussion/{post_id}
.
Template code: edit_reply.html
{% load static %}
{% block body %}
{% load crispy_forms_tags %}
<div >
<form method="POST">
<div >
{% csrf_token %}
<fieldset >
<legend >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 >
<button href="" type="Update">
Update
</button>
</div>
</div>
</form>
</div>
{% endblock body %}
CodePudding user response:
You can redirect it to discussion
view with its pk
by passing args=[reply.post.id]
in edit_reply
view.
Try this: 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.
It must be
return f'{self.user} Post'not
return f'{self.user`} Post'
As it is not any field in Replie
model.
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.
For better understanding:
If table name is PizzaTopingCategory
so while creating ForeignKey you should name it as
pizza_toping_category=models.ForeignKey(PizzaTopingCategory, on_delete=models.CASCADE)
Edit:
You need to find out post_id
, so you can send it through:
Try this in the delte_reply
view:
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]))