form.is_valid() returning false - django

I have a Model class.
class Search(forms.Form):
query=forms.CharField()
And, a view function.
def search(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
form = Search(request.POST)
if form.is_valid():
search_query=form.cleaned_data['query']
return HttpResponse("your query: %s" %search_query , c)
else:
return HttpResponse(form , c)
else:
return render_to_response('polls/search.html', c)
And, here is my search.html:
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="query_label">query:</label>
<input type="text" name="query_txt" id="query_txt_id" /></p>
<input type="submit" value="Submit" />
</form>
After giving some characters as input, it always show me the following as plain text(Not as error).
"A server error occurred. Please contact the administrator."

The id of your query field is incorrect. Django expects it to be id_query.
You don't need to hardcode your form inputs. If you include {{ form.as_p }} in your template, Django will render the form correctly.
<form action="/polls/search" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
If you really want to hardcode the form in the template, start with the working html that Django produces, and customize it from there. Note that the forms in your template and the snippet below do not display errors. See the docs on customizing the form template for more details.
<form action="/polls/search" method="post">{% csrf_token %}
<p><label for="id_query">Query:</label> <input type="text" name="query" id="id_query" /></p>
<input type="submit" value="Submit" />
</form>

Related

Forbidden (403) CSRF verification failed

When I click on ok button in add_tech.html then it will redirect me on upload_type.html.
But it show error while clicking on ok button.
ERROR -
Forbidden (403)
CSRF verification failed. Request aborted.
Help
Reason given for failure:
CSRF token missing or incorrect.
My template(add_tech.html) -
<form action="/uploads/type/" method="post">
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
My Template(upload_type.html)-
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
</form>
My View.py -
def upload_type(request):
if request.method =='POST':
details = NameForm(request.POST)
if details.is_valid():
return render(request, "core/upload_type.html", {'form':details})
else:
details = NameForm()
return render(request, 'core/upload_type.html', {'form': details})
My Url.py -
urlpatterns = [
url(r'^uploads/type/$', views.upload_type, name='upload_type'),]
My form.py -
from uploads.core.models import Name
class NameForm(forms.ModelForm):
class Meta:
model = Name
fields = ('your_name', )
My Models.py-
class Name(models.Model):
your_name = models.CharField(max_length=100)
You need to have the csrf token like this for your post method in the django template
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
For POST request, csrf token is required. So in your template, add `{% csrf_token %}.
<form action="/uploads/type/" method="post">
{% csrf_token %}
<label for="your_name">New Tech: </label>
<input id="your_name" type="text" name="your_name" value="{{ current_name }}">
<input type="submit" value="OK">
</form>
From the Docs:
Django ships with an easy-to-use protection against Cross Site Request
Forgeries. When submitting a form via POST with CSRF protection
enabled you must use the csrf_token template tag as in the preceding
example.

Submitting dynamically created input field in django

am working on a project with Django, i dynamically created an input field and am trying to submit it, but i could not do so, i searched online and i saw that it could be done with formset_factory but when i tried it, i got this error
CatName = int(float(request.POST.get('CatName')))
TypeError: float() argument must be a string or a number, not 'NoneType'
here is my code
the form.html
<form action="." method="post" id="PostCat__form">{% csrf_token %}
<input type="hidden" name="deyHidden" value="category_hidden">
{% comment %} {{ catForm | crispy }}
<input type="hidden" name="deyHidden" value="category_hidden"> {% endcomment %}
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<input type="text" class="form-control" name="CatName[]" >
<div class="form-group">
<h6 id="PostCat__show"></h6>
<img src=" {% static 'images/ajax-loader.gif' %}" style="Display:none;" id="PostCat__img">
<button class="btn btn-outline-info" type="submit" id="PostCat__submit">Create</button>
</div>
</form>
the model.py
class Category(models.Model):
CatName = models.CharField(max_length=100)
the view.py
myFormCat = CatPostForm(request.POST)
CatName = int(float(request.POST.get('CatName')))
# print(CatName)
formset = formset_factory(FormsetForm, CatName=CatName)(request.POST)
if myFormCat.is_valid() and formset.is_valid():
for form_c in formset:
if not form_c.cleaned_data['CatName']:
Category.objects.get_or_create(CatName=CatName)
response_data = {
'SType': 'success',
'message': "Saved Successfully"
}
return HttpResponse(json.dumps(response_data), content_type="application/json")
the forms.py
class CatPostForm(forms.ModelForm):
class Meta:
model=Category
fields = ['CatName']
pls how can i do it so that i can successfully submit the form,
on your views.py
from django.forms import formset_factory
CatPostFormSet = formset_factory(CatPostForm)
catformset = CatPostFormSet() #this goes to your page context. do the validations here also after the post
on your form.html
<form method="post">
{{ formset.management_form }}
{{formset}}
</form>

Django Document upload issue does not show "no file selected"

I have the following form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
This produces a form which produces (in [] brackets denotes a button):
**Document:**
[Choose File] no file selected
[Upload]
When I use the following form:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.document }}
<button type="submit">Upload</button>
</form>
I don't get the "no file selected" part in Safari but I do in chrome. Is there some sort of "form.something" that will allow me to have it shown in whatever browser.
Form is as follows:
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ('document', )
Model is as follows:
class Document(models.Model):
user = models.ForeignKey(User)
document = models.ImageField(upload_to=user_directory_path)
uploaded_at = models.DateTimeField(auto_now_add=True)
HTML Output for the manual example (in chrome):
<form method="post" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='2ZMTQTumTh5DS4nwVvAZv3IUSpM2o5LB' />
<input id="id_document" name="document" type="file" />
Document
<button type="submit">Upload</button>
</form>
HTML Output for the manual example (in safari):
<form method="post" enctype="multipart/form-data">
<input type='hidden' name='csrfmiddlewaretoken' value='DTLKigyikubFrJqrh4AHR61Lmkyutrsw' />
<input id="id_document" name="document" type="file" />
Document
<button type="submit">Upload</button>
</form>
HTML Output for the automatic example (in safari):
Document:
Upload
Many thanks, Alan.
Have you included (request.FILES) in your views.py file if not add like this .
def view(request):
if request.method == 'POST':
form = DocumentForm(request.POST,request.FILES)
if form.is_valid():
#Then Save your Form

django return and render a csrf_token and variable at the same time for two different forms

I have a view in my views.py file which looks like this:
def index(request):
c = {}
c.update(csrf(request))
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/register_success')
args = {}
args.update(csrf(request))
args['form'] = MyRegistrationForm()
return render_to_response('index.html', c), render_to_response('index.html', args)
and my index.html looks like this:
<form action="/accounts/auth/" method="post">{% csrf_token %}
<label for="username">User name:</label>
<input type="text" name="username" value="" id="username">
<label for="password">Password:</label>
<input type="password" name="password" value="" id="password">
<input type="submit" value="login" />
</form>
<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
{{form}}
<input type="submit" value="Register" />
</form>
I want to render c for the form whose action="/accounts/auth/" and render args for the form whose action="/accounts/register/".. any idea how I would go about doing so?
There's no need for two separate csrf tokens, and as your dictionary c contains no data other than the token, you can user render_to_response('index.html', args) to achieve what you want.
Or even better, use render(request, 'index.html', args). I would also recommend using a template context processor to get the csrf token in your view, as explained here.

Add an additional form with django-registration

I have a registration form that is rendered by the following urlconf --
url(r'^$',
register,
{'backend': 'registration.backends.default.UserBackend',
'template_name': 'index.html'},
name='auth_index'),
In the template, I have the following --
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register" />
</form>
How would I add additional forms and context to this template? I want to be able to have something like the following --
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Register" />
</form>
...
<form action='{% url waiting_list %}' method='post'>{% csrf_token %}
<p>Enter your email: <input type="text" name="email" value=""></p>
<input type="submit" name="email_submit" value="Submit Email">
</form>
{{message}}
How could I do this? (Preferably, all within a view). Thank you.
Your template is OK. Now you add the waiting_list url to your uelconf and implement it's view:
url(r'^waiting_list/$', 'myapp.views.waiting_list', {}, name='waiting_list'),
and:
# myapp/views.py
def waiting_list(request):
...
Since this is not data critical form, I would probably use #csrf_exempt to bypass csrf validation to makes thing easier. In case of error, redirect to an error page.
(BTW, usability wise, a better implementation for this problem might be posting the email with javascript.)