Restrict Integer value in the django urls

Viewed 50

I have the following Django URL, which allows users to register for any one security code from 1 to 6.

path('add/<int:security_code>/', security_views.RegisterView.as_view(), name='register_code'), 

Url should render the template up to 6 security codes such as

https://www.example.com/add/1/ #-- It should work
https://www.example.com/add/2/ #-- It should work
https://www.example.com/add/3/ #-- It should work
https://www.example.com/add/4/ #-- It should work
https://www.example.com/add/5/ #-- It should work
https://www.example.com/add/6/ #-- It should work
https://www.example.com/add/7/ #-- It should throw 404 when the user types a number greater than 6.

What change I would need to do to restrict URL for limited codes, it should throw a 404 or bad request error if the user manually puts a different number. I don't want to modify the view as I would need to add the get as well as the post methods.

from django.views import generic
from core import models

class RegisterView(generic.edit.CreateView):
    model = models.SecurityCode
    fields = ['name', 'code']

Is there any way we can do it without modifying the views part?

1 Answers

You can work with re_path(…) [Django-doc] to specify a regular expression:

from django.urls import re_path

re_path(
    'add/(?P<security_code>[1-6])/$',
    security_views.RegisterView.as_view(),
    name='register_code'
),
Related