give an active to class to active link - python

I am writing a python website built on the back of the django framework, I am looking for a way to highlight the current link the user is on depening on what the URL, I thought doing some thing like this would work.
What I have done is create a new application called nav and built some templatetags, like so,
from django import template
register = template.Library()
URL_PATTERNS = {
'home': (r'^/$',),
}
#register.tag
def nav_selection(parser, token):
try:
tag_name, nav_item = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
if not (nav_item[0] == nav_item[-1] and nav_item[0] in ('"', "'")):
raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
return NavSelectionNode(nav_item[1:-1])
class NavSelectionNode(template.Node):
def __init__(self, nav_item):
self.nav_item = nav_item
def render(self, context):
if not 'request' in context:
return ""
import re
try:
regs = URL_PATTERNS[self.nav_item]
except KeyError:
return ''
for reg in regs:
if re.match(reg, context['request'].get_full_path()):
return "active"
return ''
In my template I do this
<ul id="navigation">{% load nav %}
<li><a href="{% url views.home %}" class='{% nav_selection "home" %}'>home</a></li>
<li><a href="{% url views.about %}" class='{% nav_selection "about" %}'>about neal & wolf</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>our products</a></li>
<li><a href="{% url shop.views.home %}" class='{% nav_selection "shop" %}'>shop</a></li>
<li><a href="{% url views.look %}" class='{% nav_selection "look" %}'>get the look</a></li>
<li><a href="{% url news.views.index %}" class='{% nav_selection "news" %}'>news</a></li>
<li><a href="{% url contact.views.contact %}" class='{% nav_selection "contact" %}'>contact us</a></li>
<li><a href="{% url store_locator.views.index %}" class='{% nav_selection "finder" %}'>salon finder</a></li>
<li><a href="{% url professional.views.index %}" class='{% nav_selection "contact" %}'>neal & wolf professional</a></li>
</ul>
yet the markup I get out in firebug is this in this example I am browsing the index page
<a class="" href="/home/">
So something is obviously failing but I cannot see where, can anyone help me please?

Some things to check:
Is the request object actually in your context? Are you passing it in specifically, or are you using a RequestContext?
Why are you defining regexes in your templatetags, rather than using the built-in reverse function to look them up in the urlconf?
Do the regexes here actually match the ones in the urlconf?
Have you included your home urlconf under the 'home' url somehow?

Related

Django error NoReverseMatch on remote site but works fine locally

My Django site is working fine locally. I am pushing it to my website but one of the links is not working and I can not for the life of me see why as similar things are working fine.
Here is my urls.py:
from . import views
app_name = 'sitepages'
urlpatterns = [
path('', views.greeting_page_def, name='greeting_page_html'),
path('home/', views.home_def, name='home_html'),
path('specs/', views.specs_def, name='specs_html'),
path('about/', views.about_def, name='about_name'),
path('faq/', views.faq_def, name='faq_name'),
path('howTos/', views.howTos_def, name='howTos_name'),
path('howTos/puller', views.howTosPuller_def, name='howTosPuller_name'),
path('howTos/conformer', views.howTosConformer_def, name='howTosConformer_name'),
path('howTos/general', views.howTosGeneral_def, name='howTosGeneral_name'),
path('howTos/submitter', views.howTosSubmitter_def, name='howTosSubmitter_name'),
]
And my views.py:
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.
def greeting_page_def(request):
return render(request, 'sitepages/greeting_page_html.html')
def about_def(request):
return render(request, 'sitepages/about.html')
def faq_def(request):
return render(request, 'sitepages/faq.html')
def home_def(request):
return render(request, 'sitepages/home.html')
def specs_def(request):
return render(request, 'sitepages/specs.html')
def howTos_def(request):
return render(request, 'sitepages/howTos.html')
def howTosPuller_def(request):
return render(request, 'sitepages/howTosPuller.html')
def howTosConformer_def(request):
return render(request, 'sitepages/howTosConformer.html')
def howTosGeneral_def(request):
return render(request, 'sitepages/howTosGeneral.html')
def howTosSubmitter_def(request):
return render(request, 'sitepages/howTosSubmitter.html')
and the html template that has the links.
{% extends 'base.html' %}
{% block content %}
{% load static %}
<a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}"} >How Tos - Puller</a>
<a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}"} >How Tos - Submitter</a>
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a>
<a class="link-primary" href="{% url 'sitepages:howTosConformer_name' %}"} >How Tos - Conformer</a>
{% endblock %}
all the links here work except for
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}"} >How Tos - General</a>
when I click that I get
NoReverseMatch at /sitepages/howTos/
Reverse for 'howTosGeneral_name' not found. 'howTosGeneral_name' is not a valid view function or pattern name.
the other thing is it works locally but not on my site and I am pushing it via git and it looks the same.
Where am I going wrong?
All links have extra } at the end before closing of opening anchor tag.
So, the template should be:
{% extends 'base.html' %}
{% block content %}
{% load static %}
<a class="link-primary" href="{% url 'sitepages:howTosPuller_name' %}">How Tos - Puller</a>
<a class="link-primary" href="{% url 'sitepages:howTosSubmitter_name' %}">How Tos - Submitter</a>
<a class="link-primary" href="{% url 'sitepages:howTosGeneral_name' %}">How Tos - General</a>
<a class="link-primary" href="{% url 'sitepages:howTosConformer_name' %}">How Tos - Conformer</a>
{% endblock %}
Note: Always add / at the end of every route, so:
Urls.py:
from . import views
app_name = 'sitepages'
urlpatterns = [
path('', views.greeting_page_def, name='greeting_page_html'),
path('home/', views.home_def, name='home_html'),
path('specs/', views.specs_def, name='specs_html'),
path('about/', views.about_def, name='about_name'),
path('faq/', views.faq_def, name='faq_name'),
path('howTos/', views.howTos_def, name='howTos_name'),
path('howTos/puller/', views.howTosPuller_def, name='howTosPuller_name'),
path('howTos/conformer/', views.howTosConformer_def, name='howTosConformer_name'),
path('howTos/general/', views.howTosGeneral_def, name='howTosGeneral_name'),
path('howTos/submitter/', views.howTosSubmitter_def, name='howTosSubmitter_name'),
]

Displaying my current domain in my django template not working

I send a html email to the users using the EmailMultiAlternatives and it worked, but the problem is in the email message the link is not working.
But when I tried doing <a href="http://127.0.0.1{% url 'add_your_details' user.username %}"> then it worked perfectly as I wanted.
template
<a href="{{ request.scheme }}://{{ request.get_host }}{% url 'add_your_details' user.username %}"
target="_blank">Add your details </a>
settings
ALLOWED_HOSTS = ['127.0.0.1']
I solved this by using the get_current_site method.
In views:
from django.contrib.sites.shortcuts import get_current_site
my_current_domain = get_current_site(request)
return {'domain':my_current_domain}
then in template
<a href="{{ request.scheme }}://{{ domain }}{% url 'add_your_details' user.username %}"
target="_blank">Add your details </a>

Python/ Django- copying buttons from one HTML page to another

I have just taken over the development of some project management software that has been written in Python/ Django- having not used Python or Django much at all before...
There are a few buttons displayed on one of the webpages that it would be useful to display on another page within the application. I can see that these buttons are defined in budget.html with the following code:
{% block page_options %}
<a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a>
<a class="button m-r-md" href="{% url 'costing:schedule_of_works_post_dep' budget.id %}" target="_blank">Schedule of works</a>
<a class="button m-r-md" href="?pdf=1" target="_blank">PDF</a>
<input data-view-url="{% url 'costing:combined_budget' project.id %}?search=" type="text" id="item_search" placeholder="Item search" />
{% endblock page_options %}
The other page, where I want to be able to use them- variations.html has the following code already in its {%block page_options %} block:
{% block page_options %}
<button class="button modalBtn" name="variation">+ Add variation</button>
<a class="button" href="{% url 'costing:add_omit_builder' project.id %}">+ Add group</a>
<a class="button" id="scas" data-view-url="{% url 'costing:preview_scas' project.budget_overview.version.id %}" href="{% url 'costing:scas_2_variations' project.budget_overview.version.id %}">+ Standard cost assumptions</a>
<!--ERF(17/11/2016 # 1700) Add buttons to export adds/ omits table to excel -->
{% endblock page_options %}
So I tried copying and pasting the code from the first page into this block in the second page:
{% block page_options %}
<button class="button modalBtn" name="variation">+ Add variation</button>
<a class="button" href="{% url 'costing:add_omit_builder' project.id %}">+ Add group</a>
<a class="button" id="scas" data-view-url="{% url 'costing:preview_scas' project.budget_overview.version.id %}" href="{% url 'costing:scas_2_variations' project.budget_overview.version.id %}">+ Standard cost assumptions</a>
<!--ERF(17/11/2016 # 1700) Add buttons to export adds/ omits table to excel -->
<a class="button m-r-md" href="{% url 'costing:export_csv' budget.id %}">Export to Excel</a>
<a class="button m-r-md" href="{% url 'costing:schedule_of_works_post_dep' budget.id %}" target="_blank">Schedule of works</a>
<a class="button m-r-md" href="?pdf=1" target="_blank">PDF</a>
<input data-view-url="{% url 'costing:combined_budget' project.id %}?search=" type="text" id="item_search" placeholder="Item search" />
{% endblock page_options %}
but when I now try viewing this page in the browser, I get an error page which says:
NoReverseMatch at /costing/5915/variations/
I'm not sure why I'm getting this error... do I need to reference any of the calls to the views that I'm using in the code I've copied in elsewhere in the HTML file? Both of the HTML files are in the same app, so share the same models.py file- so I would have thought that they would both be able to use all of the models & views defined within this app?
Is this the case? If so, why am I getting this error on the variations page?
Based on what you said I suppose problem is that your don't have "budget" value in context variable. I think that view which using first template send "budget" in it's context.
But second view don't. That is why when you try to get budget.id in the second template you get the error.
Try to modify context in your view and add "budget" variable to it.
def my_view(request, pk):
budget= get_object_or_404(Budget, pk=pk)
return render(request, 'budget.html', {'budget': budget})
Or if you are using class based view you should override get_context_data method:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['budget'] = self.budget
return context

Django passing a string in url

I want to pass a string, in the url, and then catch in in the view
<a href="{% url 'dolgozo:dolgozo-detail' orderby=nev %} ">
I want to pass "nev" string.
url(r'^orderby=(?P<nev>.+)$', login_required(DolgozokListView.as_view(template_name="DolgozoKarbantart/DolgozokList.html")), name='dolgozo-detail'),
What is the regex for this, and how can i catch it in the view?
Why not try the simple one...
HTML
<a href="{% url 'dolgozo:dolgozo-detail' %}/?orderby={{ nev }}">
URL
url(r'^orderby/$', login_required(DolgozokListView.as_view(template_name="DolgozoKarbantart/DolgozokList.html")), name='dolgozo-detail'),
And in the view simply get the orderby using GET
orderby = request.GET.get('orderby')
html, no need for / before ?
<a href="{% url 'dolgozo:dolgozo-detail' %}?orderby={{ nev }}">
urls.py
url(r'^orderby/$', login_required(DolgozokListView.as_view(template_name="DolgozoKarbantart/DolgozokList.html")), name='dolgozo-detail'),
views.py
orderby = request.GET.get('orderby')

How to call a "wizard view" with {% url %} statement in Django?

urls.py:
url(r'^signin_client$', views.signin_client, name='signin_client') # normal view,
url(r'^signup_owner$', SignupOwnerWizard.as_view()), # wizard view
In a 'normal view' case: <a href='{% url "myapp.views.signin_client" %}'> works.
But I can't figure how to do the same thing for my "wizard view". Of course, I don't want to hardcode the url.
Add name to the pattern:
url(r'^signup_owner$', SignupOwnerWizard.as_view(), name='signup_owner'),
And than use the name in {% url %} tag:
<a href='{% url "signup_owner" %}'>
If you use namespaces you would need a namespace prefix:
<a href='{% url "mynamespace:signup_owner" %}'>

Categories