dl8
dl8

Reputation: 1270

Django optional view parameter with HttpResponseRedirect

So I have a view that grabs a person's info from a query and returns the info to the page:

def film_chart_view(request, if_random = False):

I also have a view that randomly grabs a person's info and redirects it to the above view:

def random_person(request):
         .
         .
      return HttpResponseRedirect(reverse('home.views.film_chart_view')+"?q="+get_person.short)

However, I want the first view to recognize if it came from the second view, so that if it is, it sets the if_random parameter to True, but I'm not exactly sure how to do that.

my urls:

url(r'^film_chart_view/$', 'home.views.film_chart_view'),
url(r'^random/$', 'home.views.random_person'),

Upvotes: 2

Views: 1944

Answers (1)

Leonardo.Z
Leonardo.Z

Reputation: 9791

You don't have to pass if_random as a url parameter.

def random_person(request):
    return HttpResponseRedirect(
        reverse('home.views.film_chart_view') + \
        "?q=" + get_person.short + \
        "&is_random=1"
    )

def film_chart_view(request):
    is_random = 'is_random 'in request.GET

But if you prefer url parameters, the solution is a little more complex.

The parameters passed to the view function comes from the url patterns, you need to set them at first.

Because the is_random para is optional, I suggest you to write 2 separated patterns for the film_chart_view.( actually you can combine these 2 patterns to one with a more complex regex expr, but readability counts.)

urlconf:

url(r'^film_chart_view/$', 'home.views.film_chart_view', name ='film_chart_view'),
url(r'^film_chart_view/(?P<is_random>.*)/$', 'home.views.film_chart_view', name ='film_chart_view_random'),
url(r'^random/$', 'home.views.random_person'),


def random_person(request):
    return HttpResponseRedirect(
        reverse('home.views.film_chart_view', kwargs={'is_random': '1'}) + \
        "?q=" + get_person.short
    )

The view parameters(except the request) are always strings, you need to convert it to int/bool/... in you code.

def film_chart_view(request, is_random=None):
    if is_random:
        ...

Upvotes: 3

Related Questions