How do I create a filtered Dropdown Choice field in Django using ajax? - django

I am trying to create a dynamic filtered drop down choice fields,i gone through below blog but it confusing,can any one suggest easy way to do this in django.
I'm trying to create a dynamically filtered dropdown Choice field in Django. I've tried the steps outlined here, but I don't understand it.
How do I create a filtered Dropdown Choice field in Django using ajax?

You can use dajaxproject (django+ajax). Example: http://www.dajaxproject.com/forms/ It's so easy.

Maybe you mean something like this?
http://code.google.com/p/django-ajax-selects/
I have this implemented in a couple of projects, and it's working well. If you are looking for a kind of search form for foreign keys, have a look at an app I started some weeks ago:
https://github.com/schneck/django-foreignkeysearch

I only had a small array of drop down choices I needed to display, so I chose to be lazy and not to go the Ajax route but rather used the initial example provided in the blog (his prototype). This will slow down rendering the page if you have many drop-down choices, which I do not have.
The way it worked for me was that I replaced the array:
modelstxt[1] = "1\tEscort\n2\tTaurus";
modelstxt[2] = "1\tAltima\n2\tMaxima";
With template tags that will create the same array while building the page (note I use locations and areas, not models and makes):
areastxt[0] = "0\t--";
{% for location in locations %}
areastxt[{{location.id}}] = "0\t--
{% for area in areas %}
{% if area.location_id == location.id %}
\n{{area.id}}\t{{area.name}}
{% endif %}
{% endfor %}";
{% endfor %}
Disclaimer: I am noob'ish, so I may be committing a noob faux-pas using this approach.

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.

How to get the value of an individual radio button in a Django template?

Is there a way for a template to examine the value of an individual radio button?
I know how to get other attributes:
{% for button in myform.radio_select %}
{{button.tag}}
{{button.choice_label}}
{{button.id_for_label}}
{% endfor %}
But how do I get the value? I tried the obvious {{button.value}} and the less obvious {{button.tag.value}} but they did not work.
The answer to this question says that as of Django 1.11, the value is stored in {{button.data.value}}.
Previous versions of Django used {{button.choice_value}}.

Using the Django assignment_tag built-in tag the right way

I'm working on a project in Django.
Earlier today, I discovered the new (Django >= 1.4) assignment_tag. I immediately decided that it was just what I needed EVERYWHERE and threw some logic into one that executed a very simple query against the database and returned the resulting queryset. The function I wrapped takes an argument that allows the invoking context to specify how many results to grab, directly in the template when I am using the template tag.
It is quite convenient - I don't have to update my view when I decide this list should have 5 items, not 3 - but it seems like one of those gray areas where we aren't supposed to tread (i.e. pushing application logic into templates) when writing good, maintainable Django code.
Now, a couple of hours separated from writing the code, I'm wondering if I should scrap the assignment_tag entirely.
Code:
models.py:
class SomeObject(models.Model):
is_active = models.BooleanField(default=False)
(...)
templatetags/myapp_tags.py:
from django import template
from myapp.models import SomeObject
register = template.Library()
#register.assignment_tag
def get_someobjects_list(max_results=0):
queryset = SomeObject.objects.filter(is_active=True)
if max_results == 0:
return queryset
elif max_results > 0:
return queryset[:min(max_results, queryset.count())]
else:
return None
templates/myapp/chunks/someobject_list.html:
{% load myapp_tags %}
{% get_someobjects_list as someobjects_list %}
# or {% get_some_objects_list 5 as someobjects_list %} ... flexible!
{% if someobjects_list %}
<ul>
{% for someobject in someobjects_list %}
<li>
<a href="{{ someobject.get_absolute_url }}">
{{ someobject.name }}
</a>
</li>
{% endfor %}
</ul>
{% else %}
<span>No someobjects exist</span>
{% endif %}
I was really excited to discover these existed - it's convenient for me in this particular case. Now that my excitement over finding a new feature has passed, it seems pretty clear that I'm misusing it. The example given in the Django docs seems like a better application of this - grabbing the string representation of current datetime, something that doesn't require a DB query. My worry is that I'm setting myself up for heartache if I start using this pattern regularly. Following the slippery slope all the way down: I'll end up not even bothering to pass a context to my templates and ALL my DB queries will be hidden away in template tags where nobody would think to look for them.
It seems the code would be cleaner if I just threw out this whole "great idea" I had when I discovered assignment_tags and created a custom model manager instead.
Are there other clean ways of accomplishing this that I am missing? Are manager methods the consensus best way among Django developers?
assignment template tags are especially helpful if you need to get some information into the template context for a few pages of a website, but don't want to (or can't) put the info into every view on the website, and don't want to or can't rely on a context processor.
they basically guarantee that your information will be available in the template.

Infinite scroll in django

Is it possible to implement facebook style loading of content while scrolling down? I would like to implement it in an ecommerce site. There are a lot of items in each category and the category page becomes too long. I could implement page numbers but my client wants me to implement that facebook type of loading. Is there anything I can use? Rest of the site has already been built.
I did look into django-endless-pagination but was not able to get it to work. Is there any demo of it so that I can look into it?
We used django endless pagination on www.mymommemories.com without too much problem. Because we were using html5media we did have to add a line to run that function with a one second delay. (setTimeOut("html5media()", 1000). Running it without the delay caused problems in some browsers. If your not using html5media, this should not be a concern however.
Core part of the template code.
{% load endless %}
{% paginate memories %}
{% for memory in memories %}
.
.
.
{% endfor %}
{% show_more %}
In the view we have the following to handle the ajax request.
if request.is_ajax():
template = page_template
return render_to_response(template,context,context_instance=RequestContext(request))
The page_template is not the whole page, just the portion related to the "paging".
I thinks the easiest way to do endless pagination is use jQuery (use $.loads).
You even don't need change the back-end code.
http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Perhaps take a look at that?

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.