0

I have a question regarding conversion of pre - Django 2 urls to path

If I have an url like this:

url(
r'^some_path/(?P<type>type_one|type_two)/',
 views.SomeViewHere.as_view(),
 name='important_name',
),

Question is how to convert this url to modern Django path keeping same functionality and keeping same name?

Important aspect: kwargs type_one and type_two should be passed into view. Name parameter can’t be changed or split.

What I have done:

path('some_path/', include(
    [
        path('type_one/', views.SomeViewHere.as_view(), kwargs={'type': 'type_one'}),
        path('type_two/', views.SomeViewHere.as_view(), kwargs={'type': 'type_two'}),
    ]
), name='important_name',
     ),

But reverce doesn’t work with this configuration

Thank you.

ps. type is a string

Aleksei Khatkevich
  • 1,923
  • 2
  • 10
  • 27
  • 1
    The path api also provides a `re_path()` Why remove the regex if it's working? – Michael Lindsay Dec 14 '20 at 13:31
  • @ Michael Lindsay , well , this is not my choice. I just have to do it. This is the situation. But i agree with you generally about re_path() – Aleksei Khatkevich Dec 14 '20 at 13:33
  • 1
    if you have to do it in the path rather than url or view, maybe this post will help. https://stackoverflow.com/questions/48031043/how-to-have-options-in-urls-in-django-2-0 – ha-neul Dec 14 '20 at 13:45

1 Answers1

1

Pass the two choices as a parameter to the view, and then move any value checking to the SomeViewHere class.

path('/some_path/<str:type>/', views.SomeViewHere.as_view(), name='important_name')

class SomeViewHere(View):

    def get_context_data(self, **kwargs):
         type = kwargs.get('type', None)

         if type not in ['type_one', 'type_two']:
             raise Http404("not one or two") 

         ...do rest of view....
Michael Lindsay
  • 1,290
  • 1
  • 8
  • 6