I have an Area model, and I have Service model. Area is a Foreignkey of Service.
I want a template which shows each Service grouped under its respective Area, i.e.
Area 1
- service a
- service b
Area 2
- etc.
I've passed in an object list of all services to service_list.html. I have a custom tag get_areas which returns the areas, on which I can create the Area divisions, and from which I can potentially pass an area name to a service filter. But since I can't filter (can I?) in {% for service in object_list %}, how can I filter the service list in each Area's section of the HTML?
Thanks so much in advance.
If you post your models I can give you the exact code, but in general something like this should work:
# Pass in 'areas' variable from view with all required areas
{% for area in areas %}
{{ area.name }}
{% for service in area.service_set.all %} #Gets all the services associated with an area
{{ service.name }}
{% endfor %}
{% endofor %}
Not sure you even need a custom tag, but maybe I just don't understand that part.
Take a look at the regroup template tag. It was built for exactly the same purpose
https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#regroup
One thing that I have realized is that once you get the point of displaying complex interrelated data in your templates, that it makes sense to transform the data into an appropriate object (generally a list of dictionaries) before passing them onto the template.
That way, you can test your information easier, and have a much easier time displaying it. (You'll have much powerful tools at your disposition in Python based Views than in Django Templating Language).
#Maz - thank you for that. I'm learning at the moment and need to look at service_set.
#arustgi - that worked perfectly. For the benefit of fellow novices stumbling over this, I pass in 'queryset': Service.objects.all() and use:
{% regroup object_list by area as area_list %}
{% for area in area_list %}
<h2 class="separate">{{ area.grouper }}</h2>
{% for service in area.list %}
<div class="column">
<h3>{{ service.title }}</h3>
{{ service.body }}
</div>
{% endfor %}
{% endfor %}
Concise, descriptive code. Many thanks, both of you
Related
In trying to keep with DRY, I'm setting up my Django project HTML files now. I have successfully extracted most repeated information to my base.html page. On most (but not all) of my pages, my content is displayed within a general 'panel' which is basically just a container set-up with styling, but it's got a few div-tags to it so it looks a bit ugly and I'm having to type out the exact same code out several times on each page.
My idea was to extract this to a 'panel.html' then call it whenever I need it, for example some pages might just have one 'panel' whereas my dashboard (it's an administrative site) will have maybe 15+. So it seemed a better idea and cleaner to not have to type out all this code each time I need to set up a 'panel'.
My ideal page would look something like..
{% extends 'base.html' %}
{% block content %}
{% extends 'panel.html' %}
{% block panel_content %}
Panel content...
{% endblock panel_content %}
{% extends 'panel.html' %}
{% block panel_content %}
Second panel content
{% endblock panel_content %}
{% endblock content %}
I know I can't use extends multiple times but I'm using it just as an example for what it is I'm trying to achieve.
I am going to potentially have hundreds of these identical 'panels' across my site but each containing different content and it would be so much cleaner if I could just have one stored somewhere in a HTML file and call it however many times I need.
Is there a way to do this?
You can use include
{% include "panel.html" %}
I should mention that too many include statements create a performance issue.
I have a brain model with different resolutions and I want to let the user to change the resolution of the the model by just choosing his desired resolution from a select tag.
I mean I have the complete models loaded and without sending a POST to the server I want to change the view of the brain model.
The problem is that I can't pass the read value from the select to my django tag to choose the suitable moedl to render.
This is my code:
<body>
<select id="resolution_options" onchange="change_brain_resolution()" name="resolution_options">
{% for brain in brains %}
<option value="{{ brain.resolution }}">
{{ brain.resolution_title }}
</option>
{% endfor %}
</select>
<script>
function change_brain_resolution() {
var selcted_resolution = getElementById('resolution_options').value;
{% for brain in brains %}
// Here is my problem !!
{% if brain.resolution == selcted_resolution %}
// Do drawing
{% endfor %}
}
</script>
</body>
The reson of why I don't want to do a POST is because there are many other things the user have been drawing and doing and he may want to change the resolution of the brain model in order to have a better view or performance but he wants to keep the other objects in the scene
Thank you very much.
Try this:
function change_brain_resolution() {
var selcted_resolution = getElementById('resolution_options').value;
{% for brain in brains %}
if (selcted_resolution == {{ brain.resolution }}) {
// Do drawing
}
{% endfor %}
}
This ends up putting logic for every brain resolution on your client side. If you want to be more efficient, you have to pass the selected resolution to server with AJAX, and render the response.
Remember that templates are rendered before the page, hence they don't have access to value of javascript variables. If you want to pass javascript variables to server, you should do so after page load with an AJAX request.
I am generating some Django template code on the fly, in order to display rows in tables that are not stored in
a Django database and do not have models. I know the database and I can introspect them if needed, but I don't want
to write code by hand.
For example, field PSOPRDEFN.OPRCLASS stores an optional reference to a particular row where PSCLASSDEFN.OPRID=PSOPRDEFN.OPRCLASS, essentially a foreign key relationship. If there is no relationship PSOPRDEFN.OPRCLASS has one ' ' (space character) in it.
I also have a page for a given PSCLASSDEFN row, where the url is:
url(r'^(?i)permissions/(?P<CLASSID>[A-Z0-9_&]{1,50})/$',
'pssecurity.views.psclassdefn_detail',
name="psclassdefn_detail"),
Note that the ?P CLASSID regular expression does not allow for blanks which corresponds to gets stored in the PSCLASSDEFN table - I figure it's safer to limit what the user can put in the url request.
Back to my generated template: I want to hyperlink to the relation, if it exists. I feed my home-grown template generator a json "directive" indicating what I want put into the template (thanks for the inspiration, django-tables2):
....
{
"colname": "LANGUAGE_CD"
},
{
"urlname": "security:psclassdefn_detail",
"colname": "OPRCLASS",
"kwargs": [
{
"colname": "dbr",
"accessor": "dbr"
},
{
"colname": "CLASSID",
"accessor": "inst.OPRCLASS"
}
]
},
...
Some fairly trivial code generation then results in:
<div class="row">
<div class="col-xs-6 fieldlabel" title="LANGUAGE_CD" >Language Code</div>
<div class="col-xs-6 fieldvalue text-left _fv_LANGUAGE_CD">{{inst.LANGUAGE_CD}}</div>
</div>
<div class="row">
<div class="col-xs-6 fieldlabel" title="OPRCLASS" >Primary Permission List</div>
<div class="col-xs-6 fieldvalue _fv_OPRCLASS">
{% if inst.OPRCLASS|slugify %}
{{inst.OPRCLASS}}
{% endif %}
</div>
</div>
My problem is that started getting random Template url resolution errors when displaying some of the PSOPRDEFN data. I eventually tracked it down to the blank OPRCLASS fields in some rows.
In order to avoid this I first added
{% if inst.OPRCLASS %}
<a ...></a>
{% endif %}
That didn't work because the field is not empty, it is blank (and therefore doesn't match the CLASSID regex). So, this is where I read the filter docs again and found that slugify strips out blanks and non-alpha.
{% if inst.OPRCLASS | slugify %}
<a ...></a>
{% endif %}
Works, as a workaround. The problem is that CLASSID only stores alphanum, but that's not always true for other fields. I wouldn't mind introspecting the table column definition at template generation runtime to see what to do, but I need to find an appropriate way to disable url reversal, for only some rows.
Questions. Is there a better filter, such as a |strip? I suppose I could always build my own filter.
Even better, is there a tag to selectively catch NoReverseMatch' exceptions at template generation time?
{% try NoReverseMatch %}
{{inst.OPRCLASS}}
{% endtry %}
The reason I was so verbose in my description is because this is not something that can be worked around using Models. And neither can I custom-tune the template by hand. I find Django works quite well without models in most cases, but url reversing in templates can be quite brittle when a few rows of data do not match expectations. Hardening it would be very beneficial.
You can assign the result of the url tag to a variable.
{% url 'path.to.view' arg arg2 as the_url %}
{% if the_url %}
link
{% else %}
No link
{% endif %}
This syntax does not raise an exception if reversing the view fails.
I'm probably missing something very obvious but can't see anything in the documentation. I have a carousel with a and each will hold an image. However I've added 6 but I want to add an if statement so if an Image has not been added you don't see a blank space, where there is no content inside the .
Here is what i've tried so far:
{% if "Carousel 1" %}
<li>
{% placeholder "Carousel 1" %}
</li>
{% endif %}
Attempt 2:
{% placeholder "Carousel 1" as cara1 %}
{% if cara1 %}
<li>
{{ cara1 }}
</li>
{% endif %}
Not sure if there is something differnt i need to be doing for the django-cms template tags?
Any help would be much appreciated. Docs here - http://docs.django-cms.org/en/latest/advanced/templatetags.html#placeholder
Not to be rude, but your approach is way, way off :)
Placeholders hold Content Plugins. Content Plugins are responsible for how they render their contents.
My advice would be to create or find a carousel content type plugin. This plugin will hold multiple images or "CarouselImage" model instances that you can iterate over, and also specify a template with which to render itself.
In this template resides the conditional statement you're wanting to check for. Placeholders are just that - places held for content plugins.
in wordpress your template automatically kicks out a '.current_page_item' on your menu.
I am wondering if there is a django way of doing this?
Well django is not wordpress and also not a cms, but it could be used as one.
In this case you have to do on your own, it will depends how you designed your templates?
There are many ways to do this and it depends on how you are doing your menus. I usually create my menu as a Django model. Then, in my template I compare the current path with the menu path. eg.
<ul class="menu">
{% for m in menuitems %}
<li{% if m.path == request.path }} class="current"{% endif %}>
{{ m.title }}
</li>
{% endfor %}
</ul>
Of cause, you would need to pass in menuitems into your view. To save adding in that into all my views, I usually create a template tag that fetches the menuitems variable for me.
So yes, completely possible... but it completely depends on how you decide to structure your menus and pages. Django is a web-framework, whereas Wordpress is a Blog engine.