two-dimensional array Django - python

I have a two-dimension array in my django app which I need to pass to html template.
How I can make HTML handle two-dimensional array?
{% block content %}
<h2>Survey</h2>
<form>
{% for q in question %}
<p>{{q[0]}}</p>
<p>{{q[1]}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}
I got error:
Could not parse the remainder: '[0]' from 'q[0]'

{% block content %}
<h2>Survey</h2>
<form>
{% for q in question %}
<p>{{q.0}}</p>
<p>{{q.1}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}

Django just doesn't have a pre-setup way for passing multi-dimensional arrays to templates.
The best work-around is to separate the columns out manually like so... ("i" corresponds to each row in final output)
data = {}
for i, question_answer in enumerate(question_answer_pairs):
data[i]= {
'question':question_answer.question,
'answer':question_answer.answer
}
return render(request, 'survey.html', data)
Then in your template
{% block content %}
<h2>Survey</h2>
<form>
{% for key,value in data.items %}
<p>{{value.question}}</p>
<p>{{value.answer}}</p>
{% endfor %}
<input type="submit" value="submit">
</form>
{% endblock %}

Related

Trying to reverse posts from newer on top but I keep getting errors in Flask

Here is the code I'm trying to run in my Flask App
{% extends "bootstrap/base.html" %}
{% block title %}Testing title{% endblock %}
{% block content %}
<div class="container">
<h1>Posts</h1>
<h3>Postings</h3>
<form action="/" method="post">
<input hidden placeholder="Name" name="name">
<input placeholder="Post whatever you want..." name="post" required>
<button class="btn btn-primary" type="submit" value="Submit">Submit</button>
</form>
{% for post in posts reversed %}
<div>
{{ 'Anonymous' + ': ' + post[2] }}
</div>
{% endfor %}
</div>
{% endblock %}
This is the error I get jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 'reversed'
Figure reversed would work since I found some examples online that does that
The correct syntax in Jinja2 to loop through a list in reverse order is:
{% for post in posts|reverse %}
{{ post }}
{% endfor %}

MultipleChoiceField on multiple columns

I have a form in django:
country=forms.MultipleChoiceField(choices=lista_tari, widget=forms.CheckboxSelectMultiple(),required=True)
What i want is to display this form on multiple columns in the webpage. There are 30 choices, i want them on 6 or 5 or whatever columns.
This is the search.html:
{% block content%}
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}
I am brand-new to css, html and even django so any help would be of great help.
Thank you!
{% for field in form %}
{% ifequal forloop.counter 6 %}</ul><ul>{% endifequal %}
<li>{{ field }}</li>
{% endfor %}
you can try something like this
<form method="POST" class="post-form">{% csrf_token %}
<div class="form-check form-check-inline">
{% for field in form %}
{% if forloop.counter|divisibleby:3 %}</div><div class="form-check form-check-inline">{% endif %}
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% endfor %}
</div>
<button type="submit" class="save btn btn-default">Save</button>
</form>
But probably you should use django-bootstrap3 which helps you to integrate django and bootstrap.

How to get all the options submitted by form

How to get all the options submitted by the form in Django, this is the form which I used.
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.id}}.{{question.question_text }}</h3>
{% for option in question.options_set.all %}
<input type="radio" name="choice{{question.id}}" value="{{ option.options}}" > {{option.options}}<br>
{% endfor %}
{% endfor %}
<input type="Submit" name="Submit">
</form>
{% endblock%}
I tried selected_choice=request.POST ,but getting this as output csrfmiddlewaretokenchoice1Submitchoice3. How can I solve this? Thank you
In django request.POST is dictionary-like object, see details here.
So to obtain argument choice in view you can use following syntax:
selected_choice=request.POST.get('choice')
which return choice value or None in case this is empty.
Since request.POST is dict-like object you can use items() method to get all values and filter them:
for k, v in request.POST.items():
if k.startswith('choice'):
print(k, v)
this will print only those params with choice text in name.
selected_choice=request.POST.get('choice')
The above should work just fine, but if you're crazy, you can try this:
{% extends 'quiz/base.html' %}
{% block content%}
<h1>You are at quiz page</h1>
<form action="{% url 'quiz:process_data' %}" method="post" id= "crazyform">
{% csrf_token %}
{% for question in question_set %}
<h3>{{question.id}}.{{question.question_text }}</h3>
{% for option in question.options_set.all %}
<input type="radio" name="choice" value="{{ option.options}}" > {{option.options}}<br>
{% endfor %}
{% endfor %}
<input type="hidden" name="crazychoice" class="crazy" value="nothing">
<input type="Submit" name="Submit">
</form>
{% endblock%}
Then some JQuery:
$('#crazyform input').on('change', function() {
$(".crazy").val($('input[name=choice]:checked', '#crazyform').val())})
Everytime you click a radio button, the value of the hidden input field changes to the value of the selected radio button.
Then in your view you can:
selected_choice = request.POST.get("crazychoice", "")

Django Template to make a list to be sent as post

I am trying to make an MCQ quiz and I have used the following code in a template:
{% for MCQ in mcq %}
<input type="radio" name="MCQ" value="{{ MCQ.id }}">{{ MCQ.MCQ_Text }}
{% endfor %}
The problem is that I want to use MCQ_list = request.POST[MCQ] to access it as a list. How do I make a list in the template? Alternatively, is there a better way to approach this?
Edit:
The mcq is nested inside
{% for Questions, mcq in Quest_dic.items %}
<br>
{{ Questions.Question_Text }}
{% for MCQ in mcq %}
<br>
<input type="radio" name="ListOrAlternateHere" value="{{ MCQ.id }}">{{ MCQ.MCQ_Text }}
{% endfor %}
<hr>
{% endfor %}
change your input to type=checkbox. This will let you read the checked items as a list in python:
mcq_list = request.POST.getlist('MCQ')

Learning to use Jinja2 templates, missing URL values

I'm learning how to use Jinja2 templates (see code below). When I add an item to my form, I expect that the url will change to something like this.
http://localhost:8080/?food=steak&food=eggs&food=cheese
However, what ends up happening is that the first food will have a value, but everything else will be blank. It looks something like this:
http://localhost:8080/?food=asd&food=&food=
What am I doing wrong?
<form>
<h2>Add a Food</h2>
<input type="text" name="food">
{% if items %}
{% for items in items %}
<input type="hidden" name="food" value="{{item}}">
{% endfor %}
{% endif %}
<button>Add</button>
{% if items %}
<br>
<br>
<h2>Shopping List</h2>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
{% endif %}
</form>
Here is the function to render the HTML:
class MainPage(Handler):
def get(self):
items = self.request.get_all("food")
self.render("shopping_list.html", items=items)
For item in items?
{% for item in items %}
<input type="hidden" name="food" value="{{item}}">
{% endfor %}
I'm not certain, but I think the issue is with your <button> tag. Try something like <button type='submit'>. I think your current button just doesn't do anything.
w3 documentation here

Categories

Resources