Reversing complex Admin URLs from templates - python

I find myself needing a bit more flexibility than what I understand I can do based on the Django documentation for reversing Admin URLs. I'm doing things like:
{% url admin:billing_creditcardtoken_add %}?customer={{ user.id }}
This works, but it feels like I should be able to do it without leaving the template tags.
If I want to find all CreditCardToken objects from the billing application that belong to the current user, I find myself doing:
{% url admin:billing_creditcardtoken %}?customer={{ user.id }}
...but this fails altogether. Is there a more elegant way of getting these URLs?

I was looking at this the wrong way. While:
{% url admin:billing_creditcardtoken_add %}?customer={{ user.id }}
...might be somewhat ugly, the only thing added syntax would serve to do is try to construct a query string, which isn't something one reverses URLs to do normally anyway. So this is an acceptable method of accomplishing this task.
What I was looking for in the second turned out to be:
{% url admin:billing_creditcardtoken_changelist %}?customer={{ user.id }}
...changelist, as it turns out, does not show a history of changes, but creates a list of possible items to change. Adding the query string applies the proper filter I needed.

Related

Django is it better to check user.is_authenticated in views.py or in template?

I have a homepage, which I want to display a login form when user is not logged in or display a list of items belong to that user if he/she already logged in.
So far I came up with 2 methods:
Check whether user is authenticated in views.py and render corresponding view (in my views.py):
if request.user.is_authenticated():
return render(request, 'items.html')
else
return render(request, 'login.html')
Check directly in template and generate corresponding HTML for each case (in my index.html):
{% if user.is_authenticated %}
HTML for my items list
{% else %}
HTML for my login form
{% endif %}
Question
So which method is better for handling this? Are those methods differ much in performance? Is there any standard that we should handling these in views.py or in template itself?
I don't think there is a big performance difference. What's most important is how much you should stick to MVC pattern.
A template is meant to just display some sort of data that the view provides. Any kind of logic like deciding what kind of data to show based on requester's state should always be implemented by the view. Thus, you should move your logic into view function for the cleanness of your design.
TL;DR
Logic should be in your python code, not your template as much as possible. Due to maintenance and future-proof reasons.
Elaborate
Code quality: you can test your business logic when it's in your python not when it's in templates. The former improve your code quality and your value as a developer ;
Future-proof: you don't know which technology your application is going to use in the future, so avoiding tech-mingling will help you when upgrading it (you will be able to upgrade at different pace).
Separation of concerns principles: do you want a code that is a spaghetti plate, where you can't refactor a thing without impacting ten others?
Code legacy: you don't know who is going to work on your code neither which code you're going to work on. Don't make it hard for them (it would probably be your future self) ;
Clean code: that express itself in a single dialect is always better that mixing languages ;
Knowledge scope: front-end is often the responsibility of people with low programming skills (HTML/CSS are declarative) and you don't want them to mess with your business logic.
It depends on your html. If you want to change only a little part of your code based on the condition, check inside a template:
{% if user.is_authenticated %}
<h3>Welcome</h3>
{% else %}
Login
{% endif %}
But if items.html and login.html are different and big templates, you should definitely do the login inside your view.

Django-Tables column templates with django permissions

So, I'm using Django-Tables to generate my project datatables, but now I'm facing a new problem.
I've got this Table Class to generate my Model datatables, using the DjangoTables app. Then I use the TemplateColumn to create a new column for base operations just like Edit, Copy, Delete... This stuff goes into the template that is loaded into the column of each row.
class ReservationTable(tables.Table):
operations = tables.TemplateColumn(template_name='base_table_operations_btn.html', verbose_name= _('Operations'))
So inside the template i've got this:
{% if perms.reservation.add_reservation %}
<span class="glyphicon glyphicon-paperclip"></span>
{% endif %}
So, using the django templates perms tags, is not working here but it does in to the normal django template.
Any tips on how can I handle those perms into this kind of template? I'm kinda losen.
Thanks in advance!
So, its not just like a "perfect answer" for this problem, but here is how I managed to solve this:
Instead of using in Template django permisions, I managed to setup the permissions in the route url config. Just by adding:
permission_required('permision_name',raise_exception=True)
Function in the url.py. So here comes the full url line:
url(r'^reservation/flight/add/$', permission_required('reservation.add_reservation',raise_exception=True)(FlightReservationCreate.as_view()), name='reservation-flight-create'),
This allow me to add perms to the View instead of filtering into the themplate view.
That's not a perfect solution, because its a different way to manage permissions, and the problem with the django-tables2 column template is still there.
By the way, the final result is the same for me, so its OK.

Advice about composing several django templates

I'm developing a web application with Django and we have met a dilemma about the design.
We were making one template for every screen, but right now we have detected that some parts of of the screen with the information are repeated all over the different screens. For example, when coming to show personal data of a person, you can show also another data concerning that person, but not personal data (financial data, for instance).
My intuition told me that we should look for a solution in which we could make small templates that we could compose, combine and concatenate and that we should also make different views or functions which would return its own associated template each one.
Thus, person_data() would return the rendered template showing the name, surname, address, etc... and financial_data() would return the rendered template showing the salary, bank account, etc... After that, the desirable thing would be concatenating both or inserting them in a wider template for showing all this together.
<html>
...
{# Html code here #}
...
{# person_data template #}
...
...
{# financial_data template #}
...
{# Html code here #}
...
</html>
So as always I made some research on the net and I found:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include
a link which describes how to use include for inserting a template file in another template:
{% include "foo/bar.html" %}
And you can also use a variable from the python function with the path name or an object with render method:
{% include template_name %}
So we could use all this in this way for combining, concatenating, composing and operating on templates. We could choose the one which includes the others and passing it the context for all templates (I suppose, I didn't test anything). But I don't know if I'm well directed or if this is the best way to go. I would appreciate some advice.
I also found another interesting thread in stackoverflow talking about this:
How do you insert a template into another template?
My idea is to have small templates which are used repeatedly in different spots of the web and composing them in Unix-like style, so I would have small visual pieces that would be used once and again saving a lot of hours of writing of code.
Please some advice.
Thanks in advance
Yes, that is a correct approach. I think the best solution is to combine {% include %} and {% extend %}, which will allow you to inherit from a base template (via extend), and include parts you want from other templates (via include).
You'd end up having a base template, a template for the header, the footer, parts of the body etc.
You might also want to read more about it here and here

Iterate over XML in Django Temnplate

I have a block of XML that is returned from an API call.
It contains lots of results - person elements like below.
<root><person><name>mark</name><age>18</age></person><person><name>alan</name><age>10</age></person></root>
I want to pass this data structure (or some iterable version if it) to a django template to iterate over.
In my template I want to say
{% for r in results %}
{{ r.name }}
{{ r.age }}
{% endfor %}
I thought this would have been straight forward but its posing problems.
Django templates cannot handle it out-of-the-box. And it doesn't actually sound correct - to pass an XML structure into HTML template to process.
Making custom template tags or filters that would help to iterate over the XML structure could be a possible solution, but in this case you may find yourself overcomplicating things, template layer was made for presentation, don't put too much logic into it:
We see a template system as a tool that controls presentation and
presentation-related logic – and that’s it. The template system
shouldn’t support functionality that goes beyond this basic goal.
Parse the XML in the view, make a list of dictionaries and pass it to the template inside the context.
For example, use xmltodict tool:
persons = xmltodict.parse(data)['root']['person']
where data is your XML structure.

How to have partially pre-rendered fields using Django-haystack

I've started using a rendered field in my django-haystack indexing to avoid database hits when a search is rendered. This is working well for the most part, but I have some runtime information (such as an edit button for staff) in the results as well that I'd like to splice in. A simplified example:
{{object.name}}<br/>
{% if user.is_staff %}
Edit
{% endif %}
{{ object.description}}
The user logic obviously can't be applied at indexing time so doesn't occur. Without using javascript hacks is there a way to splice some runtime output in amongst the pre-rendered text? I'm thinking it can be done by passing the rendered text with some formatting placeholders to a custom template tag, but I wonder if there's another way.
Edit: Perhaps multiple rendered, stored fields might be possible, covering the main fragments of the search result surrounding the logic parts, and then assembled at run time in the main results template. Would this work?

Categories

Resources