Jinja: if path == '/home' or '/home/<int>' - jinja2

I am interested in knowing the proper way of performing the following function:
<li {% if request.path == '/' or '/<int> %}class="active"{% endif %}><i class="fa fa-home" aria-hidden="true"></i> Home</li>
The above does work however, if one visits a url such as '/article/3' or '/anything/', the 'active' class is triggered as well.
I had tried the following:
<li {% if request.path == '/<int> %}class="active"{% endif %}><i class="fa fa-home" aria-hidden="true"></i> Home</li>
The integer is representing a page number which is set to 1 by default.

Related

Categorie sorting HTML JINJA

I have some problem with fronend, select tag html code. I have creating sorting option.
All is working fine if it is like a list or block (depending from villing), but then i truing to make a dropdown and add select tag all categorys gone , only ALL STATUS.
Could you please explain me there is my mistake and why ?
MY HTML
<div class="top-selector-right">
<select name="status-candidate">
{% if stat_selected == 0 %}
<div class="top-selector-right">
<option><a class="nav-link"><i class="fa-solid fa-bars"></i> ALL STATUS</a></option>
</div>
{% else %}
<div class="top-selector-right">
<option><a class="nav-link" href="{% url 'candidates' %}"> ALL STATUS</a></option>
</div>
{% endif %}
{% for s in status %}
{% if s.pk == stat_selected %}
<option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ s.ff_status_id }}</a></option>
{% else %}
<option><a class="nav-link" href="{{ s.get_absolute_url }}">{{ s.ff_status_id }}</a></option>
<!-- <a class="nav-link" href="{{ s.get_absolute_url }}"><i class="fa-solid fa-ellipsis-vertical"></i> {{ s.ff_status }}</a>-->
{% endif %}
{% endfor %}
</select>
</div>
My views.py
def show_status(request, np_ff_status_id):
new_candidates = NewPlacement.objects.filter(np_ff_status_id=np_ff_status_id)
status = SatusActivity.objects.all()
context = {
'new_candidates': new_candidates,
'status': status,
'stat_selected': np_ff_status_id,
}
return render(request, 'placements/candidates.html', context=context)
models.py Just part of the models.py
class SatusActivity(models.Model):
NEW = 'New placement'
CANCELED = 'Canceled'
CONTACTED = 'Contacted'
WAITING = 'Waiting answer for the client'
ACCEPTED = 'Accepted'
DECLINED = 'Declined'
ONHOLD = 'On hold'
NOTANSWERING = 'Not answering'
STATUS = [
(NEW, 'New placement'),
(CANCELED, 'Canceled'),
(CONTACTED, 'Contacted'),
(WAITING, 'Waiting answer for the client'),
(ACCEPTED, 'Accepted'),
(DECLINED, 'Declined'),
(ONHOLD, 'On hold'),
(NOTANSWERING, 'Not answering'),
]
ff_status = models.CharField(max_length=30, choices=STATUS, default=NEW, db_index=True)
def __str__(self):
return self.ff_status
def get_absolute_url(self):
return reverse('status', kwargs={'np_ff_status_id': self.pk})
FULL urls.py on APP
urlpatterns = [
path('candidates', views.candidates, name='candidates'),
path('candidates_easy', views.candidates_easy, name='candidates_easy'),
path('new', views.placement, name='new'),
path('post/<int:id>/', show_post, name='post'),
path('category/<int:np_ff_location_id>/', show_category, name='category'),
path('status/<int:np_ff_status_id>/', show_status, name='status'),
]

Django - How to use Pagination with filter function?

I am trying to use Pagination with the Django Filter function, But I am getting this error.
http://127.0.0.1:8000/product_search/?page=2&search=e
Cannot use None as a query value
product = Product.objects.filter(productName__contains=name)
Here is The view.py function
def searchProduct(request):
name = request.POST.get("search", None)
try:
product = Product.objects.filter(productName__contains=name)
paginator = Paginator(product, 2)
page = request.GET.get('page')
page_product = paginator.get_page(page)
if page_product:
context = {
'searchResults': page_product,
'name': name
}
return render(request, "Amazon/searchResult.html", context)
else:
return render(request, "Amazon/searchResult.html", {'message': "No Product Found"})
except Product.DoesNotExist:
return HttpResponse("Page Not Found")
Here is HTML/Jinja code
<nav aria-label="...">
{% if searchResults.has_other_pages %}
<ul class="pagination justify-content-center">
{% if searchResults.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ searchResults.previous_page.number }}&search={{ name }}" tabindex="-1">
Previous</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link" tabindex="-1">Previous</a>
</li>
{% endif %}
{% for i in searchResults.paginator.page_range %}
{% if product.number == i %}
<li class="page-item active">
<a class="page-link" href="#">{{ i }}</a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="?page={{ i }}&search={{ name }}">{{ i }}</a>
</li>
{% endif %}
{% endfor %}
{% if searchResults.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ searchResults.next_page_number }}&search={{ name }}">Next</a>
</li>
{% else %}
<li class="page-item disabled">
<a class="page-link">Next</a>
</li>
{% endif %}
</ul>
{% endif %}
</nav>
I have a rough Idea that no value is getting passed in filter function that is why it is showing this error. So, any Idea how can I resolve it??
Simply filter your queryset when name is provided, eg.
name = request.POST.get('search')
page_number = request.GET.get('page')
products = Product.objects.all()
if name: # only filter when name provided
products = products.filter(productName__contains=name)
try:
page = Paginator(products, 2).get_page(page_number)
except EmptyPage:
return render(request, "Amazon/searchResult.html", {'message': "No Product Found"})
return render(request, "Amazon/searchResult.html", {
'searchResults': page_product,
'name': name
})

Invalid block tag on line 2: 'set'. Did you forget to register or load this tag?

I'm having some difficulties on building a simple menu navigation bar. I need to make a highlight on current menu tab which the user is browsing on. So I'm working with Django and Jinja2, and here's my code:
page1.html
{% extends "base.html" %}
{% set active_page = "menu1" %}
{% block title %}Apie mus{% endblock %}
{% block content %}
{{page}} - Current Page set from django return
...
My base.html:
...
<ul class="navbar-nav ml-auto">
<li class="nav-item {{ 'active' if active_page == 'menu1' else '' }}">
<a class="nav-link" href="{% url 'apie_mus' %}">Apie mus </a>
</li>
</ul>
How can I fix the issue?
if you want to do things in proper way and set active css class for the current active page, here how you can do
in templates/includes/header.html:
..
<ul class="navbar-nav mr-auto">
<li class="nav-item{% if request.path == '/' %} active{% endif %}"><a class="nav-link" href="{{ url_for('index') }}">Home <span class="sr-only">(current)</span></a></li>
<li class="nav-item{% if request.path == '/about' %} active{% endif %}"><a class="nav-link" href="{{ url_for('about') }}">About</a></li>
</ul>
..
and then in templates/base.html:
..
<body>
{% include 'includes/header.html' %}
{% block content %}{% endblock %}
{% include 'includes/footer.html' %}
..
and you don't need {% set .. %}
refer to this topic templates assignments for more details

How to add a button to nav-bar?

How can I add another button/dropdown to the navbar in sonata admin listing template for my MapAdmin class?
I just want this button in one admin class.
You have to override the default template (layout: 'SonataAdminBundle::standard_layout.html.twig') with your own in coding your logique here
Here is an extract of existing code :
{% block sonata_admin_content_actions_wrappers %}
{% if _actions|replace({ '<li>': '', '</li>': '' })|trim is not empty %}
<ul class="nav navbar-nav navbar-right">
{% if _actions|split('</a>')|length > 2 %}
<li class="dropdown sonata-actions">
{{ 'link_actions'|trans({}, 'SonataAdminBundle') }} <b class="caret"></b>
<ul class="dropdown-menu" role="menu">
{{ _actions|raw }}
</ul>
</li>
{% else %}
{{ _actions|raw }}
{% endif %}
</ul>
{% endif %}
{% endblock sonata_admin_content_actions_wrappers %}
It requires adding a custom action and overriding a certain template. You can follow the documentation on symfony.com.
Read up to the following code block:
{# src/AppBundle/Resources/views/CRUD/list__action_clone.html.twig #}
<a class="btn btn-sm" href="{{ admin.generateObjectUrl('clone', object)}}">clone</a>
I have just come across with the same problem. I am using Symfony 3.4.6 and Sonata Admin Bundle 3.9.1.These are the steps I've followed:
1. Find the standard template which lives in:/vendor/sonata-project/admin-bundle/src/Resources/views/standard_layout.html.twig.
2. Go to /app/config/config.yml and under the key sonata_admin, you just override that template as shown below
sonata_admin:
templates:
# Layout
layout: '#MyBundle/Admin/Default/Layout/standard_layout.html.twig'
3. Within your newly created template (standard_layout.html.twig) make sure you have extended the sonata standard template file like so : {% extends '#SonataAdmin/standard_layout.html.twig' %}. Now, all you need to do is override any block you want from the original sonata template file as I described in point 1, in my case I've just overridden the block tab_menu_navbar_header and Added my custom button like so:
{% block tab_menu_navbar_header %}
{% if _navbar_title is not empty %}
<div class="navbar-header">
<a class="navbar-brand" href="#">{{ _navbar_title|raw }}</a>
{% if object.state is defined and object.state is not null and object.state is same as('finished') %}
<button type="button" class="btn btn-info" style="margin-top: 10px;">
<i class="fa fa-check-square" aria-hidden="true"> History</i>
</button>
{% endif %}
</div>
{% endif %}
{% endblock %}

Django replacing html content with context tags

I have a template which contains:
Example 1:
{% if player_mark %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url 'games:map:town_map' map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ title_header }}</a>
{% endif %}
{% endif %}
Example 1 Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['player_mark'] = True
context['title_header'] = "This is map for home town"
return context
This same statement is copy and pasted about 15 times and to make it tidier i'm looking into having one and it look like this
Example 2:
{% if {{ player_header }} %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url '{{ url_header }}' map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ title_header }}</a>
{% endif %}
{% endif %}
then just updating it inside the context with what i need like so
Example 2 Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['player_header'] = ???
context['url_header'] = ???
context['title_header'] = "This is map for home town"
)
return context
I thought id be able to just replace the if statement in example one with contents of Example 2 but then i don't know how to structure this in the context_view.
Any ideas, need anything else let me know.
This is my attempt so far on the url context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['url_header'] = 'games:map:town_map' + "?{}{}".format(
map_id=self.map.id, ----- Unsure if this is correct way to pass url varibales
home_id=self) ----- Unsure if this is correct way to pass url varibales
context['header'] = "This is map for home town"
return context
Hopefully this gives a better idea of what i'm talking about.
Solution HTML:
{% if button %}
{% if commun.intern > threshold %}
<a class="btn btn-success btn-sm pull-right"
href="{% url url_path map_id=map.id home_id=homecall.id %}"><i
class="fa fa-phone-square fa-fw"></i>
{{ header }}</a>
{% endif %}
{% endif %}
Solution Context:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['button'] = True
context['url_path'] = 'games:map:town_map'
context['header'] = "This is map for home town"
return context
How i got to solution, after some html reading i found that i was going wrong because of the brackets {{}} These are for printing {% %} are for using functions.