简体   繁体   English

在Django中,提交新表单时,如何重定向到提交?

[英]In django, when submitting a new form, how do i redirect to the submission?

The form is submitting a blog post and redirecting towards the index page when submitted. 该表单正在提交博客文章,并在提交时重定向到索引页面。

How do I change it so that it redirects to the newly submitted blog post 如何更改它,以便将其重定向到新提交的博客文章

views.py views.py

def post(request, post_url):
    single_post = get_object_or_404(Post, title=post_url.replace('_', ' '))
    popular_posts = Post.objects.order_by('-views')[:5]
    single_post.views+=1
    single_post.save()
    t=loader.get_template('blog/post.html')
    c = Context({'single_post': single_post, "popular_posts":popular_posts, })
    return HttpResponse(t.render(c))

def add_post(request):
context = RequestContext(request)
if request.method =='POST':
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        form.save(commit=True)
        return redirect(index)
    else:
        print form.errors
else:
    form = PostForm()
return render_to_response('blog/add_post.html', {'form':form}, context)

Check the get_absolute_url method for django model objects 检查Django模型对象的get_absolute_url方法

def add_post(request):
    context = RequestContext(request)
    if request.method =='POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=True)
            return redirect(form.instance.get_absolute_url())
        else:
            print form.errors
    else:
        form = PostForm()

     return render_to_response('blog/add_post.html', {'form':form}, context)

considering you have a blog post url in form of : 考虑到您有以下形式的博客文章网址:

url(r'^blog/(?P<blog_id>[0-9]{4})/$', views.blog_detail, name='blog_detail'),

then, 然后,

 def add_post(request):
    context = RequestContext(request)
    if request.method =='POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=True)
            return HttpResponseRedirect(reverse('blog_detail', obj.id))
        else:
            print form.errors
    else:
        form = PostForm()
    return render_to_response('blog/add_post.html', {'form':form}, context)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM