Django url tag multiple parameters - python

I have two similar codes. The first one works as expected.
urlpatterns = patterns('',
(r'^(?P<n1>\d)/test/', test),
(r'', test2),
{% url testapp.views.test n1=5 %}
But adding the second parameter makes the result return empty string.
urlpatterns = patterns('',
(r'^(?P<n1>\d)/test(?P<n2>\d)/', test),
(r'', test2),)
{% url testapp.views.test n1=5, n2=2 %}
Views signature:
def test(request, n1, n2=1):

Try
{% url testapp.views.test n1=5,n2=2 %}
without the space between the arguments
Update:
As of Django 1.9 (and maybe earlier) the correct way is to omit the comma and separate arguments using spaces:
{% url testapp.views.test n1=5 n2=2 %}

Here's an actual example of me using this technique. Maybe this will help:
{% if stories %}
<h2>Stories by #{{author.username}}</h2>
<ul>
{% for story in stories %}
<li>{{story.title}}</li>
{% endfor %}
</ul>
{% else %}
<p>#{{author.username}} hasn't published any stories yet.</p>
{% endif %}

https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#url
From Django 1.5 Warning Don’t forget to put quotes around the function path or pattern name!
{% url 'some-url-name' arg1=v1 arg2=v2 %}

Related

link in html do not function

python 2.7 DJANGO 1.11.14 win7
when I click the link in FWinstance_list_applied_user.html it was supposed to jump to FW_detail.html but nothing happened
url.py
urlpatterns += [
url(r'^myFWs/', views.LoanedFWsByUserListView.as_view(), name='my-applied'),
url(r'^myFWs/(?P<pk>[0-9]+)$', views.FWDetailView.as_view(), name='FW-detail'),
views.py:
class FWDetailView(LoginRequiredMixin,generic.ListView):
model = FW
template_name = 'FW_detail.html'
models.py
class FW(models.Model):
ODM_name = models.CharField(max_length=20)
project_name = models.CharField(max_length=20)
FW_detail.html
{% block content %}
<h1>FW request information: {{ FW.ODM_name}};{{ FW.project_name}}</h1>
<p><strong>please download using this link:</strong> {{ FW.download }}</p>
{% endblock %}
FWinstance_list_applied_user.html
{% block content %}
<h1>Applied FWs</h1>
{% if FW_list %}
<ul>
{% for FWinst in FW_list %}
{% if FWinst.is_approved %}
<li class="{% if FWinst.is_approved %}text-danger{% endif %}">-->
{{FWinst.ODM_name}} ({{ FWinst.project_name }})
</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
<p>Nothing.</p>
{% endif %}
{% endblock %}
the image of FWinstance_list_applied_user.html, when I click the link CSR, nothing happened
You haven't terminated your "my-applied" URL pattern, so it matches everything beginning with "myFWs/" - including things that that would match the detail URL. Make sure you always use a terminating $ with regex URLs.
url(r'^myFWs/$', views.LoanedFWsByUserListView.as_view(), name='my-applied'),
You are seeing this behavior because your first URL pattern is not terminated. The regular expression r'^myFWs/' also matches the URL path myFWs/123, so your FW-detail URL is never matched. You can fix that by simply appending a $ to your URL pattern.
urlpatterns += [
url(r'^myFWs/$', views.LoanedFWsByUserListView.as_view(), name='my-applied'),
# ^ this was missing

Django URL Regex - Template value to View

I'm having trouble passing a value from my Template index.html to
my View (duplicates(request, title).
Restricted to version 1.4.3.
I believe it to be a regex problem on my part in the urls.py file.
Current Error is Page not found (404).
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^missions/$', 'app.views.index'),
url(r'^missions/(?P<mission_id>\d+)/$', 'app.views.mission_overview'),
url(r'^missions/duplicates/(?P<title>[A-Za-z0-9-\s\>]+)/$',
'app.views.duplicates'),
)
I've tried using the title as a query string such as
url(r'^missions/duplicates/title(?P<title>[\s.\>])/$', ...)
index.html
{% if mt %}
<!-- Title (string), Num (int), mission_id (list) -->
{% for title, num, mission_id in mt%}
{% if num > 1 %}
<li><a href="missions/duplicates/{{ title|urlencode }}/">
{{ title }}
</a></li>
{% else %}
{% for mid in mission_id %}
<li>{{title}}</li>
{% endfor %}
{% endif %}
{% endfor %}
{% else %}
<p>No Titles</p>
{% endif%}
I have also tried
{{ request.GET.urlencode }}
and
{{% url app.views.duplicates title %}}
views.py Only showing the required inputs
def duplicates(request, title):
I either gotten Page not found errors or duplicates() takes exactly 2 arguments (1 given).
Main goal is getting title from the template to the view duplicates.
I have some funky titles like...
01 Wall_01-_Store>
AB.Chicken.1 StoreY
TO.Test.0 StoreZ'
Thanks ahead of time!
EDIT
The trailing slash was the problem here - the Page not found error shows url pattern 3 ending with a slash, but the current URL, does NOT end with a slash. I suspect some code changes between various bits copied and pasted here since the a href= line in the template DOES have a trailing slash.
The TypeError is caused by the fact that the named group is not matching anything - it requires AT LEAST ONE character, as the regex ends in + and not *. Why two trailing slashes are not needed here may also come down to code changes between bits that you've pasted up...

Django TemplateSyntaxError in with template tag

I'm trying to use this app in my project.
https://github.com/streema/django-favit
I already can use the fav-unfav part of this app. I also want to list favourites of user for every user. In read me part it says use this and it will be listed but I have an error with
{% with user_favorites <user> "baslik.Entry" as favorite_list %}
{% for fav_obj in favorite_list %}
{{ fav_obj }}
{% endfor %}
{% endwith %}
Error:
TemplateSyntaxError at /
u'with' expected at least one variable assignment
This is the template tag part for user_favorites:
#register.assignment_tag
def user_favorites(user, app_model=None):
"""
Usage:
Get all user favorited objects:
{% with user_favorites <user> as favorite_list %}
{% for fav_obj in favorite_list %}
{# do something with fav_obj #}
{% endfor %}
{% endwith %}
or, just favorites from one model:
{% with user_favorites <user> "app_label.model" as favorite_list %}
{% for fav_obj in favorite_list %}
{# do something with fav_obj #}
{%
{% endwith %}
"""
return Favorite.objects.for_user(user, app_model)
How can I get rid of this error? Thanks.
It's a reasonably common convention in documentation that anything in angle brackets is a placeholder to be replaced by the actual value. In this case, <user> is supposed to be replaced by the object containing the actual user.
{% with user_favorites request.user ...
I must say, though, that the documentation still doesn't make any sense. You can't use an assignment tag in a with statement like that - even after correcting the user issue, this still won't work. The confusing thing is that the same syntax is repeated throughout the documentation, but it simply doesn't work.
I think this is simply a bug with the documentation, and suspect that if you simply remove the word "with" this will work.
To use custom template tag in django, it is needed to explicitly load it in template.
Add this line at the beginnig of your template (but after {% extends ... %}, if you have such):
{% load favit_tags %}
Looks like this step is missed from django-favit README.

Django: Named URLs / Same Template, Different Named URL

I have a webapp that lists all of my artists, albums and songs when the appropriate link is clicked. I make extensive use of generic views (object_list/detail) and named urls but I am coming across an annoyance. I have three templates that pretty much output the exact same html that look just like this:
{% extends "base.html" %}
{% block content %}
<div id="content">
<ul id="starts-with">
{% for starts_with in starts_with_list %}
<li>{{ starts_with|upper }}</li>
{% endfor %}
</ul>
<ul>
{% for song in songs_list %}
<li>{{ song.title }}</li>
{% endfor %}
</ul>
</div>
{% endblock content %}
My artist and album template look pretty much the same and I'd like to combine the three template's into one. The fact that my variables start with song can easily be changed to the default obj. It's my <ul id="starts-with"> named url I don't know how to correct. Obviously I want it to link to a specific album/artist/song using the named urls in my urls.py but I don't know how to make it context aware. Any suggestions?
urls.py:
urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
# (r'^$', index),
url(r'^artists/$', artist_list, name='artist_list'),
url(r'^artists/(?P<starts_with>\w)/$', artist_list, name='artist_list_x'),
url(r'^artist/(?P<artist_id>\d+)/$', artist_detail, name='artist_detail'),
url(r'^albums/$', album_list, name='album_list'),
url(r'^albums/(?P<starts_with>\w)/$', album_list, name='album_list_x'),
url(r'^album/(?P<album_id>\w)/$', album_detail, name='album_detail'),
url(r'^songs/$', song_list, name='song_list'),
url(r'^songs/(?P<starts_with>\w)/$', song_list, name='song_list_x'),
url(r'^song/(?P<song_id>\w)/$', song_detail, name='song_detail'),
)
You could define url patterns for a generic object_type instead of individually for artists, albums and songs:
urlpatterns = patterns('tlkmusic.apps.tlkmusic_base.views',
# (r'^$', index),
url(r'^(?P<object_type>\w+)/$', music_object_list, name='music_object_list'),
url(r'^(?P<object_type>\w+)/(?P<starts_with>\w)/$', music_object_list, name='music_object_list_x'),
url(r'^(?P<object_type>\w+)/(?P<object_id>\d+)/$', music_object_detail, name='music_object_detail'),
)
Then in your template, your url tag becomes
{% url music_object_list_x object_type starts_with %} *
You may find you only need one view, music_object_list. If you find you need different functions for each object type, then call the individual functions in music_object_list.
def music_object_list(request, object_type, starts_with=None):
if object_type == 'artists':
return artist_list(request, starts_with=starts_with)
elif object_type == 'albums':
return album_list(request, starts_with=starts_with)
...
If you are using django.views.generic.list_detail.object_list, then remember to add object_type to the extra_context dictionary. This will add object_type to the template context, allowing the url tag to work.
extra_context = {'object_type': 'songs', ...}
* This is the new url tag syntax for Django 1.2. For older versions you would use a comma.
{% url music_object_list_x object_type,starts_with %}
See the docs (Current, 1.1) for more information

Django 1.1 - comments - 'render_comment_form' returns TemplateSyntaxError

I want to simply render a built-in comment form in a template, using Django's builtin commenting module, but this returns a TemplateSyntaxError Exception.
I need help debugging this error, please, because after googling and using the Django API reference, I'm still not getting any farther.
Info:
This is the template '_post.html'[shortened]:
<div id="post_{{ object.id }}">
<h2>
{{ object.title }}
<small>{{ object.pub_date|timesince }} ago</small>
</h2>
{{ object.body }}
{% load comments %}
{% get_comment_count for object as comment_count %}
<p>{{ comment_count }}</p>
<!-- Returns 0, because no comments available -->
{% render_comment_form for object %}
<!-- Returns TemplateSyntaxError -->
This is the Exception output, when rendering:
Caught an exception while rendering: Reverse for 'django.contrib.comments.views.comments.post_comment'
with arguments '()' and keyword arguments '{}' not found.1
{% load comments i18n %}
<form action="{% comment_form_target %}" method="post">
{% if next %}<input type="hidden" name="next" value="{{ next }}" />{% endif %}
{% for field in form %}
{% if field.is_hidden %}
{{ field }}
{% else %}
{% if field.errors %}{{ field.errors }}{% endif %}
<p
{% if field.errors %} class="error"{% endif %}
{% ifequal field.name "honeypot" %} style="display:none;"{% endifequal %}>
{{ field.label_tag }} {{ field }}
/posts/urls.py[shortened]:
queryset = {'queryset': Post.objects.all(),
'extra_context' : {"tags" : get_tags}
}
urlpatterns = patterns('django.views.generic.list_detail',
url('^$', 'object_list', queryset,
name='posts'),
url('^blog/(?P<object_id>\d+)/$', 'object_detail', queryset,
name='post'),
)
/urls.py[shortened]:
urlpatterns = patterns('',
(r'', include('posts.urls')),
(r'^comments/$', include('django.contrib.comments.urls')),
)
I had the same exact problem, render_comment_form template tag was triggering it.
The issue is certainly with your URL config, you had it set the same way i did:
(r'^comments/$', include('django.contrib.comments.urls'))
The correct way is to remove the '$' after 'comments/':
(r'^comments/', include('django.contrib.comments.urls'))
Otherwise django can't properly include all necessary urls under the path comments/...
Hope this helps.
The error message is indicated that it can't find a reverse url for:
django.contrib.comments.views.comments.post_comment
So basically something isn't configured right in your urls. Without being able to see more of how things are setup it's difficult to know exactly what.
Maybe try re-ordering the urls pattern includes in your urls.py, to force the django comments urls to the top?
I had this same problem today. I was referencing a view in urls.py that I hadn't created yet.
From http://docs.djangoproject.com/en/dev/topics/http/urls/#reverse
As part of working out which URL names
map to which patterns, the reverse()
function has to import all of your
URLconf files and examine the name of
each view. This involves importing
each view function. If there are any
errors whilst importing any of your
view functions, it will cause
reverse() to raise an error, even if
that view function is not the one you
are trying to reverse.
Make sure that any views you reference
in your URLconf files exist and can be
imported correctly. Do not include
lines that reference views you haven't
written yet, because those views will
not be importable.
This error is saying that it found the view django.contrib.comments.views.comments.post_comment
but no args () or kwargs{} were passed.
Its not passing a value for object.id into the url.
Take out the url tag and see if the id of the <div id="post_{{object.id}}"> reflects a proper object.id

Categories

Resources