In django how to generate dynamic url after domain name for every page?

I am building a blog website where I set a unique title for every article. I want the article should have url domain_name/<article_title>/.

Suppose I have model A :

class A(models.Model):
    title = models.CharField(max_length=500,unique=True) file :

urlpatterns = [
    path('contact/', contact, name="contact"),
    path('about/', about, name="about"),
    path('terms-and-conditions/', terms, name="terms_and_conditions"),
    path('privacy/', privacy, name="privacy"),
    path('<str:title>/', article_details, name="article_details"),

I have view file as follows:

def article_details(request,title):
        article = A.objects.get(title=title)
        context = {'article':article}
        return render(request,"app/article.html",context=context)
        return render(request,"app/404.html")

project.urls file:

urlpatterns = [
    path('', include('app.urls')),
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

handler404 = 'clothes.views.view_404'

My question is:

  1. Is this type of page rendering good or not?
  2. Does 404 request handles correctly?

The way OP is doing is ok, but if one wills it's possible to simplify the article_details view by using the shortcut get_object_or_404, like

from django.shortcuts import get_object_or_404

def article_details(request,title):
    article = get_object_or_404(A, title=title)

In order to customize the 404 view one can use handlers. Here's a good example in the docs.

Hard to say if OP's renders correctly because the question doesn't show that OP has a clothes app with a view_404 in

Back to Top