P
P
Pennyw1se2018-02-04 16:12:56
Django
Pennyw1se, 2018-02-04 16:12:56

How to use slug in django?

#admin.py

from django.views import generic

from .models import Post, Guide


class IndexView(generic.ListView):
    template_name = 'alpha/index.html'
    context_object_name = 'latest_post_list'

    def get_queryset(self):
        return Post.objects.order_by('-pub_date')[:15]

#models.py
from django.db import models


class Post(models.Model):
    title = models.CharField(verbose_name='Заголовок', max_length=60)
    text = models.TextField(verbose_name='Текст')
    description = models.CharField(verbose_name='Описание', max_length=100)
    pub_date = models.DateTimeField(verbose_name='Дата публикации', auto_now_add=True)
    slug = models.SlugField(verbose_name='URL', max_length=50, unique=True,)
    image = models.ImageField(verbose_name='Картинка', upload_to='images/%Y/%m/%d')

    def __str__(self):
        return self.title

#urls.py
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static

app_name = 'alpha'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('guides/', views.GuidesView.as_view(), name='guides'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

==============
How should the slug be defined in these files ? In the documentation I found only about admin.py

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2018-02-04
@Pennyw1se

urlpatterns = [
    ...
    path('<slug>/$', views.DetailView.as_view(), name='detail'),
    ...
]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question