Django 中的 DetailView,关键字 'slug'
DetailView in Django, keyword 'slug'
我最近开始学习 Django。我想显示一条新闻,但是当我打开 link 时,我收到一条错误消息:
Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug
Request Method: GET
Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/
Django Version: 4.0
Exception Type: FieldError
views.py
from django.views.generic import DetailView
from .models import News
class GetNews(DetailView):
model = News
slug_url_kwarg = 'NewsSlug'
template_name = 'news/single_news.html'
context_object_name = 'single_news'
allow_empty = False
urls.py
from django.urls import path
from .views import GetNews
urlpatterns = [
path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'),
]
models.py
from django.db import models
from django.urls import reverse_lazy
class News(models.Model):
NewsTitles = models.CharField(max_length=120)
NewsContent = models.TextField(max_length=255)
NewsSlug = models.SlugField(max_length=255)
def __str__(self):
return self.NewsTitles
def get_absolute_url(self):
return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug})
我做错了什么?
首先,不要用大写而是小写“newslug”或更好的“new_slug”来称呼您的 slug“NewSlug”,名称本身也应该更具描述性。
最后您需要告诉您的视图要使用哪个字段,您可以使用以下属性来定义它:
slug_field = "NewSlug"
注意 : class 的属性不应该是驼峰而是蛇形
我最近开始学习 Django。我想显示一条新闻,但是当我打开 link 时,我收到一条错误消息:
Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug
Request Method: GET
Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/
Django Version: 4.0
Exception Type: FieldError
views.py
from django.views.generic import DetailView
from .models import News
class GetNews(DetailView):
model = News
slug_url_kwarg = 'NewsSlug'
template_name = 'news/single_news.html'
context_object_name = 'single_news'
allow_empty = False
urls.py
from django.urls import path
from .views import GetNews
urlpatterns = [
path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'),
]
models.py
from django.db import models
from django.urls import reverse_lazy
class News(models.Model):
NewsTitles = models.CharField(max_length=120)
NewsContent = models.TextField(max_length=255)
NewsSlug = models.SlugField(max_length=255)
def __str__(self):
return self.NewsTitles
def get_absolute_url(self):
return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug})
我做错了什么?
首先,不要用大写而是小写“newslug”或更好的“new_slug”来称呼您的 slug“NewSlug”,名称本身也应该更具描述性。
最后您需要告诉您的视图要使用哪个字段,您可以使用以下属性来定义它:
slug_field = "NewSlug"
注意 : class 的属性不应该是驼峰而是蛇形