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

时间:2017-10-15 01:32:45

标签: python django django-views url-redirection django-urls

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

这是我的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>

1 个答案:

答案 0 :(得分:1)

您的网址期待一个slug值作为参数。你需要在重定向而不是pk中传递帖子的标题slug。 尝试:

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

我假设您的slug字段为post.slug