我试图让索引视图显示一个" Journal" s列表,每个链接到列出" Manuscripts"在期刊上。我还希望journal_view
位于期刊名称的slug中,同样适用于manuscript_view
。
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/journals/
Django Version: 2.0.3
Python Version: 3.6.4
Installed Applications:
['social_django',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'journal.apps.JournalConfig']
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 ... error at line 8
Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or pattern name.
1 : {% load static %}
2 :
3 : <link rel="stylesheet" type="text/css" href="{% static 'journal/style.css' %}" />
4 :
5 : {% if journal_list %}
6 : <ul>
7 : {% for journal in journal_list %}
8 : <li><a href=" {% url journal.get_absolute_url journal.slug %} ">{{ journal.title }}</a></li>
9 : {% endfor %}
10 : </ul>
11 : {% else %}
12 : <p>No journals are available.</p>
13 : {% endif %}
# ...(Traceback)...
Exception Type: NoReverseMatch at /journals/
Exception Value: Reverse for 'view_journal' not found. 'view_journal' is not a valid view function or pattern name.
class Journal(models.Model):
title = models.CharField(max_length=100, unique=True)
slug = models.SlugField(unique=True)
# blah blah
def __str__(self):
return self.title
def get_absolute_url(self, *args, **kwargs):
return reverse("view_journal", kwargs={"slug": self.slug})
class IndexView(generic.ListView):
template_name = 'journal/index.html'
context_object_name = 'journal_list'
def get_queryset(self):
return Journal.objects.all()
class JournalView(generic.ListView):
template_name = 'journal/journal.html'
context_object_name = 'latest_article_list'
def get_queryset(self):
return Manuscript.objects.filter(
pub_date__lte=timezone.now()
).order_by('-pub_date')[:5]
app_name = 'journal'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<slug>/', views.JournalView.as_view(), name='view_journal'),
path('<slug>/', views.ArticleView.as_view(), name='view_manuscript'), ]
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('journals/', include('journal.urls')),
path('social/', include('social.apps.django_app.urls', namespace='social')),
]
答案 0 :(得分:0)
我以这种方式工作:
我首先在我的模型中定义了一个slug字段,正如你所做的那样:
greater<int>
然后在我的views.py中我添加了这个:
slug = models.SlugField(max_length=20, unique=True)
最后用这种方式写了我的路径:
slug_url_kwarg = 'slug'