Reputation: 1487
def view_post(request, post_id):
"""Display a blog post"""
blogpost = BlogPost.objects.get(id=post_id)
context = {'blogpost': blogpost}
return render(request, 'blogs/blogpost.html', context)
def new_post(request):
"""Create a new blog post"""
if request.method != 'POST':
# No data submitted; create a blank form.
form = BlogPostForm()
else:
# POST data submitted; process data.
form = BlogPostForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('blogs:index')
# Display a blank or invalid form.
context = {'form': form}
return render(request, 'blogs/new_post.html', context)
def edit_post(request, post_id):
blogpost = BlogPost.objects.get(id=post_id)
if request.method != 'POST':
# Initial request; pre-fill form with current blogpost.
form = BlogPostForm(instance=blogpost)
else:
# POST data submitted; process data.
form = BlogPostForm(instance=blogpost, data=request.POST)
if form.is_valid():
form.save()
view_post(request,post_id)
# Display form with original contents
context = {'blogpost': blogpost,'form': form}
return render(request, 'blogs/edit_post.html', context)
The code above is for a blog site where users can create, edit, and view blog-posts. Edit_post should process a user's edited post, and then redirect to the post that has been edited. Redirect doesn't allow data to be sent to my knowledge, so I tried to nest a function to no avail.
I've seen online that cookies / messages may be a solution. If so, how might I implement it?
EDIT: I've added
print("DEBUG returning HttpResponseRedirect of reverse of view_post")
return HttpResponseRedirect(reverse(view_post, args=[post_id]))
to the end of the else for edit_post, replacing the previous view_post attempt at a redirect. After submitting post data, however, I receive the error NoReverseMatch at /post/edit_post/1/
Upvotes: 0
Views: 672
Reputation: 1487
https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
I found that it does take parameters. The following code achieves what I needed:
return redirect('blogs:view_post', post_id=post_id)
blogs:view_function
was needed for the reverse to work.
Upvotes: 0
Reputation: 1090
Redirect doesn't allow data to be sent to my knowledge, so I tried to nest a function to no avail.
If after edit you want to be redirected to detail view of Post
, you can just use HttpResponseRedirect
object and reverse
function. For example:
return HttpResponseRedirect(reverse(view_post, args=[post_id]))
Upvotes: 1