0

I am trying to write a generic urlpatterns entry in urls.py that would replace hardcoded entries, as below:

path('apple/', RedirectView.as_view(url='/apple/abc/'), name='apple_redirect'),
path('orange/', RedirectView.as_view(url='/orange/def/'), name='orange_redirect'),
path('banana/', RedirectView.as_view(url='/banana/ghi/'), name='banana_redirect'),  

The model called fruits holds the following data:

    name = 'apple'
    url = 'apple/abc/'

    name = 'orange'
    url = '/orange/def/'

    name = 'banana'
    url = '/banana/ghi/'

I would like to avoid the need for manual addition of another path in case new entry in fruits model is added.

2
  • Yes having parameters in URLs of the normal thing to do and is well described in the tutorial and docs. Where are you having trouble? Commented Jan 7, 2019 at 21:46
  • well, I know how to capture URL parameters, say apple, but I do not know how to check if given parameter exists in fruits model, and if it does how to pull corresponding apple/abc and place it n the RedirectView.as_view(). I just started with django, hence potentially obvious things are not that clear yet... Commented Jan 7, 2019 at 21:54

2 Answers 2

2

You should catch url param and pass it to your view like this

from django.shortcuts import redirect, get_object_or_404

def fruit_redirect_view(request, url_path):
    fruit = get_object_or_404(Fruit, name=url_path)
    return redirect(fruit.url)

So if fruit with such name exists, request will be redirected to fruit's url, otherwise 404 error will be raised

Sign up to request clarification or add additional context in comments.

1 Comment

Clear and easy to understand. Thank you!
1

If you want to use RedirectView, you can subclass it and override get_redirect_url.

class FruitRedirectView(RedirectView):
    def get_redirect_url(self):
        fruit = get_object_or_404(Fruit, name=self.kwargs['fruit'])
        return fruit.url

Then replace your individual fruit URL patterns with:

path('<slug:fruit>/', FruitRedirectView.as_view(), name='fruit_redirect'),

Note you don't need to use RedirectView here. Alex C's view is easier to understand, especially if you're not familiar with Django's generic views.

Note that once you have added the <slug:fruit>/, the view will raise a 404 error for any fruits that are not in the database. This is slightly different than when you had apple/ and orange/ in your URL patterns - in that case, Django might be able to match a pattern further down your list of URL patterns.

1 Comment

Thank you for detailed explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.