Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex in django 2.0 re_path

I'm fairly new to python and Django, so please excuse me if this seems like too simple a question.

I've been trying to use this in CreateView, but it is not working:

re_path(r'^<str:pk>/$', indexView.as_view(), name='index'),

Can anyone tell me why, and how to fix this?

like image 224
Mohamed Benkedadra Avatar asked Mar 25 '18 10:03

Mohamed Benkedadra


People also ask

What is re_path in Django?

re_path is a callable within the django. urls module of the Django project.

What is regex in Django?

The Django regex field provides custom fields and utilities for a Django model that stores a regex. This provides the ability to easily store regex patterns and access them as compiled regular expressions from your models. Patterns can be expressed in perl syntax to set regex flags.

How Django URLs work with regular expressions?

We use regular expressions to match these url paths to their corresponding request handler (aka View). If a path, either dynamic or static, is matched the View will then handle the request and return a response to the User. If a path is not matched, Django will automatically send a 404 Page Not Found response.

Which method is used instead of path () in URLs py to pass in regular expression as routes?

If the paths and converters syntax isn't sufficient for defining your URL patterns, you can also use regular expressions. To do so, use re_path() instead of path() .


1 Answers

You are doing wrong, you are using re_path which expects regex, you should use path here in this case. And also you should use slug type and not str.

path('<slug:pk>/', indexView.as_view() ,name = 'index'),

But if you still want to use, re_path you have to use regex.

re_path(r'^(?P<slug>\w+)/$', indexView.as_view() ,name = 'index'),

You can follow the django docs here.

like image 69
Astik Anand Avatar answered Oct 20 '22 02:10

Astik Anand