I am trying to build code that allows people to pay for the services that they get from my website. I have built the form using the forms.Form model available in django. I have also used the following pattern to build my view.
if request.method == 'POST'
form = ContactForm(request.POST)
if form.is_valid(): # All validation rules pass
conn = urllib2.Request(payment_gateway_url,urllib.urlencode(my_dat_in_dict))
f= urrlib2.urlopen(conn)
all_results=f.read()
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {
'form': form,
})
The problem i am facing is that my forms get submitted OK and the payment gateway responds back to me with a whole bunch of html that helps the user to choose the credit card details etc in the response to this form POST(details that i am not collecting on my website). I can see this in the all_results (f.read()).
My question is that how do i show the user this page, since i get this as a result of my form POST. Should i save this response in a html file and HTTPResponseredirect to that page. I am assuming that HTTPResponseRedirect is more for a complete transaction and not the intermediate responses.
So, basically how do i handle the situation where the user will get sent to the payment gateway site and then after completing the proceedings come back to my site?
thanks
First off, I would say, if you live in the US, check out Stripe (or something similar). The way you are describing your payment process seems a bit overly complicated.
With that said, if (and I doubt this is the case), the HTML returned from the most is in the correct format for display on your website, you can just stick it in to an HttpResponse (must be a sprint)
return HttpResponse(html)
Otherwise, use something like BeautifulSoup, Scrape.py, or something similar to format it IN RAM, and then use HttpResponse. I would not write it to the file system for modification.
Related
I am struggling with the update of database information with the forms, and simply passing information between views. I could really use some advice because I am fairly new to Django.
The flow goes like this:
1. First form; I transfer the article price and title to the view "event"
2. The view "event" handles title and price and ask for confirmation in the html form
3. Once confirmed, it directs that information to the view "transact_test", I want this view to handle the update of the database via a new form that is build with the Article model. But it provides the error message : "didn't return an HttpResponse object. It returned None instead."
To fix your error: In transact_test you are just calling render in the request.method == 'POST' block:
render(request, ...)
You need to return render:
return render(request, ...)
You should really take a look at some additional django tutorials you are making this harder than you need to. You should almost never manually render a form when using django. And as Tariq said, please don't use images.
I am building a website and I want various views that will ask the user to request a quote from our page. I want to keep the code as DRY as possible so I am writing a view quote which will receive the quote requests from various views and, if there is a validation error redirect back to the page that made the request. I managed to solve this using the super bad practice 'global variables'. I need a better solution, I would like redirecting to respective view with the current form so I can iterate through the form.errors. Here is my code:
def send_quote(request):
form = Quote(request.POST)
if form.is_valid():
# do stuff when valid
return redirect('Support:thanks', name=name or None)
quote_for = request.POST['for_what']
global session_form
session_form = form
return redirect('Main:' + quote_for) # Here I would like to send form instead of storing in global variable`
You can use the HttpResponseRedirect function, and pass as argument the page that made the request.
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
All the META data is store on a dictionary, if you want to learn more check the documentation.
https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META
If you redirect to the referrer, form.errors will be empty, as redirection is always a GET request.
I can think of two solutions to your problem:
Submit forms asynchronously using JavaScript and so populate the errors
Make all the views containing the form support POST - one way to do this would be to create a base class that inherits from FormView
The second option is a typical way of handling forms in Django - you process both POST and GET inside the same view.
After two days of searching I finally found the answer. Instead of saving form in request.session I just save request.POST and then redirect. Here is the code:
def send_quote(request):
form = Quote(request.POST)
if form.is_valid():
# do stuff when valid
return redirect('Support:thanks', name=name or None)
quote_for = request.POST['for_what']
request.session['invalid_form'] = request.POST
return redirect('Main:endview')
def endview(request):
session_form = request.session.pop('invalid_form', False)
if session_form:
form = Quote(session_form)
# render template again with invalid form ;)
Now I can repeat this with all the views I want and just change the what_for input of each form to match the respective view (Like I intended).
I have a Django page with a form. I have some view code which deals with the form as normal but prepopulates the form with initial data from the a user's session if available. This is so that when a user returns to this form they see previously selected options (yes, the form is quite extensive).
My views,py:
def myView(request):
...
form = ProjectInfoForm(request.POST or None)
if form.is_valid():
# process form, including a redirect
...
# if there is form data in the session, let's use that
# to initaliaze our from with data
if key in request.session:
form = ProjectInfoForm(
initial={
'model': request.session.get('model'),
...
}
)
return render_to_response(template_name, {
...
}, RequestContext(request))
Problem is: if I load the session data then the page does not display any error messages. The form does fail validation, I am just not getting the any output. Is there some conflict here with initial?
Any help would be much appreciated.
Well, from that snippet, if the session data is found then you completely re-initialize the form: the original, validated instance, which contained the POST data and any errors, has now been disposed. Presumably you would want to only enter that second if if the request is not a POST.
Hi Stackoverflow people,
I am irritated by the the Django Form handling, if the form submits to new page and the form validation fails. I intended to return to the earlier submitted form, and display the error message for correction.
The error message will be displayed, but the url link is not changing.
How can I change the *else statement of the is_valid() statement*, in order to redirect to the earlier form?
Thank you for your advice!
urls.py
urlpatterns = patterns("",
url(r"^add/$", "remap.views.add_project", name="add_project_location"),
url(r"^add/details/$", "remap.views.add_project_details", name="add_project_details"),
)
views.py
def add_project_details(request):
if request.method == 'POST': # If the form has been submitted...
locationForm = LocationForm(request.POST)
if locationForm.is_valid(): # All validation rules pass
locality = locationForm.cleaned_data['locality']
state = locationForm.cleaned_data['state']
country = locationForm.cleaned_data['country']
projectForm = ProjectForm(initial = {
'locality': locality,
'state': state,
'country': country,
})
return render_to_response('map/add_project_details.html', {
'projectForm': projectForm,
}, context_instance = RequestContext(request))
else:
print locationForm.errors
return render_to_response('map/add_project_location.html', {
'locationForm': locationForm,
}, context_instance = RequestContext(request))
else:
return HttpResponseRedirect('../') # Redirect to the location reg if site is requested w/o proper location
There's no cause to get irritated about Django doing exactly what it is designed to do.
Your redirect is on the else clause corresponding to if request.method == 'POST'. So, it will only take effect if this is not a form submission. In other words, that view will never actually display an empty form.
Then, depending on whether or not the POSTed form is valid, you display one of two templates. You're not doing any redirecting at this point.
However, even if you had asked Django to redirect when the form is invalid, I doubt you would get the result you want. This is because the rules of HTTP (not Django) say that you can't redirect a POST - so your request to the redirected view would be a GET, without any of the invalid data or error messages.
You can't update the url unless you tell the browser to do a redirect. You are returning two different html versions on the same url which can be confusing to the user.
What you should do instead is have two views. The /add url and add_project_location view would accept a post and validate, staying on that url and view until success.
Upon success it would set some session variables, redirect to the add_project_details page. Merging them like this is just not possible because of how browsers work.
I've seen Django's samples and I can see they have decent error handling. However I want to see if there is yet a better approach, a general pattern to handle form validation errors in Django. This is the sample I found here:
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,
})
In particular, I was wondering:
How can the view in "/thanks/" be sure that the form was validated? Are there any common ways to pass the successful validation of the form to the next view? Or do I need to do something manually such as setting a flag in request's session?
How can one write this code in a way that when form is NOT valid and the page is shown with errors upon submission, if user refreshes the browser it wouldn't ask the user if they want to POST data again?
EDIT: With regards to #1 I am referring to cases like user manually entering the '/thanks/' url or going back and forth through history pages and accidentally openning it without any form being validated. (Do we still show the "thanks" page? or we need to somehow re-validate why we are in thanks view).
The view can be sure that the form is validated because it will only be called if the form is valid...
If the page is generated through a post request the browser will always ask you that when hitting refresh... I guess the only way to avoid this would be redirecting to another page!
How can the view in "/thanks/" be sure that the form was validated?
form.is_valid() should thoroughly check any field or - if necessary - any combination, cornercase, etc. That's basically it. The views knows, the form was valid if it renders. There is no need to include redundant information in the session.
How can one write this code in a way that when form is NOT valid and the page is shown with errors upon submission, if user refreshes the browser it wouldn't ask the user if they want to POST data again?
I am not sure what the point would be. The form contains errors and the user may correct them or leave. To render a page that would not ask for form resubmission, one could use a redirect, just as in the valid case. The error markup would have to be done manually in that case.