Django视图不会重定向到详细信息页面

问题描述:

我已经在Django中创建了一个表单和视图。当我访问http://localhost:8000/post/new/时,我可以看到添加新帖子的表单,但是在完成所有必填字段并单击提交后,页面只是刷新自己,而我没有重定向到帖子详细信息页面。Django视图不会重定向到详细信息页面

这里是我的views.py

def post_new(request): 
    if request.method == "POST": 
     form = PostForm(request.POST, request.FILES) 
     if form.is_valid(): 
      post = form.save(commit=False) 
      post.createdAt = timezone.now() 
      post.writer = request.user 
      post.save() 
      return redirect('posts:post_detail', pk=post.pk) 
    else: 
     form = PostForm() 
    context = {'form':form} 
    return render(request,"posts/post_new.html",context) 

这里是我的urls.py:

urlpatterns = [ 
    url(r'^$', views.post_list, name="post_list"), 
    url(r'^posts/(?P<post_title_slug>[\w\-]+)/$', views.post_detail, name='post_detail'), 
    url(r'^post/new/$', views.post_new, name='post_new'), 
] 

这里是我的html:

<div class="col"> 
<form method='POST' class='post_form' enctype='multipart/form-data'> 
    {% csrf_token %} 
    {{ form.non_field_errors }} 
    <div class="form-row"> 
    <div class="form-group col-md-6"> 
     <label for="{{ form.title.id_for_label }}" class="col-form-label">Title</label> 
     <input type="text" class="form-control" id="{{ form.title.id_for_label }}" name= "{{ form.title.html_name }}" placeholder="Enter post title"> 
     {{ form.title.errors }} 
    </div> 
    </div> 
    <div class="form-group"> 
    <label for="{{ form.comment.id_for_label }}">Description here:</label> 
    <textarea class="form-control" rows="5" id="{{ form.comment.id_for_label }}" name="{{ form.comment.html_name }}" aria-describedby="descriptionHelpBlock"></textarea> 
    <small id="descriptionHelpBlock" class="form-text text-muted"> 
     Describe your post in this text box. 
    </small> 
    {{ form.comment.errors }} 
    </div> 

    <div class="form-group"> 
    <label for="{{ form.image.id_for_label }}">Upload picture here</label> 
    <input type="file" id="{{ form.image.id_for_label }}" name="{{ form.image.html_name }}" class="form-control-file"> 
    {{ form.image.errors }} 
    </div> 
    <br> 
    <button type="submit" class="btn btn-info">Post</button> 
</form> 

+0

是您的帖子得到没有问题的产生? –

+0

不幸的是帖子没有在db中创建 – MaxRah

+0

如果没有创建帖子 - 它看起来像表单无效。我建议完整地打印form.errors以查看错误或缺失。 – Igor

您的网址是期待一个塞价值作为论据。您需要通过重定向而不是pk的帖子标题slu pass。 尝试:

return redirect('posts:post_detail', post_title_slug=post.slug) 

我假定你塞字段post.slug

+0

我已将此重定向改为此效果,结果仍然相同 – MaxRah

+0

似乎您的表单无效。尝试在模板内的任意位置添加** {{form.errors}} **,然后再次尝试提交表单。 –