Home > Net >  DetailView in Django, keyword 'slug'
DetailView in Django, keyword 'slug'

Time:12-11

I recently started learning Django. I want to display one news item, but when I open on the link I get an error message:

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})

What am I doing wrong?

CodePudding user response:

First of all do not call your slug "NewSlug" with uppercase but all lower case "newslug" or even better "new_slug", the name itself should be more descriptive as well.

Finally you need to tell your view which field to use, you can define that with the following attribute :

slug_field = "NewSlug"

Note : Attribute of a class should not be camel case but snake case

  • Related