I can't understand, why this code is not work:
{% set t_c = 'param_1' %}
<div class="col-sm-9">
<select id="category" name="category" class="form-control " required>
<option></option>
{% for c in categories %}
{% if c.id|string == org.category.id %}
{% set t_c = 'param9' %}
<option value="{{ c.id }}" selected>{{ c.name }} </option>
{% else %}
<option value="{{ c.id }}">{{ c.name }} </option>
{% endif %}
{% endfor %}
</select>
</div>
<input id="category_h" name="category_h" type="hidden" value="{{ t_c }}">
Why t_c in last line is 'param_1', when condition {% if c.id|string == org.category.id %} is true?
Thanks.
UPDATE
I have fast solution on JavaScript with jQuery+Select2 like:
var category = $("#category"),
category_h = $("#category_h");
category.select2();
category_h.val(category.find("option:selected").text());
t_c = 'param9' is local to the scope of the for loop
There are workarounds to extend beyond inner block scope
Related
Want to filter data with multiple values in django.Currently i can only take two value from html but only one value filtering
This is my views code
p = request.GET.getlist('passout',[])
c = request.GET.getlist('course',[])
s = request.GET.getlist('skill',[])
search_variables = {}
if p:
for l in p:
search_variables['passout__yearofpassing__contains'] = l
print("#####",p)
if s:
for j in s:
search_variables['skill__skill_name__contains'] = j
if c:
for k in c:
search_variables['course__course_name__contains'] = k
print("##kk",k)
datas_list = Student.objects.filter(
**search_variables, status="Active").order_by('id')
This is html code
<div class="col col-sm-3" style="margin-right:-80px;">
<select class="selectpicker" id="passout" name="passout" placeholder="Select YOP" multiple >
{% for j in p %}<option value="{{ j }}" selected>{{i.yearofpassing}}</option> {% endfor %}
{% for i in yr %}
<option value="{{i.yearofpassing}}">{{i.yearofpassing}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right:-80px;" >
<select class="selectpicker" name="course" id="course" placeholder="Select Course" multiple >
{% for j in c %}<option value="{{ j }}" selected >{{i.course_name}}</option> {% endfor %}
{% for i in cr %}
<option value="{{i.course_name}}">{{i.course_name}}</option>
{% endfor %}
</select>
</div>
<div class="col col-sm-3" style="margin-right: -350px;">
<select class="selectpicker" id="skill" name="skill" placeholder="Select Skills" multiple >
{% for j in s %}<option value="{{ j }}" selected >{{i.skill_name}}</option>{% endfor %}
{% for i in sl %}
<option value="{{i.skill_name}}" >{{i.skill_name}}</option>
{% endfor %}
</select>
</div>
<button id="search4" style="margin-left: 320px; " class="au-btn btn-info btn-sm" >Search </button>
<button id="search" style="margin-left: 1px; " class="au-btn btn-info " > <i style="font-size:medium; margin-bottom: 1px; " class='fas fa-sync'></i></button>
in this image i search student with year of passout 2019 it shows a result
if i search with two or three values it shows nothing but in db the students are present
the thing is that you don't have that data for all search filters because Django filter work with AND operator and in your image you said give me a result that happened in 2019 AND 2020 and this is not possible.
the filter is working you just need to store the right data.
I output datalist, but output pk. I read that it can be removed in data-value like this https://stackoverflow.com/a/48076273/9653855
How can I rewrite the code so that my datalist is displayed in this format <option data-value="1" value="DjangoOneLove"></option>?
my forms
class ListTextWidget(forms.Select):
template_name = 'include/_forms_orders_datalist.html'
def format_value(self, value):
if value == '' or value is None:
return ''
if self.is_localized:
return formats.localize_input(value)
return str(value)
class ChoiceTxtField(forms.ModelChoiceField):
widget=ListTextWidget()
class SimpleOrderAddForm(forms.ModelForm):
#service = forms.ModelChoiceField(queryset=Service.objects.all(), widget=ListTextWidget())
service = ChoiceTxtField(queryset=Service.objects.order_by('-used'))
class Meta:
model = Orders
fields = ['service']
my forms_orders_datalist.html
<input id="ajax_input_{{ widget.name }}" list="{{ widget.name }}" autocomplete="off"
{% if widget.value != None %} name="{{ widget.name }}" value="{{ widget.value|stringformat:'s' }}"{% endif %}
{% include "django/forms/widgets/attrs.html" %}>
<span class="badge rounded-pill bg-warning text-dark" id="ajax-{{ widget.name }}" name="ajax-{{ widget.name }}"></span>
<datalist id="{{ widget.name }}">
{% for group_name, group_choices, group_index in widget.optgroups %}
{% if group_name %}
<optgroup label="{{ group_name }}">{% endif %}{% for option in group_choices %}
{% include option.template_name with widget=option %}{% endfor %}{% if group_name %}
</optgroup>{% endif %}{% endfor %}
</datalist>
My model has this in it:
start_date = models.DateField(default=datetime.date, blank=True)
stop_date = models.DateField(default=datetime.date, blank=True)
In my view I have:
start_date = datetime.date(int(request.POST.get('start_year')),
convert_month_to_int(request.POST.get('start_month')),
int(request.POST.get('start_day')))
end_date = datetime.date(int(request.POST.get('end_year')),
convert_month_to_int(request.POST.get('end_month')),
int(request.POST.get('end_day')))
before I save to the DB.
And the HTML is this:
<label class="col-md-4"> Start Date: </label>
<select class="selectpicker" data-width="auto" name="start_month" id="start_month" required>
{% for month in month_list %}
<option value="{{ month }}" {% if path_start and path_start.1 == month %} selected {% endif %}> {{ month }} </option>
{% endfor %}
</select>
/
<select class="selectpicker" data-width="auto" name="start_day" id="start_day" required>
{% for day in day_list %}
<option value="{{ day }}" {% if path_start and path_start.2 == day %} selected {% endif %}> {{ day }} </option>
{% endfor %}
</select>
/
<select class="selectpicker" data-width="auto" name="start_year" id="start_year" required>
{% for year in year_list %}
<option value="{{ year }}" {% if path_start and path_start.0 == year %} selected {% endif %}> {{ year }} </option>
{% endfor %}
</select>
</div>
<div class="row">
<label class="col-md-4">End Date: </label>
<select class="selectpicker" data-width="auto" name="end_month" id="end_month">
{% for month in month_list %}
<option value="{{ month }}" {% if path_end and path_end.1 == month %} selected {% endif %}> {{ month }} </option>
{% endfor %}
</select>
/
<select class="selectpicker" data-width="auto" name="end_day" id="end_day">
{% for day in day_list %}
<option value="{{ day }}" {% if path_end and path_end.2 == day %} selected {% endif %}> {{ day }} </option>
{% endfor %}
</select>
/
<select class="selectpicker" data-width="auto" name="end_year" id="end_year">
{% for year in year_list %}
<option value="{{ year }}" {% if path_end and path_end.0 == year %} selected {% endif %}> {{ year }} </option>
{% endfor %}
</select>
I get the error 'Required argument 'year' (pos 1) not found' when I try to save. I can't figure out why this is happening. Any advice would be appreciated. Thanks.
I have an html template that includes some Python code and HTML templates. This is a sample below.
Python:
cur1 = g.db.execute('select ID from Students')
students = [dict(ID=row[0]) for row in cur1.fetchall()]
cur2 = g.db.execute('select ID from Quizzes')
quizzes = [dict(ID=row[0]) for row in cur2.fetchall()]
if request.method == 'POST':
if not session.get('logged_in'):
abort(401)
g.db.execute('insert into Results (quiz,student,grade) values '\
'(?,?,?)',[request.form['Quiz'],
request.form['Student'],
request.form['grade']])
g.db.commit()
return render_template('add_result.html',students=students,quizzes=quizzes)
HTML:
<form action="{{ url_for('add_result') }}" method=post>
<select name="Quiz">
{% for quiz in quizzes %}
<option value="{{ quiz }}">{{ quiz.ID }}</option>
{% endfor %}
</select>
<select name="Student">
{% for student in students %}
<option value="{{ student }}">{{ student.ID }}</option>
{% endfor %}
</select>
<input type="number" name="grade">
<input type="submit" value=Submit>
</form>
which outputs the drop down lists in the format I want (integers), however, for example, say the values quiz #1 and student #1 with a grade of 100, they are then input into SQLite as
(2, u"{'ID': 1}", u"{'ID': 1}", 100.0)
How can I get this output?:
(2,1,1,100.0)
You need to convert the values to the right type before sending them to the database. The request.form dict provides a get method that will convert values or raises an error.
g.db.execute(
'insert into Results (quiz,student,grade) values (?,?,?)',
(
request.form.get('Quiz', type=int),
request.form.get('Student', type=int),
request.form.get('grade', type=float)
)
)
It would be much easier (and safer) in the long run to use a form library such as Flask-WTF to parse, convert, and validate the data for you. Also consider using an ORM such as Flask-SQLAlchemy rather than writing raw SQL statements.
The problem was in the HTML:
<select name="Quiz">
{% for quiz in quizzes %}
<option value="{{ quiz }}">{{ quiz.ID }}</option>
{% endfor %}
</select>
<select name="Student">
{% for student in students %}
<option value="{{ student }}">{{ student.ID }}</option>
{% endfor %}
I had "quiz" and "student" as the s, with quiz.ID and student.ID appearing as text in the values. It is the option value that gets returned by the form.
It should be:
<select name="Quiz">
{% for quiz in quizzes %}
<option value="{{ quiz.ID }}">{{ quiz.ID }}</option>
{% endfor %}
</select>
<select name="Student">
{% for student in students %}
<option value="{{ student.ID }}">{{ student.ID }}</option>
{% endfor %}
i am fairly new to Django and Python and have the following problem:
I have a quiz with multiple answers.
Every answer has a form attached to it, which posts data to a view that creates an objects from a Model.
But i cant post all forms, because its only posting the 5th one.
views.py:
def quiz(request, quiz_id=1):
cs = {}
cs.update(csrf(request))
height=75*Frage.objects.count()
height_menu = height + 10
if Frage.objects.count() == 0:
height = 170
height_menu = height
len_quiz = len(Quiz.objects.get(id=quiz_id).title)
count=Frage.objects.filter(quiz=quiz_id).count
count_aw = 0
aw = Frage.objects.filter(quiz=quiz_id)
cs.update({'quiz': Quiz.objects.get(id=quiz_id),
'Frage': Frage.objects.filter(quiz=quiz_id),
'len': len_quiz,
'hg': height,
'hg_m': height_menu,
'user': request.user,
'aw': Antwort.objects.all(),
'count': count,
'count_aw': count_aw})
return render_to_response('quiz.html', cs)
def check_view(request):
check = request.POST.get('aw_check', '')
user_id = request.POST.get('user_log', '')
user_act = User.objects.get(id=user_id)
frage_id = request.POST.get('frage', '')
frage = Frage.objects.get(id=frage_id)
antwort_id = request.POST.get('antwort', '')
antwort = Antwort.objects.get(id=antwort_id)
richtig = request.POST.get('richtig', '')
quiz_id = request.POST.get('quiz', '')
quiz = Quiz.objects.get(id=quiz_id)
res = Results(quiz=quiz, frage=frage, user=user_act, richtig=richtig, choice=check, aw=antwort)
res.save()
return HttpResponseRedirect('/quiz/all/')
template:
{% if Frage.count == 0 %}
<br>
<h1 id="main_link" style="text-align: center" align="center">Keine Fragen vorhanden!</h1>
{% endif %}
<ol>
{% for Frage in Frage %}
<li><div id="frage">{{Frage.content}}</div></li>
{% for aw in Frage.antworten.all %}
<form action="/quiz/check/" name="{{ aw.content }}" method="post">{% csrf_token %}
<label for="aw_check">{{ aw.content }}</label>
<input type="checkbox" name="aw_check" id="aw_check">
<input type="hidden" name="user_log" value="{{ user.id }}">
<input type="hidden" name="frage" value="{{ Frage.id }}">
<input type="hidden" name="antwort" value="{{ aw.id }}">
<input type="hidden" name="quiz" value="{{ quiz.id }}">
{% if aw.richtig %}
<input type="hidden" name="richtig" value=True>
{% else %}
<input type="hidden" name="richtig" value=False>
{% endif %}
<input type="submit" value="Abgeben" />
<br>
</form>
{% endfor %}
{% endfor %}
</ol>
<script language="javascript">
function call_submitforms(){
{% for Frage in Frage %}
{% for aw in Frage.antworten.all %}
setTimeout("document.{{ aw.content }}.submit()",1000);
{{ check.it }}
{% endfor %}
{% endfor %}
}
</script>
<input type="button" value="Abschicken" onclick="call_submitforms()" />
I think you should redesign your program. My understanding is that form submission can only handle one form. Here are some work-arounds using Django/Python. But, for your case, if you're designing a quiz, all of the answers should be part of a single form. Instead of returning {% for Frage in Frage %} I would do something like this (you'll have to redesign your models and views first):
//one form contains all questions
form action="/quiz/check/" name="{{ aw.content }}" method="post">{% csrf_token %}
//list the questions as part of that form
{%for Frage in quiz.Frages%}
<input type="hidden" name="user_log" value="{{ user.id }}">
<input type="hidden" name="antwort" value="{{ aw.id }}">
<input type="hidden" name="quiz" value="{{ frage.id }}">
{% endfor %}
//submit all of the data for each page of the quiz in one form
<input type="hidden" name="richtig" value=True>
{% else %}
<input type="hidden" name="richtig" value=False>
{% endif %}
<input type="submit" value="Abgeben" />