django url concatenation. I don't want to concatenate - django

when I do something in 'profile' page,
the url is concatenated to the next of 'profile'.
but I want to link to just 'signout'. not 'profile/signout'
this is my urls.py.
when ever I do something in 'profile'page,
the href link is concatenated to 'profile'url.
this is href source.
since this href source is header.html,
this page is included another pages.
and in the other pages, it works well.
only in profile page, the href url is concatenated to 'profile/1' url.
how can I fix it?

Yes, a URL not starting with a slash or a scheme is a relative URL. href="foo" is equivalent to href="./foo", i.e. it refers to the path foo relative to the current path. If you want the top-level path, you want href="/foo".
In Django you're supposed to use the {% url %} template tag to generate URLs, you don't hardcode them. Django will take care to generate the correct URL; especially if you move the app around to other environments, the URL may require a prefix or such, so you should never hardcode the URL.

Related

Add url parameters to a url in django view

I have a django view that lists several urls on external sites.
When I render them I would like to add a few url parameters to each.
These urls are to an external system and thus not listed in my urls.py. Furthermore, some of the links have a hash '#' so it is not as easy as appending a few parameters to the end of the string.
Based on these requirements it seems the url template tag will not be a good fit. I was wondering if there is a custom filter out that to do this.
You don't need Django's url tag here. The url tag is to resolve to URLs that belong to your application.
However, there is the nice django-spurl library. It allows you to handle query parameters via template tags.
An example from the documentation to add query parameters:
{% spurl base="http://example.com/?foo=bar" add_query="bar=baz" %}
<!--
will result in: http://example.com?foo=bar&bar=baz
-->

Url mismatch, django template link

I've got a prob with a link in the sidebar of my django site, in the template it's like that:
<li>Profile</li>
while in the urls.py:
url(r'^(?P<user_id>\d+)/profile/$', 'auth.views.show_profile', name='profile')
When i access it from the main page with url: e.g /1001/profile/ it loads fine but when I try to access it from another subpage with url: e.g /1001/forms/profile/ i get the error: The current URL, /1001/forms/profile/, didn't match any of these. How can i fix this?
It is because "profile" is a relative URL, and a relative URL is appended to the current URL - the resulting address is not valid across the whole site. Seems like you should use an absolute URL in your case.
At the template you can try something like:
Profile
UPDATE
To get request available in templates you have to add django.core.context_processors.request to TEMPLATE_CONTEXT_PROCESSORS. I'm not sure if it is added by default.
You must have to add your second subpage url in urls like you did for /1001/profile/
url(r'^(?P<user_id>\d+)/form/profile/$', 'auth.views.show_profile', name='profile_form')
and also correct your code as #Paulo mentioned or you can also do it through reverse url.
Profile

Get the original path in django

I have a question: how to get the current path of the url. Let's say, I have 3 navigation bars, about , blog and contact page. In each page, I have facebook, twitter and a manual email a friend button. When I clicked the email a friend button, and the current URL is www.example.com/about, the current URL is now already www.example.com/emailafriend. How can I get the www.example/about? Also in blog and contact. Please help me. Thanks.
How does your email a friend button work? Is it a django view that takes the current URL and emails it? If so, you don't want the "current" URL, which, as you note, is actually the email a friend URL. What you want to do is pass the URL you want to share as a URL parameter, ie:
/share?url=http://www.example.com/blog
Adding more info based on comments:
When I was referencing URL above, I was not referring to your django URL configuration. Let's take a step back.
On your About page you have a link to email a friend, right? That link is probably generated in your template, but it's the same on every page. Something like:
Email a friend
Instead of this, try this:
Email a friend
Now you need to make your email_a_friend view handle this. It can get the url via
request.get('url', '').
Some additional information:
You might want to escape the {{ request.get_full_path }} function so that it's escaped and URL safe, then you'll have to unescape it in your view. Once you get the URL back to your view, you can do as you please with it.
{{ request.get_full_path|urlencode }}
Try using Relative URLs like for example From www.example.com/about to get to www.example.com/email use /email. Using relative urls is the simplest solution .
Take a look at this.
Absolute vs relative URLs
It sounds like your want to get the referring URL (the URL that sent you to the current page). That is available to you in the request object, although it is not 100% reliable:
request.META['HTTP_REFERER']
See the documentation on HttpRequest objects for more information.

Django Generic object_list pagination. Adding instead of replacing arguments

I'm having some trouble with the django generic object_list function's pagination not really being "smart" enough to compensate my daftness.
I'm trying to do a url for listing with optional arguments for page number and category.
The url in urls.py looks like this:
url(r'^all/(?:(?P<category>[-\w]+)/page-(?P<urlpage>\d+))?/$',
views.listing,
),
The category and urlpage arguments are optional beacuse of the extra "(?: )?" around them and that works nicely.
views.listing is a wrapper function looking like this( i don't think this is where my problem occurs):
def listing(request,category="a-z",urlpage="1"):
extra_context_dict={}
if category=="a-z":
catqueryset=models.UserProfile.objects.all().order_by('user__username')
elif category=="z-a":
catqueryset=models.UserProfile.objects.all().order_by(-'user__username')
else:
extra_context_dict['error_message']='Unfortunately a sorting error occurred, content is listed in alphabetical order'
catqueryset=models.UserProfile.objects.all().order_by('user__username')
return object_list(
request,
queryset=catqueryset,
template_name='userlist.html',
page=urlpage,
paginate_by=10,
extra_context=extra_context_dict,
)
In my template userlist.html I have links looking like this (This is where I think the real problem lies):
{%if has_next%}
<a href=page-{{next}}>Next Page> ({{next}})</a>
{%else%}
Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/
It's not really surprising that this is what happens, but not having page as an optional argument actually works and Django replaces the old page-part of the url.
I would prefer this DRYer (atleast I think so) solution, but can't seem to get it working.
Any tips how this could be solved with better urls.py or template tags would be very appreciated.
(also please excuse non-native english and on the fly translated code. Any feedback as to if this is a good or unwarranted Stack-overflow question is also gladly taken)
You're using relative URLs here - so it's not really anything to do with Django. You could replace your link with:
Next Page> ({{ next }})
and all would be well, except for the fact that you'd have a brittle link in your template, which would break as soon as you changed your urls.py, and it wouldn't work unless category happened to be a-z.
Instead, use Django's built-in url tag.
Next Page> ({{ next }})
To make that work, you'll have to pass your category into the extra_context_dict, which you create on the first line of your view code:
extra_context_dict = { 'category': category }
Is /all/a-z/page-1/page-2/ what appears in the source or where the link takes you to? My guess is that the string "page-2" is appended by the browser to the current URL. You should start with a URL with / in order to state a full path.
You should probably add the category into the extra_context and do:
next page ({{next}})
"Instead of replacing the page argument in my url the link adds another page argument to the url. The urls ends up looking like this "/all/a-z/page-1/page-2/"
that is because
'<a href=page-{{next}}>Next Page> ({{next}})</a>'
links to the page relative to the current url and the current url is already having /page-1/ in it.
i'm not sure how, not having page as an optional argument actually works and Django replaces the old page-part of the url
one thing i suggest is instead of defining relative url define absolute url
'Next Page> ({{ next }})'

View referenced by two urls and url tag

I am using url tag in my template for a view, that is used by two different urls. I am getting the wrong url in one place. Is there any way to force django to retrieve different url? Why it doesn't notify my, that such conflict occured and it doesn't know what to do (since python zen says, that is should refuse temptation to guess).
Code in template:
{% url djangoldap.views.FilterEntriesResponse Entry=entry.path as filter_url %}
Code in urls:
(r'^filter_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'filter_entries.html',
'results_template': 'filter_results.html'}),
(r'^choose_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'search_entries.html',
'results_template': 'search_results.html'}),
As you can see, those two urls use the same view, but with different templates. How I can force django to retrieve former url, rather than latter?
Name your URLs by adding another item to the tuple:
(r'^choose_entries/(?P<Entry>.*)/$',
'djangoldap.views.FilterEntriesResponse',
{'filter_template': 'search_entries.html',
'results_template': 'search_results.html'},
'sensibleprefix-choose_entries') # <-- this is the name
Then you can use the name in the URL tag.