Is it possible to insert into {% url %} field from queryset record?
e. g.
{% url queryset[0].field %}
I viewed django source and reach the conclusion that what I want to do is not possible, so I made it other way. In view for every record from query set I added new field url:
for q in queryset:
q.url = reverse(q.field_with_url_name)
I think the simplest way
Of course it's possible, but square brackets are not valid syntax anywhere in Django's templating language. This is very clearly documented.
This would work:
{% url queryset.0.field %}
Related
I am making a blog website and I have to add comments to my post for that I have to check which post the comment is associated with and I am writing this line
{% if {{comment.post}}=={{blog.post}} %}
I know this line won't work because {%%} and {{}} cannot be used in the same line so does anyone has a solution for this.
In a template tag, you do not use the double curly brackets, but just the variables:
{% if comment.post == blog.post %}
…
{% endif %}
That being said, please do not filter in a template. Business logic belongs to the models or views. If you use relations, like a ForeignKey [Django-doc], or a ManyToManyField [Django-doc], then Django adds managers to the corresponding models. This also means it fetches the related comments by a query to the database. Especially if the number of comments will increase, eventually filtering in the template will no longer be feasible.
{% if comment.post == blog.post %}
…
{% endif %}
this will work well
I have a model and i want to go to a external website with my variables in the url . For example: "www.example.com\ {% object.field %} .com
My model
class Avaria(models.Model):
freguesia = models.ForeignKey(Freguesia, on_delete=models.CASCADE,verbose_name="Freguesia")
rua = models.ForeignKey(Rua, on_delete=models.CASCADE,verbose_name="Rua")
I'm changing my change_form_object_tools.html and add a extra li to do something like this:
<li>
{% trans "Example" %
</li>
If i use the original.pk it is working but i want to use another field that is not the primary key
If you're getting correct object in variable obj then
instead of
{% trans "Example" %
you need to do
{% trans "Example" %
I know in django admin model object comes in variable original, you can use original in place of obj.
Also if you want to understand django template language
{{ }} for rendering variables and using filters, read more
{% %} for sentences such as if and for or to call tags such as load, static, etc. is for tags, read more
Similarly there is {# #} for comments.
Read the documentation please
I am utilizing an includes within my template, but would only like to send a splice of the django queryset through the template. I don't want to splice in my view, because this is apart of a larger for loop that will be continually calling the include with different subsections. Here was my wishful thinking:
{% for g in gl %}
{% include 'includes/file.html' with ps=ps|id:g.id %}
{% endfor %}
You should create a filter tag that will receive your queryset and return a filtered one.... you can find details here:
https://docs.djangoproject.com/en/2.1/howto/custom-template-tags/
I am using django-filter to filter a ListView and would like to display a "Clear all filters" link if any filters are applied.
Due to the generic nature of the filtering system I haven't yet found a straightforward way to achieve this.
The only thing I came up with so far is to return the regular queryset in the get_queryset method of the view if a "clear" flag is present in the request, however this doesn't actually clear the filters - it just returns all the data.
Does anyone have a solution/idea for this?
Update: Solution
After Jerin's comment I decided to solve this problem in 2 separate parts:
has filter:
I check if any of the fields I defined in my filter class are in the request. My solution looks a bit different as I'm using class based views so I abstracted it away in a mixin but if you're using simple views like here, you could just do:
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
has_filter = any(field in request.GET for field in
set(f.get_fields()))
return render(request, 'my_app/template.html', {
'filter': f,
'has_filter': has_filter
})
clear all filters:
A simple redirect to your list view:
{% if has_filter %}
{% trans 'Clear all filters' %}
{% endif %}
Here is the mixup version of the answer (combination of mine and Chris)
You could place a Clear all filters button and that will redirect to your default ListView (/host/end/point/).
But some non-filter parameters (such as pagination or something else) may occur in URL. So the better option is, check for any filter fields in URL and if so, display the filter clearing link
The opted solution is,
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
has_filter = any(field in request.GET for field in set(f.get_fields()))
return render(request, 'my_app/template.html', {
'filter': f,
'has_filter': has_filter
})
and in template,
{% if has_filter %}
{% trans 'Clear all filters' %}
{% endif %}
Just make a button and point to the base search field.
<a class="btn btn-warning" href="{% url 'App:FilterView' %}">Reset</a>
If your FilterSet instance is available on the template you can check for filter.is_bound like this:
{% if filter.is_bound %}
Clear filters
{% endif %}
If you are using the FilterMixin or the FilterView, your FilterSet instance will be available as filter to the template as above.
I like this simple solution, however when I attempt to use it the current filter parameters are some how getting appended to the url even though it's the base url in the anchor.
So hovering over the button my link (determined using {% url 'app:view' %} shows
localhost/app/view correctly
However when clicking the button the url in browser has the parameters appended
localhost/app/view/?filter1=val1&filter2=val2 etc.
Is django caching something? Is browser (Chrome) caching? Can I force something in the anchor to not use them?
Answered my own, but for anyone else passing by:
I had the anchor on a button within a the filter form, although it was not a submit button moving it outside the form gave the desired result.
I am having a problem with djangos design choice not to allow model filtering in templates. Actually, I do understand its sense and I do not really want to break it, but currently I cannot see what's the best or usual method to circumvent my situation.
I am having a model Task with a foreign key user_solutions to another model Solution. Now I am iterating over all Tasks and if the user already has a solution for this task, I want to display both a tick and the link to his solution. Somewhat like this:
{% for task in tasks %}
{{ task.title }}
{% if task.user_solutions.filter(author=author).count() > 0 %}
Tick!
{{ task.user_solutions.get(author=author).get_absolute_url }}
{% endif %}
{% endfor %}
Yes, it looks cruel querying the database two times for the same information and django template does not accept it like this (correctly).
However, the other approaches to not seem to work either:
I cannot add a method Task.get_current_user_solution(), because in the model I do not know which user is logged in
I cannot add a method Task.get_user_solution(user), because I cannot pass arguments through the template
I cannot query information in the view and save it into a dictionary current_users_solutions (with Task.id as index), because in the template, I cannot use combined variables to access dictionaries (and the index to access it would of course be task.id)
So what else is there I can do? From the linked article I can only see that I could add a new template tag to allow querying from the template, but as said, I actually would like to follow djangos design principle if possible.
The Django way to do this is to create a custom template tag that accepts a user parameter and filters the queryset appropriately. It's just a couple of lines of code.
Django isn't dogmatic about "no logic in templates" (dogmaticism is frowned on in Python generally, aka "practicality beats purity"). It doesn't provide the ability to do that sort of thing natively in the template language, but that's why it has custom template tags at all: if your design requires it, and the simplest way to do it would be to query from the template, then that's what you should do.
You can add whatever you want to your tasks while in the view, so, in views.py, you could do something like this:
# in views.py
for task in tasks:
if task.user_solutions.filter(author=author).count() > 0:
task.is_this_users = True
task.url = task.user_solutions.get(author=author).get.absolute_url
and then in your template:
{% for task in tasks %}
{{ task.title }}
{% if task.is_this_users %}
Tick!
{{ task.url }}
{% endif %}
{% endfor %}
You can use django template tags like this:
templatetags.py
#register.inclusion_tag("template.html")
def task_def(request):
task = user_solutions.filter(author=author).count()
if task >0:
task.is_this_users = True
task_url = task.user_solutions.get(author=author).get.absolute_url
return {'task_url': task_url}
in the template file (.html)
{% load templatetags %}
and now you can use your return result here like you want
{% for element in task_url %}