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

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 %}"

Related

page not found in django?

i am new to django. this is the error i keep getting when i try to visit node.name page.
page not found Request URL: http://127.0.0.1:8000/Category//
urls.py
Category/<category_id>/ [name='productlisting']
index.html
{% load mptt_tags %}
<ul class="root">
{% recursetree listing %}
<li>
{{ node.name }}
</li>
{% endrecursetree %}
</ul>
urls.py
path('Category/<category_id>/',views.productlisting, name='productlisting'),
path('Category/<category_id>/product/<product_id>/',views.details, name='details'),
thanks in advance.
First you have an extra ending / in the endpoint you are trying to hit.
This is not how we name urls in anchor tag. Please refer here on how to name url and how to use it in template
so basically idea is that you would name url in urls.py in following manner:
path('Category/<int:category_id>/',views.productlisting,name='productlisting'),
then you would use this url name in template as:
{{ node.name }}

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 %}

Concatenate strings together in template if statement

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 %}

Django transforming an old url to new syntax

I'm trying to use this app in my project: https://github.com/s1n4/django-favorite
but it has old url syntax and I did not understand how to transform it to new url syntax.
The url that I wanna transform:
{% url favorite.views.add_or_remove target_model target_object_id %}
Its exact form in html:
<button class="btn favorite" href="{% url 'favorite.views.add_or_remove' %}" model="{{ target_model }}" id="target_{{ target_object_id }}">
I know the syntax has changed with Django 1.5 and I tried to use this version:
{% url 'favorite.views.add_or_remove' target_model target_object_id %}
It also did not work.
It says:
Reverse for 'favorite.views.add_or_remove' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
How can I fix this? Thanks.
Edit:
Its template tag can help to understand:
#register.simple_tag(takes_context=True)
def favorite_button(context, target):
user = context['request'].user
# do nothing when user isn't authenticated
if not user.is_authenticated():
return ''
target_model = '.'.join((target._meta.app_label, target._meta.object_name))
target_content_type = ContentType.objects.get_for_model(target)
target_object_id = target.id
fav_count = Favorite.objects.filter(target_content_type=target_content_type,
target_object_id=target_object_id).count()
undo = False
if user.favorite_set.filter(target_content_type=target_content_type,
target_object_id=target_object_id):
undo = True
return render_to_string('favorite/button.html',
{'target_model': target_model, 'target_object_id': target_object_id,
'fav_count': fav_count, 'undo': undo})
Since that application is in use in production (in which we used Django 1.4) I cannot patch the application to make it compatible with Django 1.5+. But there is a pull-request that I kept open for such a situation. Here it is: https://github.com/s1n4/django-favorite/pull/1 It might solve the problem.
The URL has no arguments:
url(r'^add-or-remove$', 'add_or_remove'),
and neither does that view:
def add_or_remove(request):
The URL tag in the HTML there also has no arguments:
{% url favorite.views.add_or_remove %}
To convert that to the new syntax it would be:
{% url 'favorite.views.add_or_remove' %}
After that you can use the template tag as described in the README:
{% load favorite_tags %}
{% for comment in post.comments %}
{% favorite_button comment %}
{% endfor %}

Opening external Url in Django template

I've a Django template like this:
<ul>
{% for url in urls %}
<li>{{ url.url_title }}</li>
{% endfor %}
</ul>
Url is a model that stores Url name and Url title of that particular url. I thought by using this template, I might be able to open the page and get redirected to the external url specified in:
<a href="{{ url.url_name }}">
Turns out, I can't. How do I achieve this? I'm a newbie in Django and don't know what to do.
I supposed url_name is Charfield type, and it is something like example.com or starting with http or https, for all above cases, the below worked for me:
<a href="http://{{ url.url_name }}">
If you used URL type for the url_name, then your solution should work and your problem is not with tag.
Please, try with:
<a href="{{ url.url_name }}" target="_self">

Categories