i hope you are all doing great.
I am currently working on a Django project.
In views.py i did a function that handles registration.
The user is an object from a class that django generated when i connected mysql to my django project.
The request method in my form is set to POST but django doesnt execute it.
It was working all good but suddenly i am getting a ValueError my function didnt return a HttpResponse. It returned None instead.
The method in my html form is set to POST and the action attribute leads to the url ( {% url 'name_in_my_url_file %}
Related
I'm using django-allauth and custom login and signup forms in my application. Everything works well until a user submits an error with the login or signup form.
The error shows up but on a different page.
e.g intended login form is at the URI: /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/
However, when there is a form error in the above page, it redirects to the default login URI: /accounts/login/ and displays the error there.
Is there a way to make sure the user is returned to the original page incase of a form error and have the error(s) displayed there?
Thanks in advance.
If you have login form on URI /payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/ and you do not want to redirect to /account/login, do not write as action of form. And create payment view which can handle authorization directly on payment URI.
<form class="login" method="POST" action="/payment/e886371a-fa52-4718-b8bc-e53fe8ac2bea/">
...
</form>
In your payment view you can extends class allautho/accounts/views/LoginView, which handles normal email/password auth.
I'm trying to use a Django ListView sub-class to generate a page with a form on it. It's an old school manual HTML form, not a Django-generated one (though I do also have a Django-generated form elsewhere on the same page). Since Django bakes CSRF authentication in, I need to include the CSRF token in that form in order to make it work.
However, I'm not having much luck, even after looking at several related Stack Overflow posts (and fixing things accordingly).
Basically I've got a get method on a ListView subclass, and I've used the method decorator to decorate it with the CSRF decorator:
class FooView(ListView):
#method_decorator(ensure_csrf_cookie)
def get(self, request):
# code for otherwise working view
In my template I have:
<form>
{% csrf_token %}
However, when I view the source of the page after it's been rendered, I just see:
<form>
(no CSRF token).
I'm not explicitly adding the CSRF token to the context because I'm using ListView, and as per https://docs.djangoproject.com/en/1.6/ref/contrib/csrf:
If you are using generic views or contrib apps, you are covered already
I'm sure I'm just missing something basic, but any help explaining what that might be would be greatly appreciated.
You need import this:
from django.template import RequestContext
and then use it like so:
def example():
# Some code
return render_to_response('my_example.html', {
'Example_var':my_var
}, context_instance=RequestContext(request))
This will force a {% csrf_token %} to appear.
How do I pass information from an HTML form to my Python code, without having to specify a url mapping? For example, the following code sends data from the form in my 'index.html' template, to the 'myview' mapping, which then calls the 'myview' view function, which finally renders the 'mypage' template...
index.html
<form method="get" action="{% url 'myview' %}">
urls.py
urlpatterns = patterns('',
url(r'^mypage/$', views.myview, name='myview'),
)
views.py
def myview(request):
return render(request, 'myapp/mypage.html')
However, do I really have to have a url mapping for this? What if I do not want to reload another webpage, and I just want to stay in the same 'index.html' page?
I'm just a little confused over how views are actually called, in the case when I want the view to act more like a traditional function, to process some data, rather than to necessarily render a new template.
Thank you!
You always need a URL if you want your browser to call a view. How else would the server know which view to call? The only way is through the URL mapping. Remember that there is no persistent relationship between the browser and the server: the only way they can communicate is through requests to URLs.
You don't always need to render a template, though. A view can return anything, including raw text or JSON.
I don't understand what you mean about not reloading another page. Posting data to the server is a request for another page: that's just how HTTP works. You can certainly choose to post to the same page you're currently on; and in fact that's exactly how forms are processed in the recommended Django pattern. But you still need a URL mapping pointing at that page, in order to get it in the first place as well as to process the submitted dat.
Besides understanding and accepting Daniel Roseman's answer you could also look at these two packages:
Django Rest Franework
jQuery Form Plugin
I am trying to use a Django 1.3 FormWizard to upload a file with 2 steps:
1. Only the FileField
2. If the file was correctly uploaded and valid (after custom validation), offer to give it a name and description.
Following the documentation, I wrote:
class CreateCheckWizard(FormWizard):
def done(self, request, form_list):
return HttpResponseRedirect('/my_checks/')
def get_template(self, step):
return ['create_check_%s.html' % step, 'create_check_1.html']
class CreateCheckForm1(forms.Form):
my_file = forms.FileField()
class CreateCheckForm2(forms.Form):
title = forms.CharField(max_length=255)
I added the multipart/form-data to the FORM tag in the template:
<form enctype="multipart/form-data" action="." method="post">
However, even if I upload a file, I get the error "This field is required."
I guess the form is created omitting the request.FILES field.
How can we change that behaviour to successfully upload files in the FormWizard?
Edit: Looking at Django source code, it indeed create the forms using form(request.POST) instead of form(request.POST, request.FILES) like it should be to handle files.
Any way to upload files without changing the source code?
This isn't possible in the Django 1.3 form wizard. From the Django form wizard docs:
Important limitation: Because the wizard uses HTML hidden fields to store data between pages, you may not include a FileField in any form except the last one
It is possible with the Django 1.4 form wizard (see handling files docs). If you're using Django 1.3, you can install the new form wizard as a separate app.
I my recent Django-project I use mako templates.
About Cross Site Request Forgery CSRF.
In django templates there is the tag {% csrf_token %} to protect from hackers.
What about mako templates? Is there any analog of csrf_token or there is another protection mechanism???
Thanks!
I ran into the same problem just today (that's why I ended up here). I found a solution, at least, for what I wanted to do, which is pass some POST data to another view through an HTML form. Here it is:
From your first view, get a CSRF Token and add it to your (Mako) context:
from djangomako.shortcuts import render_to_response as render
from django.core.context_processors import csrf
def first_view(request):
"""This view generates a form whose action is 'second_view'."""
context = { "csrftoken": csrf(request)["csrf_token"] }
return render("path/to/yourtemplate.html", context)
yourtemplate.html's form must have a field named “csrfmiddlewaretoken” whose value is the CSRF Token, which we placed in the context as “csrftoken”. As in:
<input type="hidden" name="csrfmiddlewaretoken" value="${ csrftoken }" />
Source: Cross Site Request Forgery protection (Django 1.5 Docs)
There's some sample code at Django Snippets that looks to do this, although judging by the comments, you may need to fiddle a bit. If you have trouble, you basically want to make sure that you're duplicating the Django stock CSRF tag (click the link, start on line 87).