Referring from the form topic of django documentation, if in a view function I write,
if form.is_valid():
return HttpResponseRedirect('/thanks/')
And in the form template I give the action like,
<form action="/your-name/" method="post">
Then on submit the form will go to the view mapped tho /your-name/ url in urls.py but what about the HttpResponseRedirect('/thanks/') line in the function from where I rendering the form? If a form is valid then I save the form. but what will be the url in the action of the form. now def get_name(request): is the function mapped to /user/ url. I hope you understand my confusion here. need some help.
This is an exemple of the "post redirect get" pattern - if a post is succesfull (the form was valid and the processing went ok), it's good practice to return a redirect, which will be followed by a get from the user-agent on the url you redirected to. It avoids multiple submissions if the user try to reload the page.
Where you redirect to is up to you - you can just redirect to the same view (usually displaying a success message to the user), or redirect to another view.
As a side note: hardcoding urls is a bad practice in Django, you should use the url reverse feature instead.
Related
I just started to learn Django by following a sentdex tutorial. During the course, we added a User model into our database and we created a function in our views.py file:
def register(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():#si les champs sont OK :
user = form.save()
login(request, user)
return redirect("main:homepage")
else:
for msg in form.error_messages:
print(form.error_messages[msg])
But in this piece of code, I don't understand how Django knows if the request.method is True or False. Is it because I created a form with a Submit button in my template ?
Its impossible to say exactly what happens in your case since we don't have your HTML but in general:
When you create an HTML form, you can specify a method as follows <form method="POST"></form> or <form method="GET"></form>. If you don't specify the default is GET.
When you submit your form, it sends the data using an http request of the specified type. This is what Django is reading.
In this case, request.method simply represents the HTTP method that was used to access your view. For example, your register function might be assigned a url configuration such as: url(r'^register/', views.register), which maps an incoming HTTP request to your view. If you have a web form with a 'Submit' button, it's likely the web application code is submitting an HTTP POST request to your web server.
Django automatically constructs the request object for you, so you can check in your view how the request was made against the web server. For more info about what other things are included in the request, check the Django docs.
I have a form that a user fills and then clicks a button to submit, then it calls a transition page, to inform the user that the form was completed. The user can click a button to go back to the home page from the transition page.
I want to get rid of the transition page and go to the home page directly. The reverse function does not change the URL but renders the correct homepage template. However, the context data in the template does not get populated and I am assuming that the URL not changing causes that.
The homepage urls.py I include:
url(r'^(?P<user_id>\d+)/$', views.UserHomePageView.as_view() ,
name='user-homepage'),
Example: the form URL is
localhost:8000/form/15/fill
After the form is submitted, I want it to redirect to
localhost:8000/home/3
from the view after form submission, I call
return HttpResponseRedirect(reverse('homepage:user-homepage', args=[userid]))
try this:
return redirect('home')
I have a small python/django web site and I'm using a html form POST some information, annoyingly however this information is stored in POST so when a user refreshes in say IE/chrome they get that warning message about the page containing POST data. How do I clear the POST data after it has been processed so a user can refresh and not see this warning message?
Also I have some logic as follows that detects a POST
if request.method == "POST":
do something
Select all
Open in new window
This is fine when I actually post the form, but when I refresh the page it also detects the POST and does the logic that I now dont want to do.
How can I solve this also??
Thanks
After form is validated and it is valid. Then do the redirect to some other page e.g. a success page or redirect to the same view. The redirection will avoid Double Form Submition problem. Read more about it here.
Use HttpResponseRedirect when you return the response for POST request. This is explained in tutorial 4 as
After incrementing the choice count, the code returns an HttpResponseRedirect rather than a normal HttpResponse. HttpResponseRedirect takes a single argument: the URL to which the user will be redirected (see the following point for how we construct the URL in this case).
As the Python comment above points out, you should always return an HttpResponseRedirect after successfully dealing with POST data. This tip isn't specific to Django; it's just good Web development practice.
As Rohan said, you should use HttpResponseRedirect. But also you can use a shortcut:
from django.shortcuts import redirect
def some_view(request):
if request.method == 'POST':
# do smth
return redirect('/page-with-form/')
I have created a basic contact form, and when the user submits information, it should redirect to the "Thank You" page.
views.py:
def contact(request):
# if no errors...
return HttpResponseRedirect('/thanks/')
urls.py:
(r'^contact/$', contact),
(r'^contact/thanks/$', contact_thanks),
Both pages work at the hard-coded URL. However, when I submit the form on /contact/ it redirects to /contact (no ending slash), which is a nonexistent page (either a 404 or an error page telling me I need a slash).
What is the reason it not correctly redirecting, and how can I fix this?
UPDATE: the return HttpResponseRedirect('/contact/thanks/') is what I now have, but the problem is that the submit button (using POST) does not redirect to the URL -- it doesn't redirect at all.
It's not the POST button that should redirect, but the view.
If not differently specified, the form (the HTML form tag) POSTs to the same URL. If the form is on /contact/, it POSTs on /contact/ (with or without slash, it's the same).
It's in the view that you should redirect to thanks. From the doc:
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
Change /thanks/ to /contact/thanks/ and you're done.
All of the responses are correct but a better approach is to give names to your URLs in urls.py and hint to them in views with reverse function (instead of hard coding URL in views).
urls.py:
(r'^contact/$', contact, name='contact'),
(r'^contact/thanks/$', contact_thanks, name='thanks'),
And hint them in views.py like this:
from django.urls import reverse
return HttpResponseRedirect(reverse('app_name:thanks'))
This is better for future approach and follow the DRY principle of Django.
I believe that apart from Aviral Dasgupta's solution, OP also needs to change the relative url.
return HttpResponseRedirect('/thanks/')
to
return HttpResponseRedirect('/contact/thanks/')
/thanks/ should take the url to root: yoursite/thanks/ and not yoursite/contact/thanks/.
Just try this. It worked for me.
return HttpResponseRedirect('thanks/')
Note:- Remove the forward slash before
Use the Django APPEND_SLASH setting.
APPEND_SLASH
When set to True, if the request URL
does not match any of the patterns in
the URLconf and it doesn't end in a
slash, an HTTP redirect is issued to
the same URL with a slash appended.
Note that the redirect may cause any
data submitted in a POST request to be
lost.
I've a page at / that displays a form for signup new users.
When a new user registers, it will redirect to /dashboard.
But when an authenticated user go to /, it should see the /dashboard page.
The question is: should I put something like this in the home() view:
if request.user.is_authenticated():
return HttpResponseRedirect("/dashboard")
or this is an ugly method and should I return different templates from my home() relying on the user's auth status? In this case, how can I customize my URL to show /dashboard and not / ?
The redirect method is absolutely fine. Not sure what you mean by ugly. The redirect should take care of your URL issue as well.
If I understand you correctly, you have a "dashboard" which is available only for authenticated users, so if not logged in user tries to enter it, he should be redirected to the sign up form. Right?
Have you considered using middleware? Such middleware could check if the user is logged in and if not - return the sign up form view, otherwise continue processing the request, and return the home view. Read about process_request and process_view here.