[英]Django view does not redirect to details page
我在 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>
您的網址需要一個 slug 值作為參數。 您需要在重定向而不是 pk 中傳遞帖子的標題段。 嘗試:
return redirect('posts:post_detail', post_title_slug=post.slug)
我假設你的 slug 字段為 post.slug
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.