我正在按照教程执行以下操作:
<a href="{ % url 'films:add_comment' slug=film.slug %}">Leave a comment</a>
他们使用slu ..我没有这样做,但一直在引用ID。我认为我的代码部分对此非常重要:
膜/ urls.py:
from django.conf.urls import url
from django.urls import path
from . import views
app_name = 'films'
urlpatterns = [
path('', views.index, name='index'),
url(r'^films/<int:film_id>/comment/', views.add_comment, name='add_comment'),
path('films/<int:film_id>/', views.detail, name='detail'),
]
膜/ views.py
def add_comment(request, film_id):
film = get_object_or_404(Film, pk=film_id)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit = False)
comment.post = post
comment.save()
return redirect('film:detail',film)
else:
form = CommentForm()
template = 'films/add_comment.html'
context = {'form':form}
return render (request,template,context)
的mysite / urls.py:
urlpatterns = [
url(r'^accounts/',include('accounts.urls')),
url(r'^', include('films.urls')),
url(r'^admin/', admin.site.urls),
]
add_comment.html:
{% extends 'base_layout.html' %}
{% block content %}
<div class="create-comment">
<h2>Add Comment</h2>
</div>
{% endblock %}
如果点击我制作的链接:<a href="{ % url 'films:add_comment' film.id %}">Leave a comment</a>
如果我手动将网址更改为
我明白了:
但看起来该列表中的网址3与我输入的内容相匹配?
答案 0 :(得分:2)
(最终工作编辑)
膜/ urls.py
urlpatterns = [
path('', views.index, name='index'),
path('<int:film_id>/comment', views.add_comment, name='add_comment'),
path('<int:film_id>', views.detail, name='detail'),
]
的mysite / urls.py
urlpatterns = [
url('films/', include('films.urls')),
url('accounts/',include('accounts.urls')),
url('admin/', admin.site.urls),
]
(锻炼)
膜/ urls.py:
app_name = 'films'
urlpatterns = [
url(r'^films/(?P<film_id>\d+)/comment/', views.add_comment, name='add_comment'),
]
注意:(?P<film_id>\d+)
了解如何捕获正确的标识符
这是不正确的:
<a href="{ % url 'films:add_comment' film.id %}">Leave a comment</a>
应该是:
<a href="{% url 'films:add_comment' film_id=film.id %}">Leave a comment</a>
{%
你的def add_comment(request, film_id):
让我感到困惑,但请给我一些建议。然后评论发生的任何问题,我们将解决这个问题!
编辑:好的下一个可能阻碍你的迷你错误
urlpatterns = [
path(r'^$', views.index, name='index'),
path(r'^films/<int:film_id>/comment/$', views.add_comment, name='add_comment'),
path(r'^films/<int:film_id>/$', views.detail, name='detail'),
]
'foo'
- &gt; r'foo'
path( )
来使用酷<int:film_id>
语法。 url()
不会伤心地☹️films/2/comment
与films/2/