Rendering dynamic variable in a django template - python

I am trying to render dynamic Url in Django template as follows
<a href={{'jibambe_site_detail/'|add: site.id}}>{{ site }}</a>. This however is returning a TemplateSyntaxError at /jibambe_sites/
add requires 2 arguments, 1 provided. What am I missing or how should I render this dynamic URL, I want it to produce something like jibambe_site_detail/1

OP's strategy changed on this one but OP's original error seems to be because of the space after colon.
Use add:site.id instead of add: site.id
See a similar question about default here

From #schwobaseggl comment, I was able to add a dynamic url variable as follows <a href={% url 'site_details' pk=site.id %}>{{ site.name }}</a>
then in the urls.py urlpatterns, I gave the path to jibambe_site_details a name path('jibambe_site_detail/<slug:pk>', JibambeSitesDetails.as_view(), name='site_details'),

Related

Getting 'path' of previous URL from template

I know I can get the previous URL in the template by using the following:
{{ request.META.HTTP_REFERER}}
But I want to know if I there's a way to get only the path and not the absolute URL
(i.e /my-page instead of http://localhost:8000/my-page)
Like in the view we can do:
from urllib import parse
parse.urlparse(request.META.get('HTTP_REFERER')).path
Can I do something like that in the template as well?
Update (with more info): My usecase is to compare the previous url with another url within the same site to see if the user came in from there
Looks like there isn't a direct way to do that in the template, so this is what I ended up doing in the template to check if a particular (relative) url is part of the previous (absolute) URL :
{% url 'schoollist:add_school' as add_school_url %}
{% if add_school_url in request.META.HTTP_REFERER %}
Thanks for adding!
{% endif %}
A possible way to achieve this is to use urlparse to get components out of the referer URL, then get the relative path.
If you handle it with custom code this probably won't do much difference for basic cases but probably do some good with fancier edge cases:
from urlparse import urlparse
referer = request.META.get('HTTP_REFERER')
path = urlparse(referer).path
See: Parse URLs into components

Cannot have any URLs with slugs. NoReverseMatch

I'm a begginer grasping at straws with difficulty dealing with the django slug url system and these NoReverseMatch errors that make no sense to me even after reading the docs.
I have a django project. In one of the views, I pass a list of geoJSON features into a template, and show them on a map. I want to have each feature act as a clickable 'link' to a view that will show stuff about it. The following is part of the template that has those features that I want to click on:
//part of the template:
<script type="text/javascript">
...
function onEachFeature(feature, layer) {
layer.on('click', function (e) {
window.location.href = "{% url 'polls:areadetail' feature.properties.myslug%}";
});
}
(I have confirmed that feature.properties.myslug does in fact contain the slug I want).
The url pattern I want to go to:
urlpatterns = [...
url(r'^areadetail/(?P<areaslug>[-\w]+)/$', views.AreaDetail, name='areadetail'),]
And the view it relates to:
def AreaDetail(request, areaslug):
area = get_object_or_404(Area, nameslug=areaslug)
return render(request, 'polls/areadetail.html', {'area':area})
The issue I get is, by doing what I show and placing that url reference inside that template I show above, that I want to be able click on, that template won't even work at all, giving me a 'Error during template rendering' full page error info that starts with:
NoReverseMatch at /polls/areas/
Reverse for 'areadetail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/areadetail/(?P[-\w]+)/$']
Any help would be immensely appreciated
EDIT part1: As I've said in response to falsetru, I'm sure feature.properties.myslug has in fact got a slug expression in it.
EDIT2: Based on something I found in a django ticket, I've made a slight change in the url regex at urls.py, from (?P<areaslug>[-\w]+)/$ to (?P<areaslug>[-\w]+)?/$ and now the error is:
Page not found (404)
Request Method: GET Request URL: http://127.0.0.1:8000/polls/areadetail// Raised by: polls.views.AreaDetail
Is it possible that because the "{% url 'polls:areadetail' feature.properties.myslug%}" bit is inside javascript, that feature.properties.myslug is not being inserted there correctly? Like some sort of brackets are needed here?
According to the error message, feature.properties.myslug is empty or has no value.
Make sure the feature.properties.myslug is passed correctly from view.
Comment out {% url .. %} temporarily.
Print {{ feature }}, {{ feature.properties }}, {{ feature.properties.myslug }} to see if which part is missing.
Fix view accordingly.
Uncomment {% url .. %}.
After some more digging around I've found the answer to why doesn't this work in another question at:
How to pass javascript variable to django custom filter
The answer to it by Ludwik Trammer says:
Django templates are build on the server side, while JavaScript is executed on the client side.
That means that template code is always executed before JavaScript (as
it is executed by the server, before the page is sent to the client).
As a consequence it is absolutely impossible to mix JavaScript and
Django code the way you want to.
Which clearly applies here. I was focused on problems with the URL template, regex on the urls.py file etc. when the problem was that no matter what I did, because it's in a javascript section, run client-side, that URL template will always be incomplete no matter what I do, therefore being an impossible solution to what I want.

URL trouble to pass parameter

This link can not pass parameter to view.py
profile
It gives an error page not found, 127.0.0.1:8000/profile/edit/
There is not parameter there, even {{costumer.slug}} returns a string
Rest of template has no porblem to pass a parameter like this:
{{j.title}}
What can be wrong here?
Your problem is that you are missing a leading slash, so the browser is concatenating the URL with the one you're already on (you're on '/profile', you click 'edit', you go to '/profile/edit').
But you shouldn't be building up URLs like that. You should use the url tag. Assuming your URLconf is this:
url(r'^edit/(?P<slug>\w+)/$', 'profile.views.edit_profile', name='edit_profile')
you would do this in the template:
<a href="{% url 'edit_profile' slug=costumer.slug %}">

Generic Views NoReverseMatch when using {% url %} in Django

I have a problem to do the reverse command 'url' from the template base.html.
URLS.conf my file looks like this:
dic_info_artigo = {
'queryset': Artigo.modificado.all(),
'date_field': 'data_pub',
}
urlpatterns = patterns('django.views.generic.date_based',
(r'^$', 'archive_index', dic_info_artigo,'artigos'),
(r'^(?P<year>\d{4})/$','archive_year', dic_info_artigo,'artigos_ano'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/$',
'archive_month', dic_info_artigo,'artigos_mes'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/$',
'archive_day', dic_info_artigo,'artigos_dia'),
(r'^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$',
'object_detail', dic_info_artigo,'detalhe_artigo'),
)
base.html
<a href="{% url artigos %}"> Artigos </ a>
The error:
dictionary update sequence element # 0 has length 1; 2 is required
Already tried using the parameter 'name=', i change the value , but it did not work
url(r'^$', 'archive_index', dic_info_artigo, name='artigos'),
What am I doing wrong? Any tips?
Thanks.
The error message suggests that you have tried to name a view using something like:
(r'^my_url$', 'my_view', 'my_view')
However, the third argument should be a dictionary, not the name of a view.
To prevent errors like this, I recommend always using the url shortcut and naming the url pattern:
url(r'^my_url$', 'my_view', name='my_view')
However, you could pass an empty dictionary as the third argument if prefer:
(r'^my_url$', 'my_view', {}, 'my_view')
The urls.py you have posted looks ok, so the problem is probably in a different urls.py. If you're lucky, the full traceback might give you the exact line of the module where the error is occurring.
Use url() to name the urls and try the following in template file.
{% url 'artigos' %}

Django url template confusion

Okay I am having a bit of an issue.
I want to create a button with a link, and right now I am using action={% url views.contest_overview %} in hopes that the reverse lookup by Django will match (r'^category/$', views.contest_overview), in my urls.py. However, this is not working and I can't figure out the proper nomenclature, despite numerous guesses.
The error I get (with my best guess above) is:
Caught NoReverseMatch while rendering: Reverse for
'views.contest_overview' with arguments '()' and keyword arguments
'{}' not found.
Thank you very much for your time!
Use the application name in the url tag, e.g. {% url myapp.views.contest_overview %}
This is what I usually do; I give names to my url. For example:
url(r'^account/register/$', 'someapp.views.register_view', name='account_register'),
Therefore in template, I can do this:
{% url account_register as url_acc_register %}
<html>
..
..
Some link

Categories

Resources