I am going through a Django tutorial and getting this error when trying to edit posts in my blog app. I use Django Version: 2.0.6 and Python Version: 3.6.5.
models.py
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=100)
text = models.TextField()
def __str__(self):
return self.title
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^new_post/', views.new_post, name='new_post'),
url(r'^edit_post/(?P<post_id>\d+)/$', views.edit_post, name='edit_post'),
]
A template that causes the error in line 3 - edit_post.html. The error message highlights {% url 'edit_post' post.id %}
{% block content %}
<form action="{% url 'edit_post' post.id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">save changes</button>
</form>
{% endblock content %}
A template (index.html) with a link to edit_post.html
{% block content %}
<form action="{% url 'new_post' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Make a new post</button>
</form>
<ul>
{% for post in posts %}
<li>
{{ post.id }} - {{ post.title }}
<p>{{ post.text }}</p>
<a href="{% url 'edit_post' post.id %}">edit post</a>
</li>
{% empty %}
<li>No posts have been added yet.</li>
{% endfor %}
</ul>
{% endblock content %}
views.py
def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
text = post.text
title = post.title
if request.method != 'POST':
form = BlogForm(instance=post)
else:
form = BlogForm(instance=post, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('index'))
context = {'title': title, 'text': text, 'form': form}
return render(request, 'blog/edit_post.html', context)
forms.py
from django import forms
from .models import BlogPost
class BlogForm(forms.ModelForm):
class Meta:
model = BlogPost
fields = ['title', 'text']
The problem
When I click edit post link on index page, I get the aforementioned error. Creating a new post using this approach works flawlessly but editing does not. I am stuck with this problem and have no idea what is wrong.
What I have tried
Any help is appreciated. Thank you in advance!
in your blog/edit_post.html
you use post.id
<form action="{% url 'edit_post' post.id %}" method='post'>
...
</form>
but in views.py
you don't pass post
variable to context
variable
def edit_post(request, post_id):
post = BlogPost.objects.get(id=post_id)
...
context = {
'title': title,
'text': text,
'form': form,
'post': post # here
}
return render(request, 'blog/edit_post.html', context)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With