【问题标题】:Django view does not redirect to details pageDjango 视图不会重定向到详细信息页面
【发布时间】:2018-03-26 19:52:37
【问题描述】:

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

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

【问题讨论】:

  • 您的帖子创建没有问题吗?
  • 不幸的是,帖子也没有在数据库中创建
  • 如果未创建帖子 - 看起来表单无效。我建议完全打印form.errors,看看有什么问题或遗漏。

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


【解决方案1】:

您的网址需要一个 slug 值作为参数。您需要在 redirect 而不是 pk 中传递帖子的标题 slug。 试试:

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

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

【讨论】:

  • 我已经把重定向改成了这个,结果还是一样
  • 您的表单似乎无效。尝试在模板中的任意位置添加 {{ form.errors }},然后再次尝试提交表单。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多