Reputation: 243
I've created a form and view in Django. I can see the add new post form when I go to http://localhost:8000/post/new/ but after I complete all required fields and click submit the page just refreshes itself and I am not redirected to the post details page.
Here's my 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)
Here's my 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'),
]
Here's my 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>
Upvotes: 0
Views: 1253
Reputation: 946
Your url is expecting a slug value as argument. You need to pass the title slug of the post in redirect instead of pk. Try:
return redirect('posts:post_detail', post_title_slug=post.slug)
I assumed your slug field as post.slug
Upvotes: 1