Concatenate strings together in template if statement - python

I read this and my code looked like this:
html:
<li {% if request.path == '/groups/{{ group.id }}/' %}class="active"{% endif %} >Link</li>
The only problem is that /groups/{{ group.id }}/ obviously turn into:
/groups/{{ group.id }}/
not
/groups/1/
that will end up being a lot of code if type it for the other 10 links on the page.

Instead of hardcoding the url, use the url tag with as
{% url 'my_group_url_name' group.id as group_url %}
{% if request.path == group_url %}

Related

How to change href in django based on the current page url?

As I said in the title, what would be the correct syntax to change the href of a link according to the current url the user is on?
I tried this, but it doesn't work.
{% if url == '' %} href='/cookies' {% else %} href='' {% endif %}
What would be the correct syntax to do this?
At Django 1.9 and above can use something like this
href='{% if not request.path %}/cookies{% endif %}'
You can check the current url with
href="{% if request.path == '' %}/cookies{% endif %}"

Clean url in django app. without ?page=1 pattern

I want to have my url pattern like the below pattern:
host:8000/archive/2/
I define page_kwarg in my view but I still receive: host:8000/en/2
Code form main url.py file:
url(_(r'^archive'), include('events.urls_archive', namespace='archive')),
start edit1
and link form main site to my app:
<a href="{% url 'archive:list' %}" title="{% trans 'Archive' %}">
{% trans 'Archive' %}
</a>
end edit1
start edit2
This is the url in my app urls_archive.py:
urlpatterns = [
url('^/(?P<page>\d+)/$', ArchiveListView.as_view(), name="list"),
url('^/(?P<slug>[-\w]+)/(?P<pk>\d+)$', ArchiveDetailView.as_view(), name="detail"),
]
end edit2
The code for my view:
class ArchiveListView(ListView):
model = Booking
queryset = Booking.objects.filter(period__type='archive').order_by('-date_start')
paginate_by = 80
page_kwarg = 'page'
Here is my template code:
{% if is_paginated %}
{% if page_obj.has_previous %}
<h4>Previous</h4>
{% endif %}
<span class="arrow header"><h4>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</h4></span>
{% if page_obj.has_next %}
<h4>Next</h4>
{% endif %}
{% endif %}
Please provide any help.
Thanks.
page_kwarg sets the key that the page number is passed in as. It doesn't affect how it is used in the page. For some reason, you are outputting that directly as /{{ page_obj.previous_page_number }}, which resolves to just /2. You should output it in the same format as it is passed in:
?page={{ page_obj.previous_page_number}}
Edit
If you want your page number to be specified as part of the path arguments, you should use the url tag, like any other URL:
{% url 'archive' page=page_obj.previous_page_number %}

Python Flask SQLAlchemy-Paginator Access next page in html view

I have currently a problem to include the pagination function into my project. I know there is LIMIT/OFFSETor yield_per(), but I was not able to implement them.
I am using SQLAlchemy not Flask-SQLAlchemy so paginate wont work.
My Database is not that big. I am trying to show rooms which have been added by a user. So all in all a user will have 20~ rooms, big users maybe 100. I want to show on the profile page the 6 last inserted rooms and if there are more, there should be pagination, like page 2 shows the next 6 etc.
I am using SQLAlchemy-Paginator.
I already implemented it and tested it, it works fine. It also limits already the results depending on which page I am. But how do I access the next page while on HTML?
Here is the python code:
#app.route("/user/logged_in")
#login_required
#check_confirmed
def logged_in():
if current_user.email_verified:
users_room = db_session.query(Zimmer).filter_by(users_id=current_user.id).order_by(desc("id"))
paginator = Paginator(users_room, 2)
for page in paginator:
print "page number of current page in iterator", page.number
print "this is a list that contains the records of current page", page.object_list
return render_template('logged_in.html', paginator=paginator)
return redirect(url_for('unconfirmed'))
Here is the view. The solution must be somewhere here. I can access pages by page.previous_page_number or page.next_page_number. But there is no example in the docu how to do it in view.
<div class="user-rooms">
<h2> Ihre Zimmer </h2>
{% for page in paginator %}
{% if page.number == 1 % }
{% for zimmer in page.object_list %}
{% if zimmer.users_id == current_user.id %}
<div class="col-sm-4 col-xs-6 col-xxs-12 img-holder">
<img src="../static/userimg/{{ zimmer.hauptbild }}"/>
<div class="buttons-del-work"> Bearbeiten Löschen </div>
</div>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
If I manually change the page numbers here it show me the correct items, so I feel like I am close:
{% if page.number == 1 % }
Okay here is a solution (which does not use any further methods from the SQLAlchemy-Paginator package). I coded everything myself, but I would still like to know how it is done with page.next_page_number etc.
Explained:
First of all I added an argument (pagenumber) to my logged_in function. Everytime url_for("logged_in", pagenumber=1) is called the pagenumber has to be set to the defaultvalue 1.
I created an empty list, where I add all the page.number items, so I know how many pages my resultset will have:
pages_list = []
for page in paginator:
pages_list.append(page.number)
I use the pages_list also in the view to generate the buttons which can be clicked to see the next page, I also give the pagenumber to the html view:
return render_template('logged_in.html', paginator=paginator, pagenumber=pagenumber, pages_list=pages_list)
Here is the HTML view where I show the buttons:
<div class="col-xs-12">
{% for number in pages_list %}
{{ number }}
{% endfor %}
</div>
Now if a user clicks one of the Buttons the logged_in will be called with a new pagenumber argument (the actual pagesite you clicked)
In the logged_in I added also typecasted pagenumber to int before giving it to html view:
pagenumber = int(pagenumber)
Solution Code
Python:
def logged_in(pagenumber):
if current_user.email_verified:
users_room = db_session.query(Zimmer).filter_by(users_id=current_user.id).order_by(desc("id"))
paginator = Paginator(users_room, 2)
pages_list = []
for page in paginator:
pages_list.append(page.number)
pagenumber = int(pagenumber)
return render_template('logged_in.html', paginator=paginator, pagenumber=pagenumber, pages_list=pages_list)
return redirect(url_for('unconfirmed'))
HTML:
<div class="user-rooms">
<h2> Ihre Zimmer </h2>
{% for page in paginator %}
{% if page.number == pagenumber %}
{% for zimmer in page.object_list %}
<div class="col-sm-4 col-xs-6 col-xxs-12 img-holder">
<img src="../static/userimg/{{ zimmer.hauptbild }}"/>
<div class="buttons-del-work"> Bearbeiten Löschen </div>
</div>
{% endfor %}
{% endif %}
{% endfor %}
</div>
<div class="col-xs-12">
{% for number in pages_list %}
{{ number }}
{% endfor %}
</div>

Django template multiple url return

I've 2 urls pointing to the same place:
url(r'^index/$', 'proj.views.index'),
url(r'^index/show_closed/$', 'proj.views.index'),
If I use in a template file this:
{% url proj.views.index %}
it' ll return /index/show_closed
and this is OK, but how can i make {% url %} to return only /index ?
Use named patterns; giving your pattern a unique name:
url(r'^index/$', 'proj.views.index', name='index_direct'),
url(r'^index/show_closed/$', 'proj.views.index', name='index_closed'),
then refer to those names in the {% url %} tag instead of the view:
{% url 'index_direct' %}
{% url 'index_closed' %}

Jinja - Is there any built-in variable to get current HTML page name?

i'm very new to Jinja and Flask
I want to set different background color in the navigation bar to indicate the current page.
Is there any built-in Jinja variable or method that returns current HTML pages? If possible, I want the code that doesn't need to communicate with the Python file.
So if i'm currently in index.html, it will return "index" or "index.html"
Here's my navigation code in my template:
<ul>
{% for item in navigation %}
<a href="{{url_for(item.route)}}">
<li>
{{item.text}}
</li>
</a>
{% endfor %}
</ul>
I want to add if statement so the current page will get <li> that has class
{% if ??? %}
<li class="current">
...
</li>
{% else %}
...
{% endif %}
Thank You
There is a trick in jinja2 document for your problem: http://jinja.pocoo.org/docs/tricks/
If your list is simple enough, just using request object, something like that:
<li {% if request.endpoint == item.endpoint %} class='active' {% endif %}>
{{item.text}}
</li>
Normally, I write this snippet to a macro with an explicit argument to set active:
{% macro render_sitem(endpoint, display, cls='', icon-cls='', active='') %}
<li {% if request.endpoint == endpoint or active == endpoint %} class='active' {% endif %}>
<a class='{{cls}}' href="{{url_for(endpoint)}}"><i class="{{icon-cls}}"></i> {{display}}</a>
</li>
{% endmacro %}
The list will be something like:
<ul class="nav nav-list">
{{render_sitem('page.index', _('Pages'), icon-cls='icon-sitemap', active=active_page)}}
{{render_sitem('post.index', _('Posts'), icon-cls='icon-file', active=active_page)}}
{{render_sitem('user.index', _('Users'), icon-cls='icon-group', active=active_page)}}
</ul>
So if you have a child page which extends or includes your list, you can set active item like:
{% set active_page = 'page.index' %}
in the top of your child page.
In pyramid 1.5 there are no method like request.endpoint in Flask.
We use custom filter get_endpoint
request.path|get_endpoint
jinja2_custom_filters.py:
from pyramid_jinja2 import Environment
def get_endpoint(str):
"""
:param str:
:return:
"""
return str.split('/')[-1]
env = Environment()
env.filters['get_endpoint'] = get_endpoint
and in development.ini:
jinja2.filters =
model_url = pyramid_jinja2.filters:model_url_filter
route_url = pyramid_jinja2.filters:route_url_filter
static_url = pyramid_jinja2.filters:static_url_filter
get_endpoint = path to ... jinja2_custom_filters.get_endpoint
Maybe it will be useful to someone :)
In Flask 2.0.1, the request object is available in the template. With this you can easily use it to check the page using the request.path attribute.
An example of a check would be like this:
{% if request.path == "/" %}
<h1>You are at the root</h1>
{% endif %}

Categories