add a get variable django - django

I have a (what I think) is a pretty basic question about appending a get variable to url in django.
I have a filter sidebar on the page which creates a list of available classes based on the selection the user makes in the sidebar. For example, user may click on Aquatics class as a filter(other filters include things like location,price, time of day,etc) it will produce a list of aquatics classes available. Obviously, you can revise the search by choosing a specific location and now it should show a list of aquatics classes in that location.
what I would like is to make it so that every time use makes a choice, it adds a get variable to url like so: example.com/search?category=1&location=3. I'm not sure how I should go about it in the template. I know I need to get the list of variables by doing something like this
{% for k, v in request.GET.iteritems %}
{{ k }}={{ v }}&
{% endfor %}
But I dont really know what to do next... Could someone point me in the right direction?

You need to use this. request.GET.urlencode
That code automatically encode your GET parameter into URL friendly.

Related

In Django, is there a better alternative to using "include" 100+ times in the same document?

I made a Django site that lets users search a database and then display results. Each result is an article and for each article you see the title, author, publication date, etc. This information for each result appears in a box I created with CSS to make the result look nice. Since I may alter the look of the box in the future, I want to use it as a template and then "include" it in my results page. But because there could be over 100 results and each result will display the box, I would need to "include" the box over 100 times with code like the following:
{% for article in article_results %}
{% include 'result_box.html' %}
{% endfor %}
Is this ok? Is there a better way to do this?
Yes. See this documentation:
https://docs.djangoproject.com/en/1.11/ref/templates/builtins/#cycle
You can loop through each element passed into your template and generate some HTML depending on it's characteristics.

simple application pass value from django views to javascript

It has been 2day i am trying to figure out how to do that. I am a novice so please give as detailed explanation as possible.
I am doing this in my views.py
dict1 = simplejson.dumps(dict1)
return render_to_response('main_page.html', {
'js_testsuite':testsuite_dict,
'js_testset':js_testset,
'dict1':dict1})
In main_page.html
{% if js_testsuite %}
<select id="testsuites" name="testsuite" onchange="setOptions(document.selection.testsuite.selectedIndex);">
{% for key, value in js_testsuite.items %}
<option value={{ value }} name="testsuite">{{ key }}</option>
{% endfor %}
</select>
{% endif %}
In setoptions.js, which contains the function setOptions(value), to which i am passing selected index of the select box, and using this value i have to set the second select box and the data for this select box has to come from the views.py given above.
Also, I tried doing
var value_from_django = {{ dict1 }};
what are the other things im missing. Could you please provide a detailed explanation on this. I had been trying this for 2 days.
Is there a way in which I can pass the value from django views to the javascript directly bypassing the django template?
Can I pass the information from django views to the html template and then to the javascript?
The javascript I am referring to is a simple javascript not jquery.
Thanks for your support,
Vinay
You cannot pass values to javascript bypassing the template, unless you use an ajax call to start a separate request or unless you do something very unusual like embedding the data in a response header (don't actually do this, it is not what response headers are for!). The response, which includes the header and the body (the body being the part generated by the template) is the sum total of the information your application provides to your client, so unless you generate an additional request and fetch an additional response with ajax, you have no other options.
If you don't want to do that, then your options for passing information to the javascript via the template are basically the following:
Using an inline tag, create properly formatted javascript dynamically via the templating system. The example line you have, var value_from_django = {{ dict1 }}; is essentially what I'm talking about here, except that I'm not sure you can pass a dict through from django to javascript like that, because django's text output of a dict in the template is unlikely to be exactly the correct formatting for a javascript variable declaration. So, instead you can...
Translate your data into JSON and put that into your template, and then process that with the javascript. (This is usually done with an ajax call, but there's nothing stopping you from injecting the JSON data into the initial template directly.)
Or populate your HTML with the data you want and then use javascript to locate the HTML tag containing the data and parse the data out.
If you are trying to pass simple variables like integers, it might be easiest to do it with the first or third options. If you are trying to pass a more complex data structure like a dictionary, you will probably be better off using JSON (that's what it's for!)
I would like to give you more detailed and concrete instructions, but for that you will need to post more detail about what exactly is going wrong with your current approach and what your desired functionality is.
By the way: if it is at all feasible to include jquery on this page and use that instead of trying to use basic javascript, you should do so. It will make your life much, much easier.

Django template system - getting fields from template

Is there a function that returns a list of fields that are expected in template? For example, I have the following template:
hello i am {{ name }}. {% for i in docs %} i have doc {{ i }}
Written in file. And i want to get a dict which contains:
{'name': 'str', 'docs': 'list'}
Is there something like that or i have to write it by myself?
As far as i know, NO....
Your template contains some html and some place holders (and may be something else). What render_to_template doing is, it gets a context dictionary which contain some keys and some data attached to that keys and a template. Then it places the values to those place holders according to their key names, execute some loops or condition checks if your template contains control flows like {% if...%} or {%for....%}
If TEMPLATE_DEBUG is closed in your settings, and if there is a place holder with no matching key in your context dictionary, then it will skip that without raising any error.
Also, if you pass a form object to your template and place your object directly to template as it is (without calling each field separately) [ex: {{form}} or {{form.as_p}} then django will check for fields on the form and palce them as it is shown here. In a such situation, you will only know that form is used. You have to check which fields are used from your Form definition.
If you look through that process, you must know what you need to place your context dictionary. You may write a parser to parse your template but it is far more difficult than just examining the template and find missing data, i guess.
The builtin {% debug %} tag may be helpful for you, however I don't know if I fully understand what you are asking. Basically, if you put the debug tag in your template it will print a lot of useful stuff, including all the variables available in your template.
Perhaps you could take a look at the source code for the debug tag (because they have access to all the variables there), and build a custom tag tag based off of this. Taking a glance at the source, this seems like it would be really simple to do.

Putting links in list_detail.object_list to list_detail.object_detail

I've started using Django and am going right to generic views. Great architecture! Well, the documents are great, but for the absolute beginner it is a bit like unix docs, where they make the most sense when you already know what you're doing. I've looked about and cannot find this specifically, which is, how do you set up an object_list template so that you can click on an entry in the rendered screen and get the object_detail?
The following is working. The reason I'm asking is to see if I am taking a reasonable route or is there some better, more Djangoish way to do this?
I've got a model which has a unicode defined so that I can identify my database entries in a human readable form. I want to click on a link in the object_list generated page to get to the object_detail page. I understand that a good way to do this is to create a system where the url for the detail looks like http://www.example.com/xxx/5/ which would call up the detail page for row 5 in the database. So, I just came up with the following, and my question is am I on the right track?
I made a template page for the list view that contains the following:
<ul>
{% for aninpatient in object_list %}
<li><a href='/inpatient-detail/{{ aninpatient.id }}/'>{{ aninpatient }}</a></li>
{% endfor %}
</ul>
Here, object_list comes from the list_detail.object_list generic view. The for loop steps through the object list object_list. In each line I create an anchor in html that references the desired href, "/inpatient-detail/nn/", where nn is the id field of each of the rows in the database table. The displayed link is the unicode string which is therefore a clickable link. I've set up templates and this works just fine.
So, am I going in the right direction? It looks like it will be straightforward to extend this to be able to put edit and delete links in the template as well.
Is there a generic view that takes advantage of the model to create the detail page? I used ModelForm helper from django.forms to make the form object, which was great for creating the input form (with automatic validation! wow that was cool!), so is there something like that for creating the detail view page?
Steve
If you're on django < 1.3 then what you are doing is basically perfect. Those generic views are quite good for quickly creating pages. If you're on django 1.3 you'll want to use the class based generic views. Once you get a handle on those they are are crazy good.
Only note I have is that you should use {% url %} tags in your templates instead of hardcoding urls. In your urls.conf file(s) define named urls like:
url('inpatient-detail/(?P<inpatient_id>\d+)/$', 'your_view', name='inpatient_detail')
and in your template (for django < 1.3):
...
In 1.3 a new url tag is available that improves life even more.

Django - Pre render signal?

I have a 'live settings' app which I use to store certain global site settings. Certain pages of my site reference these settings, although generally they only use 2-3 at a time. I access these settings using a custom template tag like so:
{% settings site_name %}
Each time I use this tag, the model will retrieve the setting from the database, so if I had something like:
{% settings site_name %} {% settings num_articles %}
the database would get queried twice.
What I'd like to do is not hit the database more than once per page for the settings values, if I could get all the settings used on a page and then hit the database to retrieve them all, that would be much better.
I had a look through the documentation and it seems Django has no pre render signal which I could use to update any references to the settings, so does anyone have any suggestions how I could optimise this system? And yes obviously caching is the obvious answer but I'd still like to improve on this for when the page isn't cached.
Agreeing with Daniel that process_template_response is the hook you're looking for. I don't know how many settings you have, but it could also make sense to retrieve all settings once, and store them in some dictionary like structure, so you can access them anytime without hitting the database. You could retrieve them once either per request, or - even if your settings do barely change - when django initializes. You could additionally use django's signals to update your cached settings on delete or update.
If you have a look at django-dbsettings you will see it does a similar thing!
Django 1.3 includes the new TemplateResponse class, which allows you to modify the response later in the rendering process - eg in middleware. This looks like it might do what you want.
If you wish to stick to a scheme similar to what you already have, I'd implement a filter that takes in a list of keys and returns a dict with all the relevant values.
Example filter:
def get_settings(key_list):
# take values from conf.settings. In practice, can be from any source
return dict((k, getattr(settings, k, None)) for k in key_list.split(","))
register.filter("get_settings", get_settings)
Usage:
{# load multiple values with a single call #}
{% with "KEY1,KEY2"|get_settings as settings %}
setting values {{ settings.KEY1 }} and {{ settings.KEY2 }}
{% endwith %}
Note that I used a filter instead of a tag because the with builtin expects a single value before as.