Chidananda Nayak
Chidananda Nayak

Reputation: 1201

how to convert regular expression of django 1.4 to django 2.0 style path?

url('add/(?P<journal_type>C[DR])/$', add_bank_entry),

how to convert this line to django 2.0 version path() pattern? What is does C[DR] do?

Upvotes: 1

Views: 542

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124548

The C is just a literal character that must match. The [DR] part is regular expression syntax for one character, either a D or and R. So the following two paths are valid for the given URL pattern:

add/CD/
add/CR/

and the journal_entry will be set to either 'CD' or 'CR' when the add_bank_entry view is called.

You could either register two routes and pass in default values for journal_type for each, use the regular expression as is with re_path(), or register a custom path converter that knows how to handle the two string matches.

Using two urls is simple enough:

path('add/CD/', add_bank_entry, {'journal_type': 'CD'}, name='add_bank_entry'),
path('add/CR/', add_bank_entry, {'journal_type': 'CR'}, name='add_bank_entry'),

This does the exact same thing; match one of two possible URL paths and pass in the right string value for either to the view function.

You can just take the original regex and not convert at all by replacing url() with re_path():

re_path(r'add/(?P<journal_type>C[DR])/$', add_bank_entry),

In Django 2.0, url() is an alias for re_path(), so you can get away with not changing anything for now. In a future Django release, the alias is going to be removed.

If the pattern is common in your URLs (across different Django apps even), you can create a custom path converter:

from django.urls import register_converter, StringConverter

class JournalEntryTypePathConverter(StringConverter)
    regex = 'C[DR]'

register_converter(JournalEntryTypePathConverter, 'journaltype')

then use that in a path:

path('add/<journaltype:journal_type>/', add_bank_entry),

Upvotes: 2

JPG
JPG

Reputation: 88649

From Django documentation for url

url(regex, view, kwargs=None, name=None) This function is an alias to django.urls.re_path(). It’s likely to be deprecated in a future release.

Key difference between path and re_path is that path uses route without regex

You can use re_path for complex regex calls and use just path for simpler lookups


So, you can use
re_path('add/(?P<journal_type>C[DR])/$', add_bank_entry), instead of

url('add/(?P<journal_type>C[DR])/$', add_bank_entry), if the regex is working fine with url()

Upvotes: 1

Related Questions