Django Slug + ID URL: Dev.to의 URL 패턴 복사

내가 좋아하는 것 중 하나는 URL 디자인입니다. 고유성을 보장하기 위해 일종의 인덱스 값의 내부 대표를 나타내는 해시 값과 슬러그를 결합합니다. URL ""에 포함된 내 게시물 "자동 문서화 Makefiles"에서 그 예를 볼 수 있습니다.

해당 URL을 분해해 보겠습니다.
  • feldroy는 제 회사 이름입니다.
  • autodocumenting-makefiles는 슬러그이며 기사 제목을 기반으로 합니다.
  • 175b는 인덱스 문자 필드에 저장되거나 라우터에 의해 숫자 기본 키로 분류되는 해시 값입니다.

  • URL 디자인을 보는 또 다른 방법은 다음과 같습니다.

    /<org-or-username>/<slugified-title>/<hashed-id>
    


    Django를 사용하여 이 기술의 단순화된 버전을 구현하는 방법을 살펴보겠습니다.

    URL 버전



    Dev.to 구현의 더 간단한 버전을 사용할 것입니다. 우리의 구현은 데이터베이스 기본 키를 사용하여 Dev.to에 의존하는 해시 값 대신 고유성을 보장합니다.

    /<username>/<slugified-title>/<primary-key>/
    


    자, 이제 URL 디자인을 결정했으므로 구축해 봅시다!

    모델



    데이터를 저장하세요!

    # articles/models.py
    from django.conf import settings
    from django.db import models
    from django.utils.translation import gettext_lazy as _
    
    class Article(models.Model):
    
        title = models.CharField(_("Title"), max_length=100)
        slug = models.CharField(_("Slug"), max_length=100)
        author = models.ForeignKey(settings.AUTH_USER_MODEL, 
            on_delete=models.CASCADE)
        # More fields...
    


    양식



    데이터를 수집하고 검증하십시오!

    # articles/forms.py
    from django import forms
    
    from .models import Article
    
    class ArticleForm(forms.ModelForm):
    
        class Meta:
            model = Article
            fields = ('title', ) # more fields
    


    관점들



    이제 모델과 양식이 있으므로 뷰를 빌드해 보겠습니다.

    # articles/views.py
    from django.shortcuts import get_object_or_404
    from django.contrib.auth.mixins import LoginRequiredMixin
    from django.utils import slugify
    from django.views.generic import CreateView, DetailView, UpdateView
    
    from .forms import ArticleForm
    from .models import Article
    
    
    class ArticleCreateView(LoginRequiredMixin, CreateView):
    
        model = Article
        form_class = ArticleForm
    
        def form_valid(self, form):
            # Save the data to an article object - 
            #   this hasn't yet saved to the database.
            article = form.save(commit=False)
            article.slug = slugify(article.title)
            article.author = self.request.user
            # Save again - this time to the database
            article.save()
            return super().form_valid(form)
    
    
    class ArticleUpdateView(LoginRequiredMixin, UpdateView):
        model = Article
        form_class = ArticleForm
    
        def get_object(self):
            # We get records by primary key, which ensures that
            # changes in the title or slug doesn't break links
            return get_object_or_404(Article,
                id=self.kwargs['pk'],
                author__username=self.kwargs['username'],
                author=self.request.user
            )
    
        def form_valid(self, form):
            # Update the slug if the title has changed.
            article = form.save(commit=False)
            article.slug = slugify(article.title)
            article.save()
            return super().form_valid(form)        
    
    
    class ArticleDetailView(DetailView):
        model = Article
    
        def get_object(self):
            # We get records by primary key, which ensures that
            # changes in the title or slug doesn't break links
            return get_object_or_404(Article,
                id=self.kwargs['pk'],
                author__username=self.kwargs['username']
            )        
    


    URL



    이것을 URL로 라우팅합시다.

    # articles/urls.py
    from django.urls import path
    
    from articles import views
    
    urlpatterns = [
        path(route='/new/',
            view=views.ArticleCreateView.as_view(),
            name='create',
        ),
        path(route='/<slug:username>/<slug:slug>/<int:pk>/edit/',
            view=views.ArticleUpdateView.as_view(),
            name='update',
        ), 
        path(route='/<slug:username>/<slug:slug>/<int:pk>/',
            view=views.ArticleDetailView.as_view(),
            name='detail',
        ),       
    ]
    


    그리고 프로젝트의 루트 구성에서 다음을 추가합니다.

    # config/urls.py or wherever you stick the project's root urls.py
    from django.conf.urls.static import static
    from django.contrib import admin
    from django.urls import include, path
    
    urlpatterns = [
        # Django Admin, change this URL
        path('two-scoops-of-django-is-awesome', admin.site.urls),
        # Articles management
        path('', include('articles.urls', namespace='article')),
        # More URLS here
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
    # There's certainly more URLs down here
    


    템플릿을 추가하면 Dev.to URL 디자인을 따르는 Django 예제가 있습니다!

    앞으로



    숙련된 Django 사용자는 form_valid 메서드의 slugification 논리가 뷰가 아니라 Article 모델의 save() 메서드에 적절하게 속한다는 것을 알 것입니다. 그것이 우리가 Two Scoops of Django에서 논의하는 종류의 것입니다.

    말하자면, 모든 종류의 고급 요령과 팁을 배우고 싶다면 Django Best Practices에서 me and my's my ice-cream 테마bookcourse을 살펴보세요.

    좋은 웹페이지 즐겨찾기