Django: How to make this GET request with a hyperlink? - django

So if I want a user's name to link to it's profile, I want the link to contain the user's first name and last name in GET form...Do I just hard-code this into the link, or is there a more elegant way of coding this? Here is hard-coded:
<p>
<li role="presentation" class="active">{{ user.fname }}
</li>
</p>

Yes, the more elegant way would be to set up a route that takes, for example, the user's ID (pk) and use either a DetailView set up for the User model or a function view that accepts the ID and retrieves the relevant user. Passing in the first and last name directly means you need to query on both of them (after pulling them out of the querystring) rather than simply querying on the ID as it's passed to you (after the framework politely checks its type, provided you've set up the route correctly).
So your route would look something like url(r'^profile/(?P<pk>\d+)/$', ProfileView.as_view(), name='profile') and your template tag would look something like {% url 'profile' user.id %}.

Related

Django: How to get user full name from user id

My model:
author=models.ForeignKey(User)
User id (ex. 174948) is saved to column author_id.
In the template I show user id with {{post.author}}
I want also to show full name for that particular user.
How to do that in the template?
By using the method that does it.
{{post.author.get_full_name}}
It depends if the user object has the first and/or last name fields set.
If not (for example a new user was just created), then calling {{ post.author.get_full_name }} may return an empty string.
This method is more reliable:
{{ post.author.get_full_name|default:post.author.username }}
Another way
{{post.author.first_name}} {{post.author.last_name}}

How to pass a variable to urls.py

I have a database 'artist' with one table : 'name', 'style'.
Users can add any names for an artist.
I would like to pass an argument to url in my template, like this :
<a href="{% url 'webgui.views.music' artist.name %}" style="margin-bottom: 3px" type="button"
But is it possible to set dynamically the URL with the argument 'artist.name' (in urls.py) ?
My urls.py actually :
url(r'^music/(\d+)/$', 'webgui.views.music'),
Maybe I need to change '\d+' by another regexp ??
Instead of using
url(r'^music/(\d+)/$', 'webgui.views.music'),
because d+ stands for digits, you should use
url(r'^music/?P<artist_name>[a-zA-Z0-9 \'&-]/$', 'webgui.views.music')
Don't forget to modify function
def whatever_named_it(request, artist_name):
...
Update: In template you should use
{% url 'webgui.views.music' artist_name=artist.name %}
because we are using named arguments.
Extra: If you are going to allow any text for artist's name, I would recommend you using slug to avoid spaces in URL. That would make it better to read, search engine friendly and avoid of insane user input. When programming web-app never trust user input ... ever.
For "slugified" name urls would be:
url(r'^music/(?P<slug>[\w-]+)/$', 'webgui.views.music')

Django if statement with foreign key

Cut it short I have a model called Page and a field called "parent" that links to itself, I want to write if the nav.parent has a parent called home then do this but for some reason it doesn't work.
{% if nav.parent == "home" %}
The problem is of course that Django doesn't know which field to use when comparing, unless you tell it. Since "home" is in the title field, you need to actually specify that field:
{% if nav.parent.title == "home" %}
You can't do this in the template.
You have 2 options as a solution to your problem:
The bad one: pass the variables in the context from the view.
The best: create a custom tag which will receive nav as a parameter and find its parent:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

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.

Dynamically set default form values in django

I'm trying to find a way to dynamically set default form values. So for example, if I add a facebook login feature on my webpage, and I can get his first name and last name from what the facebook javascript returns, I want to be able to set these values as the new "value" parameter in the given form. (basically so I'm able to put the user in my database)
I was hoping that there is some sort of
{{ form.firstname.default = Javascript.return.firstname }}
that I can insert into a template but there isn't...
Any ideas? Thank you.
Edit;; Maybe it would be better to first pass in the information into a views.py? But how would I do this? I am just considering hand writing the inputs out in the javascript field, which would be annoying...
You can set the default value of a template variable:
{{ form.firstname|default:Javascript.return.firstname }}
assuming that {{ Javascript.return.firstname }} is valid in that template context.
The code generated by Django is all server-side, its templates can't use anything which isn't available when the page is loaded. You need to use javascript to set the value.
For example, if your form looks like this:
<form id="login">
<input name="firstname" />
</form>
You could use this javascript (assuming you're using jQuery):
// Do the facebook login, set the var fname to the first name, then:
$('#login [name=firstname]').val(fname);