I'm trying to have my form not display (display:none;) if the maximum number of people signed up for a specific event is reached/exceeded. signups is a model with fields eventname and fullname. I'm also using a ListView, FormView to loop through the list of events, each with a sign up form.
I'm trying to do something like:
<form action="/events/" class="form" method="POST" style="{% for signups in signup %}{% if signups.eventname == events.name %}*counter increment here*{% if *counter value* >= events.maximum %}display:none;{% endif %}{% endif %}{% endfor %}" id="{{ events.name }}" name="{{ events.name }}">
{% if signups.eventname == events.name %} checks the model signups for objects with matching eventnames so that only objects for the wanted event is counted.
This is all inside of {% for events in events_list %}{% endfor %} and consider text inside asterisks comments.
How would I do this? If you would like to see any other files or information, I will gladly edit this.
Think you're going about ths the wrong way. Get the number of people signed up first in your view which you can then pass to your template as a template variable and make an if condition something like this:
{% if (signed_up_variable) < (max number) %}
# display the form
{% endif %}
Although, if i recall correctly ifequal may be deprecated, so adjust that accordingly.
i guess you need forloop.counter . https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#for
Related
I have a context dictionary entry objectives that maps objective query objects to a list of tests that belong to that objective. Example code:
objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
tests = Test.objects.filter(objective=objective)
context_dict["objectives"][objective] = tests
In my django html template, I iterate over objectives and display them. I then want to iterate over the tests that belong to these objectives. When I do this:
{% for test in {{ objectives|get_item:objective }} %}
I get a TemplateSyntaxError: 'for' statements should use the format 'for x in y':
In the application/templatetags directory, I have:
from django.template.defaulttags import register
...
#register.filter
def get_item(dictionary, key):
return dictionary.get(key)
If instead I make {{ objectives|get_item:objective }} a JS variable, I see that it does indeed produce a list, which I should be able to iterate over. Of course, I can't mix JS variables and the django template tags, so this is only for debugging:
var tests = {{ objectives|get_item:objective }}
var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']
How do I iterate over this list in the django template tag?
You cannot user {{...}} inside the {%...%}
What you can try is changing your filter to an assignment tag and using that value in the loop
#register.assignment_tag
def get_item(dictionary, key):
return dictionary.get(key)
And then in your template use it as
{% get_item objectives objective as tests %}
{% for test in test %}
....
{% endfor %}
Instead of all this if your models are proper with foreign keys I would do something like
{% for objective in requirement.objective_set.all %}
{% for test in objective.test_set.all %}
....
{% endfor %}
{% endfor %}
In my context I would pass only the requirement
You already have an answer, but note that dropping the {{ }} tags and keeping everything else the same would have worked fine.
{% for test in objectives|get_item:objective %}
**This is Right Answer for Using Django if else and for loop **
Note :- We Have to Put Key in " " string (Double quotes) some time produce an error so That is good way bcz i faced that problem whwn i Learned
{% if 'numbers'|length > 0 %}
{% for i in numbers %}
{% if i > 20 %}
{{i}}
{% endif %}
{% endfor %}
{% else %}
Empty
{% endif %}
I want to add a '*' before (or after) label's text in case the filed is required.
I can do this now by using this in my template:
{% for field in form %}
<label for="{{ field.name }}">
{{ '*' if field.flags.required }}{{ field.label.text }} :
</label>
{{ field }}
{% endfor %}
Is there some better way than this, at least a way to avoid adding label element manually?
That's how you do it, there is no simpler way than by checking the flag and then outputting what you want. You can change the text of the label somewhat more directly, though. You could also make a macro out of it so you don't need to copy and paste as much for each field in each template. Create a template "forms.html":
{% macro form_field(field) %}
{% if field.flags.required %}{{ field.label(text='*' + field.label.text) }}
{% else %}{{ field.label }}{% endif %}:
{{ field }}
{% endmacro %}
Then use it in other templates:
{# import the macro at the top of the template #}
{% from "forms.html" import form_field %}
{# use it in your for loop #}
{% for field in form %}
{{ form_field(field) }}
{% endfor %}
I've tried to find a better answer to this question and in my case this css trick worked very well and I did not have to alter anything else:
add a file to the-flask-wtf-project/app/static/styles/custom.css
with the following content in it:
div.required label:after {
content: " *";
color: red;
}
Then make sure to include the css in base.html (or all your templates using forms) inside the {% block scripts %}
<link rel="stylesheet" type="text/css" href="{{url_for('static',filename='styles/custom.css') }}">
I still consider myself a newbie so if this tips is off somehow please chime in.
Just my 2 cents, that I was very pleased with and could not find easily on any other thread here or elsewhere.
Following Henrik Andreasson's answer (thanks to his suggestion), I would like to add some more precision, because I spent few hours understanding how to avoid to do macros, like on the answer of davidism.
In the html file, you should add the attribute required:
<label for="{{ field.name }}" required="">
In my case, I was also doing a project on Flask with WTForms, so instead of what was written above, I did:
{{ form.field.label(required=form.field.flags.required) }}
In the css file, you should add:
label[required]:after {
content: " *";
}
which means:
after all the tags label containing the attribute required, add all the things in the dictionary.
Hope it helps.
I'm trying to use this app in my project.
https://github.com/streema/django-favit
I already can use the fav-unfav part of this app. I also want to list favourites of user for every user. In read me part it says use this and it will be listed but I have an error with
{% with user_favorites <user> "baslik.Entry" as favorite_list %}
{% for fav_obj in favorite_list %}
{{ fav_obj }}
{% endfor %}
{% endwith %}
Error:
TemplateSyntaxError at /
u'with' expected at least one variable assignment
This is the template tag part for user_favorites:
#register.assignment_tag
def user_favorites(user, app_model=None):
"""
Usage:
Get all user favorited objects:
{% with user_favorites <user> as favorite_list %}
{% for fav_obj in favorite_list %}
{# do something with fav_obj #}
{% endfor %}
{% endwith %}
or, just favorites from one model:
{% with user_favorites <user> "app_label.model" as favorite_list %}
{% for fav_obj in favorite_list %}
{# do something with fav_obj #}
{%
{% endwith %}
"""
return Favorite.objects.for_user(user, app_model)
How can I get rid of this error? Thanks.
It's a reasonably common convention in documentation that anything in angle brackets is a placeholder to be replaced by the actual value. In this case, <user> is supposed to be replaced by the object containing the actual user.
{% with user_favorites request.user ...
I must say, though, that the documentation still doesn't make any sense. You can't use an assignment tag in a with statement like that - even after correcting the user issue, this still won't work. The confusing thing is that the same syntax is repeated throughout the documentation, but it simply doesn't work.
I think this is simply a bug with the documentation, and suspect that if you simply remove the word "with" this will work.
To use custom template tag in django, it is needed to explicitly load it in template.
Add this line at the beginnig of your template (but after {% extends ... %}, if you have such):
{% load favit_tags %}
Looks like this step is missed from django-favit README.
I want to filter a result of a field in django in an html file.
Something like this
{{ model.field where id = 2 }}
I've been looking for in django docs but i only could find a way to do it on the views.py.
I also so something like javascript when u write a "|" simbol after the request but i still couldnt archieve it
You can use the {% if %} template tag. So:
{% if model.field == 2 %}
# do something
{% endif %}
Here is the official documentation:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#operator
Edit:
If model.field has a value of 2 then it just needs to be the above.
Edit 2:
Without seeing your code, it is hard to tell, but here is how to filter for Users based on Gender in a template:
{% for user in users %}
{% if user.gender == "male" %}
# do something
user.username
{% endif %}
{% endfor %}
I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.
{% for q in questions %}
<div class="question_wrap">
<h2>{{ q }}</h2>
# this does not work
{% if not request.session.get(str(q.id), False) %}
<!-- show them vote options -->
{% else %}
<!-- dont show options -->
{% endif %}
</div>
{% endfor %}
The syntax of Django templates is very limiting in order to prevent people from putting too much logic inside templates and doesn't allow you to pass parameters to methods.
You can prepare a list of tuples already in the view or write a simple template tag for that. The first options is usually easier:
In the view:
questions = [(q, request.session.get(str(q.id), False)) for q in questions]
In the template:
{% for q, has_voted in questions %}
...
{% endfor %}