我正在浏览Django教程并在尝试编辑我的博客应用中的帖子时收到此错误。我使用Django版本:2.0.6和Python版本: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'),
]
导致第3行出错的模板 - edit_post.html。错误消息突出显示{%url&#39; edit_post&#39; 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 %}
带有edit_post.html
链接的模板(index.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']
问题
当我点击索引页面上的编辑帖子链接时,我收到上述错误。使用这种方法创建新帖子可以完美地工作,但编辑却没有。 我坚持这个问题,不知道出了什么问题。
我尝试了什么
感谢任何帮助。提前谢谢!
答案 0 :(得分:3)
blog/edit_post.html
的post.id
中的
<form action="{% url 'edit_post' post.id %}" method='post'>
...
</form>
但在views.py
中,您未将post
变量传递给context
变量
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)