Django path to current page - django

I have a django template page, and want a link from this page, containing current URL, for example, I am on /article/11 and want link to /article/11/remove
I tried the following construction:
Remove article
But I get link to /article/remove instead of /article/11/remove
However when I change it to
<a href="{{ request.path }}">
I get link to /article/11
How can I get URL not trimmed?

I don't see why it doesn't point you to /article/11remove, which is what it sounds like it should do, but either way, you're missing a slash. Try <a href="{{ request.path }}/remove"> instead.
However, that's really not the right way to do it. You shouldbe using {% url 'name_of_remove_view' %} to get the url, not assuming it's going to be wherever you are plus /remove.
Edit: In that case, your problem is probably that {{ request.path }} is not outputting anything at all. That would explain why just having "remove" would take you to /article/remove, and having "" would take you to where you currently are, due to the way that relative URLs work. You might want to make sure that you have a request object at all in your template environment.

Related

Could not parse the remainder: '/{{menu.Info.page}}' from ''item'/{{menu.Info.Page}}'

<img id="page" class="abc" src="{{STATIC_URL}}page/code_251.png" style=""/>
Hitting this url like localhost:8000/app/page works fine.
If I want something from views and append that pageid with url then showing error as Couldn't parse.
From views:{{page.pageid}}
output url should be :localhost:8000/app/?pageid=xx
for this i tried with below syntax:
<img id="page" class="abc" src="{{STATIC_URL}}page/code_251.png" style=""/>
But above syntax did't worked for me.
urls.py
url(r'^(page)(?:/(?P<page_id>[0-9]+))?/$',page_ViewDetails_TemplateView.as_view(),name="page"),
May be some changes need to be done on urls.py as well.
Can someone share some idea!!
You're confused about at least two things here.
Firstly, you would never use {{ }} inside a tag. You're already in the template language context there: you have access to variables directly.
Secondly, the {% url %} tag works on urlpattern names and parameters, not literal URLs. And your page URL does not expect a querystring value for page_id: it expects it as part of the path. Your generated URL needs to be "/page/3", not "/page?page_id=3".
So your URL tag is just:
<a href="{% url 'page' page_id=page.pageid %}">

Django : model instance url is appending to the current url

i have some link in a template to which i want to point to particular url.
template is accessed at url : loacalhost:8000/account/profile
{% for poll in voted_poll_list %}
<h4>{{ poll.title }} </h4>
{% endfor %}
in models.py i have created the url for the poll objects to be used in a template.
def link_url(self):
return "polls/"+ "allcat/" +str(self.id)
the problem is when a link in template is clicked it is point to the loacalhost:8000/account/profile/polls/allcat/1 instead of loacalhost:8000/polls/allcat/1 which matches to url pattern
url(r'^polls/(\w+)/(?P<pid>[-\d]+)/', 'pollsite.views.poll_detail', name='detail_poll'),
the problem is link url of object is appended to current url. how can i avoid this ?
#garnertb 's solution works, but you should probably look into using the reverse function rather than hardcoding your url.
Something like:
return reverse('detail_poll', self.id)
This will not only take care of the leading slash, but also avoid trouble if you ever start changing your url configuration.
Try leading the url with a forward slash:
def link_url(self):
return "/polls/allcat/" +str(self.id)

Make django url tag fail silently

The Django {% url %} templatetag raises a NoReverseMatch error when it can't reverse the provided URL. This is useful in development, but in production, this stops the user dead in their tracks with an ugly 500 error, blocking the whole page, and leading them to think our site is broken.
Template developers shouldn't be able to bring down the whole site with a typo. What I want to do is transparently override this behavior so that, in production only, if a reverse match can't be found, it outputs a default url, like "#", and reports the error to our exception tracking system in the background, but still lets the user continue with what they were doing without raising the 500 error.
Is there a way to replace the default {% url %} tag with my own safer version, transparently? I don't want to have to add a {% load my_custom_url_tag %} at the top of every single template on the site, because at some point people will forget, and the behavior of the tag is will otherwise be the same, the only difference is how it handles errors.
You can use the built-in url tag in silent mode, try the lookup, and then use the URL it finds—if it finds something.
From the Django docs:
This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you’ll use this to link to views that are optional:
{% url 'path.to.view' as the_url %}
{% if the_url %}
Link to optional stuff
{% endif %}
Hope that helps.
By implementing your own url tag, you're opening yourself up to lots of forward compatibility issues. My recommendation would be to add custom 500 error handler instead: https://docs.djangoproject.com/en/1.4/topics/http/views/#the-500-server-error-view
I would think you would actually want the view to throw an error if a template developer has made a typo. Trying to mask that behavior seems illogical - isn't that reason enough to have some simple unit tests to make sure your views are at least returning a 200 response code?

Showing 'cancel' on login page to return user to where they were (using django.contrib.auth)

We are using the #login_required decorator so that users see a login page if they try to access a url for which they need to be authenticated.
We want to show a 'cancel' button on the login page, which should return the user to whichever page they were on when they tried to access the url (by clicking a link etc - we don't need to deal with them manually entering the url).
At the moment our login.html looks for a request parameter 'login_cancel_url' and if present uses that (otherwise the home page).
However, this means we have to manually pass this parameter (set to the url of the current page) whenever we show a link or button that leads to an 'authentication required' url.
Is there a more elegant way to do this?
Thanks, Martin
Well you can try get the referrer header from the request but as far as I am aware, it's browser dependent and is not very reliable so the way you are doing it is probably best. You could try make life easier by creating template tags to avoid having to rewrite the return URL manually.
You are easily able to get the current URL from django's request object on any page, so instead of setting it manually on the link, you could write a snippet of html:
link_to_login.html
<!-- You should probably get /login/ using the {% url ... %} template tag -->
<a href="/login/?login_cancel_url={{ request.path|urlencode }}">
Login Page</a>
and use the {% include "link_to_login.html"%} template tag.
Alternatively, If the text needs to be different depending on the link you can instead create an inclusion template tag:
templatetags/extra_auth_tags.py
#register.inclusion_tag('templates/extra_auth_tags/login_link.html')
def login_link(context, text=None):
return {
'text':text
}
templates/extra_auth_tags/login_link.html
<!-- You should probably get /login/ using the {% url ... %} template tag -->
<a href="/login/?login_cancel_url={{ request.path|urlencode }}">
{% if text %}
{{ text }}
{% else %}
Some Default Text
{% endif %}
</a>
and then call it in your templates as {% login_link text="Check you messages" %}. Be aware that keyword arguments for inclusion tags are only supported in the django dev version so you might need to write the template tag by hand.

Create a PDF or Printable version of change_list.html in Django Admin

I would like to add a tool link at the top of my admin change_list.html, which I have already done, and have this link basically be able to produce some sort of printable document version of my models data based off of my current filter settings. Basically a print button in the admin change_list.html.
so far I have overridden the change_list.html to create the link, and I notice that this
<li>
<a href="{{ choice.query_string|iriencode }}" class="addlink">
{% blocktrans %}View PDF{% endblocktrans %}
</a>
</li>
gives you a link based on these choices.. but Im kinda lost as to the best/easiest way to do this..
Sorry, new to Django. I know I can use ReportLabs to generate pdfs, but not a 100% on how to get the filtered data from change_list to it.
A bit late, but for those who might be searching "in the future" like me, this might be helpful: http://djangosnippets.org/snippets/1842/