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>
としてあなたslugフィールドを想定し、問題なく作成したばかりあなたのポストですか? –
残念ながら、投稿はdbでも作成されません – MaxRah
投稿が作成されていない場合、フォームが有効ではないようです。 'form.errors'を完全に表示して、何が間違っているか見当がつかないかを確認することをお勧めします。 – Igor