Form is not shown in html correctly.I wrote in search.html,
{% load static %}
<form action='/search/' method='POST>
<table>
{{ form.as_table }}
</table>
<input name="submit" type="Search" />
{% csrf_token %}
</form>
in views.py
def search(request):
form = SearchForm()
if request.method == 'GET':
return render_to_response(
'search.html', {'form': form}, RequestContext(request))
elif request.method == 'POST':
form = SearchForm(request.POST)
search_result = POST.objects.all()
if form.is_valid():
result = search_result.filter(Q(title__contains=form.cleaned_data['keyword']))
return render_to_response('search.html',{'form':form, 'result':result})
When I access search method,search.html is shown as strings like
now search.html
It is not From,so I really cannot understand why such a thing happens.No error happens but UserWarning: A {% csrf_token %}was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.
"A {% csrf_token %} was used in a template, but the context " is shown in terminal.How should I fix this?What is wrong in my code?
This may not be the issue, but I think your input tag is wrong, it should be this:
<input name="submit" type="Search">
As here : https://www.w3schools.com/tags/tag_input.asp
Related
When i am running my Django project on local server. It is returning whole html code on webpage.
Like after executing command python manage.py runserver and copy and pasting url on browser i am getting whole HTML file code instead element i have used.
My Html file
{% extends "wfhApp/base.html" %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registration</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form:</h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="" value="Register">
</form>
{% endif %}
</div>
{% endblock %}
My views.py
from django.shortcuts import render
from wfhApp.forms import UserForm
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
Above is from template inheritance.
Not 101% sure since you didn't really explained what you meant by "It is returning whole html code on webpage" but here:
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
you're not correctly passing the template context - or, more exactly, you are passing {'user_form': user_form} as the context and {'registered': registered} as the response's content_type (which would else be the default "text/html").
What you want is (splitted on two lines for readability):
context = {
'user_form': user_form,
'registered': registered
}
return render(request, 'wfhApp/registration.html', context)
I got some troubles with solving of "TypeError at /editprofile/
context must be a dict rather than set." in my Django project. I'm trying to allow the users to edit their personal information but I keep getting an error. I tried to read everything here and in other pages but nothing has helped, I would love to know how to solve this if anyone could direct me or give me some tips on how to fix this.
forms.py
class EditProfileForm(UserChangeForm):
class Meta:
model = User
fields = (
'username',
'email',
'country'
)
views.py
def editprofile(request):
if request.method == 'POST':
form = EditProfileForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return render(request, 'movies_app/profile.html')
else:
form = EditProfileForm(instance=request.user)
args = {'form', form}
return render(request, 'movies_app/editprofile.html', args)
editprofile.html
{% extends 'base.html' %}
{% block head %}
<title>Edit form</title>
{% endblock %}
{% block body %}
<form action="." method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
In your views.py args should be a dict, you should replace the , for a :.
I have a form that in layman's terms, has a bunch of buttons (that act like checkboxes) with values. Users can select a handful of buttons.
The buttons push their values (via a JQuery function) into a hidden input which I'm using to gather the values.
I would like to make sure that the "values=" attribute of each hidden input isn't null or "" when the user presses the submit form.
Ex: Make sure that the input does NOT equal this:
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden"> or
<input autocomplete="off" id="id_valuePlatform" name="valuePlatform" type="hidden" value="">
Here's the forms.py:
class getGames(forms.Form):
valuePlatform = forms.CharField(required=True, error_messages={'required': 'You need to tell us your platform(s)!'}, widget=forms.HiddenInput(attrs={'autocomplete': 'off'}))
Template:
<form method= "POST" autocomplete="off"> {% csrf_token %}
{{ form.non_field_errors }}
<div class="container">
{% if form.valuePlatform.errors %}
<ol>
{% for error in form.valuePlatform.errors %}
<li><strong>{{ error|escape }}</strong></li>
{% endfor %}
</ol>
{% endif %}
</div>
{{ form.valuePlatform }}
</div>
</div>
</form>
Views.py:
from .forms import getGames
def find(request):
form = getGames()
context = {"form": form}
if form.is_valid():
print form.cleaned_data['valuePlatform']
Is this even possible, or would I have to pass the data to Django via a Ajax POST?
Changed views.py to this, after looking at # Alasdair's examples in the documentation:
from .forms import getGames
def find(request):
form = getGames(request.POST or None)
context = {"form": form}
if request.method == 'POST':
if form.is_valid():
print form.cleaned_data['valuePlatform']
I'm getting this error when submit:
CSRF verification failed. Request aborted.
I've got this far following the documentation, but I don't fully understand it and it's definitely wrong. I just want to take a query word from my search box(form) and pass it to a python script as an argument. I'm new to Django and getting stuck on the easiest things.
In models.py:
class QueryForm(forms.Form):
query = forms.CharField(label='query',max_length=100)
I added this line to my urls.py
url(r'^results/$', 'tweemo.views.results'),
On my homepage where my search box is I have this code for my form:
<form action="/home/results/" method="post">
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
In views.py I added these two functions:
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
return render(request, 'results.html', {'form': form})
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
MY results.html contains just this:
<form action="/home/results/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit"/>
</form>
You must just add the {% csrf_token %} tag inside EVERY <form></form> tag which has method to be post in your template.
So the below markup should be corrected:
<form action="/home/results/" method="post">
{% csrf_token %}
<label for="query">Search:</label>
<input id="query" type="text" name="query" value="{{ current_query }}">
<input type="submit" value="ok">
</form>
Well the problem is that you are not passing the csrf token to the form , you need to pass the csrf token to the render function in order for it to be applied in the form . To accomplish this you need to associate the csrf token to the request.
def get_query(request):
if request.method == 'POST':
form = QueryForm(request.POST)
if form.isvalid():
return HttpResponseRedirect('/thanks/')
else:
form = QueryForm()
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('results.html', args)
def results(request):
return render_to_response('results.html',{'here':TwitterStream.objects.all() })
The example in https://docs.djangoproject.com/en/1.6/topics/forms/ demonstrates usage of form and has the following code:
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
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render(request, 'contact.html', {'form': form,})
and contact.html template is
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
I am wondering if it's possible in render(request,...,{'form':form,}) instead of specifying template file contact.html to pass variable with the contents of template, something like this:
html = """
<html>
<head> bla bla bla</head>
<body>
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
"""
return render(request, html, {'form': form,})
If it's possible what could be the drawbacks and risks associated with such approach?
Thanks in advance!
Not with render, which is a shortcut for loading a template, rendering it and returning a response. But you can do it with separate calls:
from django.template import RequestContext, Template
tpl = Template(html)
rendered = tpl.render(RequestContext(request, {'form': form}))
return HttpResponse(rendered)
The main drawback is that you're mixing the HTML in the python file, which makes it hard to read. Buy you could use this technique to load templates from the database or an api, for example.