Mjguel
Mjguel

Reputation: 17

Modal forms and Django URLs, how to work?

html

<form action="{% url 'sp_feedback' %}" method="post">

url

url(r'^feedback/$', views.post_feedback, name="sp_feedback"),

views:

 return HttpResponseRedirect("")

In using modal forms, how do you, after hitting submit, return to the page?

In my current setup, the browser redirects to nothing. I'm completely confused on what to put in the url regular expressions.

Upvotes: 0

Views: 1050

Answers (1)

xyres
xyres

Reputation: 21734

In my current setup, the browser redirects to nothing.

Because you're redirecting to an empty URL:

return HttpResponseRedirect("")

You've to redirect to the url of the page:

return HttpResponseRedirect('/feedback/')

But it is rather better and convenient to use the redirect() shortcut. Because you can pass it the name of the url and Django will automatically make the redirect to the associated url.

Example:

return redirect('sp_feedback')

It is a good practice to avoid using hardcoded urls in your application.


UPDATE

Since you mention that this form is on every page and you'd like to redirect the user back to that page, here's one solution:

Use request.META['HTTP_REFERER'] in your form view to get the referring page, then use that value to make the redirect:

redirect_to = request.META.get('HTTP_REFERER', '/') # if HTTP-Referer header is not present, just redirect to homepage
return HttpResponseRedirect(redirect_to)

Upvotes: 1

Related Questions