1

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 and Moel B:

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

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

app.urls.py file :

urlpatterns = [
    path('',view.index,name="index"),
    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):
    if 'title_in_model_A':
          render 'some_page_A'
    
    if 'title_in_model_B:
          render 'some_page_B'

    render(request,'app/404.html')

project.urls file:

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


handler404 = 'app.views.view_404'

My question is:

  1. Is this type of page rendering good or not?
  2. Does 404 request handles correctly?
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Manoj Kamble
  • 620
  • 1
  • 4
  • 21

1 Answers1

0

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 views.py.

As per OP's new requirement, in the case of having two models and wanting to check the existence of instances that have the title matching a specific one, then OP can use exists() as follows

def article_details(request,title):
       if A.objects.filter(title=title).exists():
           # render page A
       elif B.objects.filter(title=title).exists():
           # render page A
       else:
            # 404 

Note that this method is good if one doesn't need the model but are just checking the existence. If one does need it as well, then one can include inside of the condition the following (before the render)

my_model = MyModel.objects.get(title=title)
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83