In the template I get the whole DropDown correctly shown with something like this:
{{form.deal_type}}
But what if I wanted just the text of the selected dropdown shown?
This shows me just a foreignkey.
{{form.deal_type.value}}
I don't know why you want to do this exactly, but try this.
TO LOOP:
{% for value, text in form.deal_type.field.choices %}
{{ value }}: {{ text }}
{% if value == form.deal_type.value %}
<strong>{{ text }}</strong> <!-- THIS IS THE SELECTED ONE... -->
{% endif %}
{% endfor %}
EDIT:
I meant the above code as an illustration, not that you should use it verbatim. This code will do more like what you want.
{{ form.deal_type.label_tag }}
{% for value, text in form.deal_type.field.choices %}
{% if value == form.deal_type.value %}
{{ text }}
<input type="hidden" name="deal_type" value="{{ value }}" />
{% endif %}
{% endfor %}
I had a similar issue. To solve it I just passed the value to the template directly from the view. So in your view you presumably have something in the way of
data = {'form' :form,}
return render_to_response('destination.html', data, context_instance = RequestContext)
In data you are passing the form that includes deal_type. Add to
data a variable deal_type set equal to Object.deal_type.display_value with
data = {'form' :form,}
if Object.deal_type: data['deal_type'] = Object.deal_type.display_value
return render_to_response('destination.html', data, context_instance = RequestContext)
Then on your template you can just use
{% if condition_to_show_just_text %}
{{deal_type}} {{form.deal_type.as_hidden}}
{% else %}
{{form.deal_type}}
{% endif %}
It may be insiginificant in this case, but it seemed to me that if the list was long, iterating with the for loop on the template would be less efficient than pulling directly from the object
Related
I'd need to pass some data from my manually generated form to the template, and would need to check the presence of that information there.
I'm generating my form as such (in the __init__ part):
for i in days_in_month:
self.fields["info_%s" % i] = forms.ChoiceField(label="%s" % i.strftime("%a %d-%m-%Y"),
required=False,
choices=Information._meta.get_field('info').choices,
widget=forms.Select(attrs={'something': 'test'}))
What I would like to do, is to check in the template whether the attribute something is set, and if so, display its value (in the example above: test).
Any idea?
I tried with {{ field.attribute }} as per Access form field attributes in templated Django and the below:
{% for field in form %}
{{ field.label_tag }} {{ field }}
{{ field.widget.attrs.something }}
{% endfor %}
... but that doesn't work (invalid).
Ultimately I want to do something similar to:
{% if field.widget.attrs.something %}{{ field.widget.attrs.something }}{% endif %}
That would be
{{ field.field.widget.attrs.something }}
I have a list of events (with links) that I want to show as comma separated like
event1, event2, event3
I tried the solution here but not working for me.
Here is the code :
<p>
{% for element in event.getelement.all() %}
<a href="{{ build_absolute_url(url('main:home_getlink',link.uri)) }}">
{{ element }} </a>
{% endfor %}
</p>
Do:
<p>
{% for element in event.getelement.all %}
<a href="{{ build_absolute_url(url('main:home_getlink',link.uri)) }}">
{{ element }}
</a>{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
Also, what's up with that href? Are you not using named routes whereby you can simply leverage the {% url [route-name] [params] %} tag?
This shouldn't be a function call since it is inside template. Change below,
{% for element in event.getelement.all() %}
with
{% for element in event.getelement.all %}
And for rest, the solution link you've posted should work after that.
Edit:
If you do this,
{{ event.getelement.all|join:", " }}
So this might produce result something like,
GetElement object, GetElement object, GetElement object
to get the value of a specific attribute you have to add the attribute as well. Something like this,
{% for e in event.getelement.all %}
{{ e.<attr_name> }},
{% endfor %}
And this might produce something like,
event1, event2, event3,
Of course this is not an optimal solution because this is not the right way to do things when using any Framework.
Optimal solution:
What should be followed is that, do each and every logic in your views and send clean (pure) form of data to your templates. I mean send lists, dictionaries, objects, tuples should be sent to the templates. Hence creating a list of all the events and sending it templates though context.
Note: Following example is all based on assumptions.
View:
def xyz(request):
event = Event.objects.get(name='xyz')
context = {
'event_elements': [e.name for e in event.getelement.all()]
}
return render(request, 'xyz.html', context)
Template:
{{ event_elements|join:", " }}
Now this will definitely work.
This seems like it should be pretty straightforward, but for some reason I am unable to solve this problem. I'm using Django 1.4. I am trying to do a basic check to see if a list QuerySet is empty or not during template rendering, but the if statement I'm using seems always to evaluate to true.
I have a Django template that reads:
{% extends 'includes/base.html' %}
{% if object_list %}
...
{% block data %}
{% for object in object_list %}
...
{{ object.create_date }}
...
{% endfor %}
{% endblock data %}
...
{% endif %}
'base.html' has the block:
<body>
{% block content %}
...
<div class="row-fluid">
<div class="span12">
{% block data %}
<div align="center"><i>No data.</i></div>
{% endblock data %}
</div><!-- span12 -->
</div><!-- row -->
{% endblock content %}
...
</body>
The view function generating the QuerySet is here:
def barcode_track(request, model):
query = request.GET.get('barcode_search', '')
object_list = model.objects.all()
if query:
object_list = model.objects.filter(barcode__icontains=query)
return render_to_response('barcode_track/barcode_list.html',
{'object_list': object_list, 'query': query},
context_instance=RequestContext(request))
Which is called via this form:
<form id="barcode_search_form" method="get" action="" class="form">
<input type="text" name="barcode_search" value="{{ query }}" />
<button type="submit" class="btn">Search</button>
</form>
And the urls.py line:
urlpatterns = patterns('barcode_track.views',
url(r'^$', 'barcode_track', {'model': Barcode},
name="barcode_track"),)
The idea is that results will only be presented if they exist in object_list, and otherwise the parent block will remain unaltered. I have tried changing the name of object_list, and I have printed {{ dicts }} to the page to ensure that object_list is, in fact, empty (which it is). I am not using a generic view, although I realize that the name suggests as much. I have actually had this trouble in a different app I wrote using similar logic, so I must be doing something systematically incorrectly.
What am I missing here?
You can't wrap control flow tags like if around a block. Your problem is that the child template's definition for block data is being used simply because it's there.
You can fix it by placing the if tag inside block data. If you want to inherit the parent's contents when the list is empty, add an else case that expands to {{ block.super }}.
How can I get the value of form.field in template. I mean not the html input element of the field but the value inside the input?
To get the bound data (in 1.2.3)
{{ form.field.data }}
In the development version, it's {{ form.field.value }} which automatically pulls initial data OR bound data whereas it's an explicit call in the current release:
form.field.field.initial or form.field.data
Update: the admin forms work differently. First of all, the BoundField is {{ adminfield.field }} and not {{ adminfield }} in your comment, but we have bigger problems.
On the change form, the form is not bound so data can only be pulled from the initial dictionary passed into the form constructor. It's not accessible via the django template syntax.
Here's the relevant lines in BoundField:
if not self.form.is_bound:
data = self.form.initial.get(self.name, self.field.initial)
# you can't do this kind of lookup from the template.
The only way to access this type of info from the template without making a template tag (which you should!) is to loop through each key/value in the initial dictionary and comparing to the current fields name.
{% for line in fieldset %}
{% for adminfield in line %}
{% for k, v in adminfield.field.form.initial.items %}
{% if k == adminfield.field.name %}
{{ k }}:{{ v }}
{% endif %}
{% endfor %}
{% endfor %}
{% endfor %}
How can I know if a checkbox is checked (True, 1) having just the {{ form.checkbox }} form-tag?
'activo' is defined as (True, 1) in the db.
My template is:
{{ form.activo }}
RESULTS:
<input id="id_activo" type="checkbox" name="activo" checked="checked"/>
{{ form.activo.data }}
RESULTS:
False
{{ form.activo.value }}
RESULTS:
""
Yet no 1's or True's are coming through. :S
Any hint is appreciated. =')
It is checked if request.POST.has_key('activo') or the {{ form.activo.data }} actually returns True when initialized with request.POST.
Your question isn't quite clear, but maybe your problem has something to do with the fact, that browsers don't put anything in the POST data for an unchecked checkbox.
This made things complicated for me when I had to differentiate between a checkbox not being displayed at all and a displayed checkbox not having been checked. Just from looking at the POST data you can't tell those two cases apart.
Following on from your reply to mbarkhau's answer, using instance= doesn't make the form bound, it just provides default values to the form.
Here's the logic in a template:
{% if form.is_bound %}
{% if form.initial.activo %}
Checked.
{% else %}
Not checked.
{% endif %}
{% else %}
{% if form.activo.data %}
Checked.
{% else %}
Not checked
{% endif %}
{% endif %}
But it makes more sense to do this logic in the view and pass extra context. Something like:
context_data = {...}
if form.is_bound:
activo = form.data.get('activo')
else:
activo = form.initial.get('activo')
context_data['activo'] = bool(activo)
return render_to_response('your_template.html', context_data)
If you want a boolean condition in templates this should work:
{% if form.activo %}
--
{% else %}
---
{% endif %}