Getting value of URL-encoded request.GET variable in Django Template - django

I am using Django 1.3 with Python 2.7.2 on Windows 7 x64.
I have a URL pattern like this:
url(r'^(?P<club_id>\d+)/$', 'view_club')
From the pattern I want to be able to use request.GET in my templates to be able to create URLs to my views based on this GET variable (club_id). I have read online that I would be able to do:
{{ request.GET.club_id }}
However, this is always showing up as blank. I cannot figure out the reason why. I have the request context processor in my list of default context processors.
Thanks for the help.

In your example, club_id is not a GET parameter, it is part of the path in the URL. Your view function takes club_id as an argument, it should then put it in the context so the template can access it.
For example, your view function:
def view_club(request, club_id):
return render(request, "template_name.html", { 'club_id': club_id })
then in your template:
{{ club_id }}

IF you are passing an variable in the URL - in this case club_id - simply include it as an argument in your view function next to request:
def get_club(request,club_id):
club = Club.object.get(pk=club_id)
return render_to_response('club.html', {'club': club})
now in your template you can access {{club}} as the individually selected object and do things like {{club.name}} This also works for variables with multiple objects which you would use a for loop to iterate through.

Related

My custom Jinja template filter will not register or work?

I've created a custom filter but my Flask server is getting an internal error.
#app.template_filter('doSomething')
def doSomething(input):
print(input)
return input
HTML
<p>{{ doSomething('Test') }}</p>
Error
jinja2.exceptions.UndefinedError: 'doSomething' is undefined
After some searching, trial and error, this is the only one that seems to work for me:
def doSomething(input):
print(input)
return input
app.jinja_env.globals.update(doSomething=doSomething)
In the documentation it says :doSomethingWith({{ user.username|tojson|safe }}); which means that the user.username object will be json serialised and then passed to the doSomethingWith which is a JavaScript function;not like {{doSomethingWith(user.username|tojson|safe);}} you used in your example which looks like you are trying to explicitly call a python function from the template, so try this and if you still have any troubles tell us more about what exactly you're trying to achieve.
Just to make this answer a bit useful while also addressing the question, I'll show a custom filter function for which I had a need. You can use the .app_template_filter() decorator method on your Flask app to effectively "register" the new template filter function. Once it's registered you can use it on any template within the context of your app or blueprint.
If you're using blueprints, in your controller you'd do something like this:
#some_blueprint.app_template_filter()
def utcToStrFilter(someUTCFloat):
try:
shiftedDateStr = datetime.strftime(datetime.fromtimestamp(someUTCFloat), "%Y-%m-%d %H:%M:%S")
return shiftedDateStr
except:
return ""
If you're not using blueprints then your decorator would be:
#app.app_template_filter()
or
#current_app.app_template_filter()
In any case, then in your template you just use it like a regular jinja filter:
{{ something.fileSavetimeUTC | utcToStrFilter }}
The key thing is to make the app aware of the function, which is what .app_template_filter() is for.

django Is there a way to get a reversed url without passing parameters?

I am using ajax data to pass info to my page, but I need to create some links that use data from the javascript to call a view, so the parameters usually passed when one does a {% url 'jobs:close' foo %}, for example, are not available at the time the template is rendered, but imported later through an ajax call. Obviously, this causes errors when the template is rendered.
Is there a way to keep the benefit of having reverse url lookups in such a situation, and dynamically get the URL in the template without passing foo, or do I need to hard code the URL in the template and paste the parameter on the end later?
Instead of getting 'foo' in ajax response, get the reverse url in ajax response and replace the DOM where you need the url.
After thinking about it, and looking at comments, I decided on the answer of adding a fake parameter and removing it afterwards. Since it will be removed when the form is rendered, the parameter doesn't much matter. I chose 1.
So, in my template, I put {% url 'jobs:close' '1' %}. Then in my javascript, as I call the form in a modal, I use jquery to find the form. It makes it easy just to use the same URL again, so here it is:
var modal = $("#modal");
var closeUrl = '{% url 'jobs:close' '1' %}';
closeUrl = closeUrl.substring(0, closeUrl.length - 2) + event.data.id + /;
modal.find("#close-job").attr('action', closeUrl);
event.data.id is where I am storing the job ID that I really need.
It isn't as slick as I was looking for, but it works well.

Django querystring transfer from template to view by (input field or anyother tags)

How would you transfer tag values to a querystring in an anchor tag in a template ?
For example, suppose I had code in a template like this :
Template
<input name="user"><input type="button"></li>
Tried using the name attribute to user pass it along as argument for the namespace but it didn't work.
I want to know how to get values of input tag and put in the querystring —which is a namespace as "searchsomething" and it takes one parameter
urls
url(r'^searchsomething/(?P<user>\w*)/$', views.searchsomething, name='searchsomething'),
views
def searchsomething(request, user):
foundMembers =Member.objects.filter(pk=user).values()
context=RequestContext(request,{'peoplefound':foundMembers})
template= loader.get_template('social/resultsFound.html')
return HttpResponse(template.render(context))
Also, I want people to note that I don't want to do it by the usual form method.

How to pass around variables without url parameters in Django?

My question is, how could I go about passing information in django from the template to a view without url parameters. I know that sessions can help me do this however, I can't find any resources online that show how to create a key value pair in the sessions from within a template. For example, If I had a link
{{ c.class_id }}
which would lead you to a specific university class homepage, how could I pass along c.class_id to the view that is responsible for rendering this specific homepage? Would I have to put this link inside a form and then POST it to the view?
You can use GET parameters. Example:
{{ c.class_id }}
To retrieve the parameter from the Django view, use:
param_value = request.GET['param_name']

Django: Passing model object values through url

I'm having problems with passing model object values through a URL pattern. The URL:
url(r'^cities/(?P<city>\w+)/$', 'city_firm', name='city_firm'),
In the template (from the index page) I have:
{{ city }}
This is in a for loop.
The related view is:
def city_firm(request, city):
city1 = Cities.objects.get(city=city)
cityf = city1.Firms.all()
return render_to_response('cityfirm.html', {'cityf': cityf})
The two models (Cities, Firms) are in a many to many relationship.
I keep getting TemplateSyntaxError at index (NoReverseMatch while rendering: Reverse for 'city_firm' with arguments '(<Cities: >,)' and keyword arguments '{}' not found). In the template link tag I tried: {% url city_firm city=city %}, {% url city_firm city=cities.city %}. Nothing changed. The urlconf part seems right. The problem seems to be in the template. Maybe there is an issue with the string values of the object as they aren't in English. But I took several precautions to prevent this. There is maybe something wrong with the view but the error says template. Any ideas?
Solution:
Thanks everyone! Finally I figured it out. The problem was simple: I was trying to send object attribute names through the url, that had non-English characters and spaces. To fix it, I had to edit my models.
The issue is that you can't pass an object in a URL, you can only pass characters. So you need to put the part of the city object that contains the text you want to be in the URL - in your case, it appears to be an attribute also called city, which is what you use to in the lookup to get the object in the view. So it should be:
{{ city }}
I don't think name means what you think it does - remove that and read this: http://docs.djangoproject.com/en/dev/topics/http/urls/#naming-url-patterns
As far as the error... the NoReverseMatch is telling you that it's not seeing any arguments. Remember that nonexisting template variables expand to "". Make sure city is in context when you're running that code - maybe post the for in the template?