user7496931
user7496931

Reputation: 1519

How to replace HttpResponseRedirect with redirect in Django?

I have the following urls.py:

urlpatterns = [
...
        path('polls/<int:pk>/', views.DetailsView.as_view(), name='detail'),
        path('polls/<int:pk>/results/', views.ResultsView.as_view(), name='results'),
        path('polls/<int:week_id>/vote/', views.vote, name='vote'),
]

In my views, I have the following vote view:

def vote(request, week_id):
    week = Week.objects.get(pk=week_id)
    try:
        selected_choice = week.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render(request, 'weeklydesert/detail.html', {
            'week': week,
            'error_message': "You didn't select a choice.",
        })
    else:
        selected_choice.votes += 1
        selected_choice.save()
    
        # How to update this to redirect? 
        return HttpResponseRedirect(reverse('results', args=(week.id,)))

I'm trying to update the HttpResponseRedirect to simply use the redirect function but i'm having trouble passing in the proper parameteres.

The redirect should lead to something like: polls/1/results/

Any suggestions?

Upvotes: 1

Views: 135

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477607

You can work with:

from django.shortcuts import redirect

def vote(request, week_id):
    # …
    return redirect('results', week_id)

You thus do not use args=(some iterable), but use positional parameters.

Upvotes: 2

Related Questions