In my html I am dynamically generating drop-down options with the same name
<form action="{% url manageCsv %}" method="post">
{% csrf_token %}
<p>
<input type="hidden" name="doc_id" value="{{ doc_id }}">
{% for column in file_columns %}
Column {{ forloop.counter0|add:1 }}
<select name="columns">
<option value="blank"></option>
{% for column_value in file_columns %}
<option value="{{ column_value }}">{{ column_value }}</option>
{% endfor %}
</select>
{% endfor %}
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
UPDATE:
My Views.py :
def manageCsv(request):
if request.method == 'POST':
file_id = request.POST['doc_id']
csvColumns = request.POST['columns']
print >> sys.stderr, csvColumns['columns']
return HttpResponseRedirect(reverse('index'))
In my view when I print my request.POST I get everythin I need :
<QueryDict: {u'csrfmiddlewaretoken': [u'lGlxVmiYI9xFb5bV7cJPrP9GR0t0LYTi'], u'doc_id': [u'14'], u'columns': [u'Organisation', u'Sum of products']}>
But the problem I am facing is that when I assign csvColumns = request.POST['columns'] , csvColumns prints out only Sum of products from the list and not the entire List [u'Organisation', u'Sum of products']
How can I get the entire list ? What have I missed ?
Any help on this would be great
Thanks in advance
Try to do it like this as explained in the docs:
csvColumns = request.POST.getlist('columns',None)
Hope this helps!
Related
I have a problem with the home page displaying form values. Although on the search page the values are fine. What could be the problem here? I copied the same form from the search page to the homepage but still, it doesn't work, the values are empty. Any hint is appreciated, thank you!
search page:
<form action="{% url 'search' %}">
<div class='flx around px'>
<input type='text' id='search-keyword' class='search-keyword form-control'
placeholder='keywords (pool,garage)'>
<select name='area' id='search-area' class='form-control'>
<option selected="true" disabled="disabled" selected>Area(All)</option>
{% for key,value in area_choices.items %}
<option value="{{ key }}" {% if key == values.area %} selected {% endif %}>{{ value }}</option>
{% endfor%}
</select>
</div>
<div class='flx around'>
<select name="bedrooms" class="form-control">
<option selected="true" disabled="disabled" selected>Bedrooms(All)</option>
{% for key,value in bedroom_choices.items %}
<option value = "{{ key }}"
{% if key == values.bedrooms %}
selected
{% endif %}
>{{ value }}</option>
{% endfor %}
</select>
<select name="price" class="form-control ">
<option selected="true" disabled="disabled" selected>Price(All)</option>
{% for key,value in price_choices.items %}
<option value = "{{ key }}"
{% if key == values.price %}
selected
{% endif %}
>{{ value }}</option>
{% endfor %}
</select>
</div>
<button type = "submit" class='btn fntmk my2 size'>Search <i class="fas fa-search size"></i></button>
</form>
home page:
<form action="{% url 'search' %}">
<div class = 'flx around px iphone'>
<input name = 'keywords' type = 'text' id = 'search-keyword' class = 'search-keyword form-control' placeholder = 'keywords (pool, garage)'>
<select name = 'area' id = 'search-area' class = 'form-control'>
{% for key,value in area_choices.items %}
<option value = "{{ key }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<div class = 'flx around iphone'>
<select name="bedrooms" class="form-control">
<option selected="true" disabled="disabled" selected>Bedrooms(All)</option>
{% for key,value in bedroom_choices.items %}
<option value = "{{ key }}">{{ value }}</option>
{% endfor %}
</select>
<select name="price" class="form-control ">
<option selected="true" disabled="disabled" selected>Price(All)</option>
{% for key,value in price_choices.items %}
<option value = "{{ key }}">{{ value }}</option>
{% endfor %}
</select>
</div>
<button type = "submit" class = 'btn fntmk my2 size'>Search <i class="fas fa-search size"></i></button>
</form>
view:
from .choices import price_choices, bedroom_choices, area_choices
def search(request):
queryset_list = Oglas.objects.order_by('-list_date')
# keywords
if 'keywords' in request.GET:
keywords = request.GET['keywords']
if keywords:
queryset_list = queryset_list.filter(description__icontains = keywords)
# Area
if 'area' in request.GET:
area = request.GET['area']
if area:
queryset_list = queryset_list.filter(area__iexact = area)
# rooms
if 'bedrooms' in request.GET:
bedrooms = request.GET['bedrooms']
if bedrooms:
queryset_list = queryset_list.filter(bedrooms__lte=bedrooms)
# price
if 'price' in request.GET:
price = request.GET['price']
if price:
queryset_list = queryset_list.filter(price__lte = price)
context = {
'area_choices' : area_choices,
'bedroom_choices' : bedroom_choices,
'price_choices' : price_choices,
'listings' : queryset_list,
'values' : request.GET,
}
return render(request, 'pages/search.html', context)
Form are handled completly different. You're mixing up the template with the form handling.
Have a look in the doc first. You need to add a form object into your context.
Extract from the mentioned doc:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
if I select all checkbox then my checkbox display only one thing
i want display multi select checkbox in django. what is problem in my code?
in html
<form action="" method="GET">
<label style="color: gray;" > 확장자 -</label>
{% for extention in file_extention %}
{% if extention.name == extention_name %}
<input type="checkbox" name="extention_name" value="{{ extention.name }}" checked>{{ extention.name }}
{% else %}
<input type="checkbox" name="extention_name" value="{{ extention.name }}"> {{ extention.name }}
{% endif %}
{% endfor %}
</form>
in views.py
if request.method == 'GET':
png = {'name' : '.png'}
jpg = {'name' : '.jpg'}
gif = {'name' : '.gif'}
file_extention = [png, jpg, gif]
context = {}
context['file_extention'] = file_extention
extention_name = request.GET.get('extention_name',None)
context['extention_name'] = extention_name
return render(request, 'home/index.html',context)```
You're currently breaking out of your IF statement when it hits the first match. Consider moving the if statement to within your input tag so each input tag in the loop is checked for matches. Something like this within your for loop should do it:
<input type="checkbox" name="extention_name" value="{{ extention.name }}"
{% if extention.name == extention_name %}checked{% endif %}>
{{ extention.name }}
I'm really stuck on this one. I have a working view/template that has a form select option that populates options from my model
views.py
def random(request):
classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block')
classblock = request.GET.get('class_block')
students = Student.objects.all().filter(classroom__course_block=classblock)
nicknames = [s.nickname for s in students]
data = serializers.serialize("json", students, fields = ("nickname", "attend"))
student_names = json.dumps(list(nicknames))
context = {'students': students}
context['classroom'] = classroom
context['student_names'] = student_names
context['data'] = data
template = loader.get_template('randomizer/randomize.html')
print (data)
return render(request, 'randomizer/randomize.html', context)
ramdomize template
{% extends 'randomizer/base.html' %}
{% load static %}
{% block body %}
<div id="djangorandom">
{{ classroom.id }}
<form action="{% url 'randomizer:random' %}" method="get">
{% csrf_token %}
<div class="form-group">
<select class="form-control" name="class_block">
{% for room in classroom %}
<option value={{ room.course_block }}>{{ room.get_course_block_display }}</option>
{% endfor %}
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
</div>
Page source returns:
<div class="form-group">
<select class="form-control" name="class_block">
<option value=11>Block 1-1</option>
<option value=13>Block 1-3</option>
<option value=14>Block 1-4</option>
<option value=P13>Pair 1-3</option>
</select>
</div>
Now I've copied a lot of this code for a slightly different template and purpose:
def pair(request):
classroom = Classroom.objects.filter(teacher=request.user).order_by('course_block')
classblock = request.GET.get('class_block')
students = Student.objects.all().filter(classroom__course_block=classblock)
nicknames = [s.nickname for s in students]
data = serializers.serialize("json", students, fields = ("nickname", "attend"))
student_names = json.dumps(list(nicknames))
context= {'classroom': classroom}
context['students'] = students
context['student_names'] = student_names
context['data'] = data
template = loader.get_template('randomizer/pairing.html')
print(data)
return render(request, 'randomizer/pairing.html')
{% extends 'randomizer/base.html' %}
{% load static %}
{% block body %}
<div id="djangorandom">
{{ classroom.id }}
<form action="{% url 'randomizer:pair' %}" method="get">
{% csrf_token %}
<div class="form-group">
<select class="form-control" name="class_block">
{% for room in classroom %}
<option value={{ room.course_block }}>{{ room.get_course_block_display }}</option>
{% endfor %}
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
</div>
But the page source doesn't show any of the options for the form selects:
<form action="/randomizer/pairing/" method="get">
<input type='hidden' name='csrfmiddlewaretoken' value='ADVUsnTserljrnDvRlmeTPyvjMOzva5xj7t8LSeDmPxnkBUtx4XmfXAI5aRfJky6' />
<div class="form-group">
<select class="form-control" name="class_block">
</select>
</div>
<span><input class="btn btn-default" type="submit" value="Submit"></span>
</form>
I've practically copied everything from the first view/template to the second view/template. I wondered if there was a scope issue where def pair re-uses the code from def random, but I commented out def random and that didn't help.
Your second view doesn't pass the context into the render() call, so there is no classroom variable and nothing to iterate over in the template.
(Note, in both views the template = loader.get_template(...) call is irrelevant and not used; you should remove those lines.)
In my template i have a multiple-choice-object like this:
<form action="/hmi/give_trend3/" method="get">
<p>
<select name="n" size="3" multiple="multiple">
{% for tag in tags %}
<option>{{ tag.name }}</option><br>
{% endfor %}
</select>
</p>
</form>
and i want to get all the values (of the multiple-choice) in my
views.py:
def give_trend3(request):
v = request.GET['v']
b = request.GET['b']
nn = request.GET['n'] ....
but in the value nn I find only the last value of the choices.
How do I do that?
Try this,
vals = request.GET.getlist("n", '')
Also bind the id to the options in your template,
<select name="n" size="3" multiple="multiple">
{% for tag in tags %}
<option value="{{ tag.id }}">{{ tag.name }}</option><br>
{% endfor %}
</select>
How to "remember" form selection value in Django?
{% load i18n %}
<form action="." method="GET" name="perpage" >
<select name="perpage">
{% for choice in choices %}
<option value="{{choice}}" {% if 'choice' == choice %} selected="selected" {% endif %}>
{% if choice == 0 %}{% trans "All" %}{% else %}{{choice}}{% endif %}</option>
{% endfor %}
</select>
<input type="submit" value="{% trans 'Select' %}" />
</form>
sorry about my words, but this seems a bad aproach. The django way to work with this is a simple form with a initial value for your selected choice. If you don't belive me, and you persist in this way, then change your template if as:
{% if choice == myInitChoice %}
Don't forget to send myInitChoice to context.
c = RequestContext(request, {
'myInitChoice': request.session.get( 'yourInitValue', None ),
})
return HttpResponse(t.render(c))
#register.inclusion_tag('pagination/perpageselect.html', takes_context='True')
def perpageselect (context, *args):
"""
Reads the arguments to the perpageselect tag and formats them correctly.
"""
try:
choices = [int(x) for x in args]
perpage = int(context['request'].perpage)
return {'choices': choices, 'perpage': perpage}
except(TypeError, ValueError):
raise template.TemplateSyntaxError(u'Got %s, but expected integer.' % args)
i just added takes_context='True' and take the value from context. The template i edited as
{% load i18n %}
<form action="." method="GET" name="perpage" >
<select name="perpage">
{% for choice in choices %}
<option value="{{choice}}" {% if perpage = choice %} selected="selected" {% endif%}>
{% if choice == 0 %}{% trans "All" %}{% else %}{{choice}}{% endif %}</option>
{% endfor %}
</select>
<input type="submit" value="{% trans 'Select' %}" />
</form>
Generally when you run into a common tasks, chances are there is an easy way to do it in django.
from django import forms
from django.shortcuts import render, redirect
FIELD_CHOICES=((5,"Five"),(10,"Ten"),(20,"20"))
class MyForm(froms.Form):
perpage = forms.ChoiceField(choices=FIELD_CHOICES)
def show_form(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
return redirect('/thank-you')
else:
return render(request,'form.html',{'form':form})
else:
form = MyForm()
return render(request,'form.html',{'form':form})
In your template:
{% if form.errors %}
{{ form.errors }}
{% endif %}
<form method="POST" action=".">
{% csrf_token %}
{{ form }}
<input type="submit" />
</form>