我的第一个问题,我刚刚开始学习Python,但最近遇到了一个问题,也许问题会很简单,但我花了三天时间找不到解决方案,
这是追溯,
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/post_detail/12/
Django Version: 2.0.4
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blogs']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Template error:
In template /home/am/Documents/PycharmProjects/practice/19.1_Blog/blogs/templates/blogs/base.html, error at line 0
Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>\\d+)/']
1 : <p>
2 : <a href="{% url 'blogs:index' %}">My blogs</a> -
3 :
4 : <a href="{% url 'blogs:all_post' %}">All Post</a>
5 : </p>
6 :
7 : {% block content %}
8 :
9 : {% endblock content %}
Traceback:
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/blogs/views.py" in post_detail
32. return render(request, 'blogs/post_detail.html', context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/shortcuts.py" in render
36. content = loader.render_to_string(template_name, context, request, using=using)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/loader.py" in render_to_string
62. return template.render(context, request)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/backends/django.py" in render
61. return self.template.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render
175. return self._render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/loader_tags.py" in render
155. return compiled_parent._render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in _render
167. return self.nodelist.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/loader_tags.py" in render
67. result = block.nodelist.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render
943. bit = node.render_annotated(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/base.py" in render_annotated
910. return self.render(context)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/template/defaulttags.py" in render
447. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/urls/base.py" in reverse
88. return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/home/am/Documents/PycharmProjects/practice/19.1_Blog/11_bg/lib/python3.5/site-packages/django/urls/resolvers.py" in _reverse_with_prefix
632. raise NoReverseMatch(msg)
Exception Type: NoReverseMatch at /post_detail/12/
Exception Value: Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>\\d+)/']
这是我的urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# home page
url(r'^$', views.index, name='index'),
# show all post
url(r'^all_post/$', views.all_post, name='all_post'),
# show post deatil
url(r'^post_detail/(?P<post_id>\d+)/$', views.post_detail, name='post_detail'),
# add new post
url(r'^new_post/$', views.new_post, name='new_post'),
# edit post
url(r'^edit_post/(?P<post_id>\d+)/', views.edit_post, name='edit_post'),
]
views.py
from django.shortcuts import render
from .models import BlogPost
from django.http import HttpResponseRedirect
from django.urls import reverse
from .forms import PostForm
def index(request):
"""psot home page"""
return render(request, 'blogs/index.html')
def all_post(request):
"""show all post"""
all_post = BlogPost.objects.order_by('-date_added')
context = {'all_post': all_post}
return render(request, 'blogs/all_post.html', context)
def post_detail(request, post_id):
"""show post detail"""
p_id = BlogPost.objects.get(id=post_id)
post_date = p_id.date_added
post_title = p_id.title
post_text = p_id.text
# print(post)
# all_post = BlogPost.objects.order_by('-date_added')
# post_detail = post_title.entry_set.order_by('-date_added')
# post_detail = BlogPost.objects.order_by('-date_added')
# post_detail = post_title.text
context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text}
return render(request, 'blogs/post_detail.html', context)
def new_post(request):
"""add new post"""
if request.method != 'POST':
form = PostForm()
else:
form = PostForm(data=request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.save()
return HttpResponseRedirect(reverse('blogs:all_post'))
context = {'form': form}
return render(request, 'blogs/new_post.html', context)
def edit_post(request, post_id):
"""edit post"""
e_post = BlogPost.objects.get(id=post_id)
# title = edit_id.title
# text = edit_id.text
if request.method != 'POST':
form = PostForm(instance=e_post)
else:
form = PostForm(instance=e_post, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('blogs:post_detail', args=[post_id]))
# return HttpResponseRedirect(reverse('blogs:post_detail', args=[post_id]))
# context = {'edit_id': edit_id, 'title': title, 'text': text, 'form': form}
context = {'e_post': e_post, 'post_id': post_id, 'form': form}
# context = {'post_id': post_id, 'form': form}
return render(request, 'blogs/edit_post.html', context)
edit_post.html
{% extends 'blogs/base.html' %}
{% block content %}
<p>Edit post:</p>
<form action="{% url 'blogs:edit_post' post_id %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">save changes</button>
</form>
{% endblock content %}
formss.py
from django import forms
from .models import BlogPost
class PostForm(forms.ModelForm):
# class title:
# model = BlogPost
# title = ['text']
# labels = {'text': ''}
class Meta:
model = BlogPost
# title = ['text']
fields = ['title', 'text']
labels = {'text': ''}
widgets = {'text': forms.Textarea(attrs={'cols': 80})}
post_detail.html
{% extends 'blogs/base.html' %}
{% block content %}
<p>Title:{{ p_id.title }}</p>
<p>Edit post</p>
<p><a href="{% url 'blogs:edit_post' post_id %}">Edit post</a></p>
<ul>
<li>
<p>Time:{{ p_id.date_added|date:'M d, Y H:i' }}</p>
<p>Post:{{ p_id.text|linebreaks }}</p>
</li>
</ul>
{% endblock content %}
现在我想实现一个编辑我的博客文章的功能,但我尝试了很多次,我根本没有找到问题。 我认为问题出现在edit_post网址中,但我无法找到问题所在。谢谢你的帮助。
答案 0 :(得分:2)
您未在模板上下文中包含post_id
:
def post_detail(request, post_id):
context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text}
return render(request, 'blogs/post_detail.html', context)
因此,以下网址标记不起作用。
<a href="{% url 'blogs:edit_post' post_id %}">Edit post</a>
您可以通过将post_id
添加到上下文中来解决此问题:
def post_detail(request, post_id):
...
post_id = p_id.id
context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text, 'post_id': post_id}
return render(request, 'blogs/post_detail.html', context)
但是,不需要单独包含所有字段。只需在模板中包含帖子即可。
def post_detail(request, post_id):
post = BlogPost.objects.get(id=post_id)
context = {'post': post}
return render(request, 'blogs/post_detail.html', context)
请注意,我已将变量名称从p_id
更改为post
,因为它是模型实例,而不是ID。
然后在模板中,您可以访问post
:
<p>Title:{{ post.title }}</p>
<p>Edit post</p>
<p><a href="{% url 'blogs:edit_post' post.id %}">Edit post</a></p>
<ul>
<li>
<p>Time:{{ post.date_added|date:'M d, Y H:i' }}</p>
<p>Post:{{ post.text|linebreaks }}</p>
</li>
</ul>
答案 1 :(得分:0)
在post_detail视图中,您将此上下文发送到模板
context = {'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text}
然后在post_detail.html中,您尝试发送一个名为'post_id'的变量,该变量对于URL不存在:
<p><a href="{% url 'blogs:edit_post' post_id %}">Edit post</a></p>
将post_id添加到您的上下文中,这应该可以正常工作
context = {'post_id': post_id, 'p_id': p_id, 'post_date': post_date, 'post_title': post_title, 'post_text': post_text}