Choosing a Django dependency
I know there are many answers to this question, but I'm new to Django and I don't know how to implement these solutions. First, what do I want to do. These are my models:
class Region(models.Model):
name = models.CharField(max_length=255, verbose_name=_("Name"))
slug = models.SlugField(max_length=150, unique=True, null=True)
def save(self,*args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(Region,self).save(*args,**kwargs)
def __unicode__(self):
return u'%s' % (self.name)
class Meta:
verbose_name = _('Region')
verbose_name_plural = _('Regions')
class District(models.Model):
name = models.CharField(max_length=255, verbose_name=_("Name"))
slug = models.SlugField(max_length=150, unique=True, null=True)
region = models.ForeignKey(Region,verbose_name=_("Region"))
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
super(District, self).save(*args, **kwargs)
def is_in_region(self, region):
if self.region == region:
return True
else:
return False
def __unicode__(self):
return u'%s' % (self.name)
class Meta:
verbose_name = _("District")
verbose_name_plural = _("Districts")
On the first page I want to select one region and select the counties to show the districts of that region. These are my views:
class SearchView(ListView):
template_name = 'advert/list_view.html'
def all_json_models(self, request, region):
current_reg = Region.objects.get(slug=region)
districts = District.objects.all().filter(region=current_reg)
json_models = serializers.serialize("json", districts)
return http.HttpResponse(json_models, mimetype="application/javascript")
def get(self, request, *args, **kwargs):
return self.post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.request = request
try:
self.page = int(self.request.GET.get('page','1'))
except:
self.page = 1
self.queryset = ""
return super(SearchView, self).get(request, *args, **kwargs)
def get_queryset(self):
"""We have to bypass the queryset because
we are joining several object lists together. """
return None
def get_context_data(self, **kwargs):
context['regions'] = Region.objects.all().order_by("name")
return context
the get_context_data method is much longer, but I'm only writing a simple one here. I am using for this solution from this site http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and- jquery / . But still, the choice with the districts does not work. I am trying to write the all_json_models method for this class in views, but still this method does not call it. Is that someone who can tell me why? thanks a lot
source to share
well i have coded a whole project just for you, hope this can help :):
in this project we have countries that have many cities
as shown in the pictures, every time you select a country only related cities are displayed in next combo box :)
ok, don't see the code
(full project source code is on my github : https://github.com/nodet07/Django-Related-DropDowns )
models.py:
just 2 simple models, a country that can have many cities!
from django.db import models
class City(models.Model):
name = models.CharField(max_length=50)
country = models.ForeignKey("Country")
def __unicode__(self):
return u'%s' % (self.name)
class Country(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s' % (self.name)
views.py:
from django.shortcuts import render
from map.models import *
from django.utils import simplejson
from django.http import HttpResponse
def index(request):
countries = Country.objects.all()
print countries
return render(request, 'index.html', {'countries': countries})
def getdetails(request):
#country_name = request.POST['country_name']
country_name = request.GET['cnt']
print "ajax country_name ", country_name
result_set = []
all_cities = []
answer = str(country_name[1:-1])
selected_country = Country.objects.get(name=answer)
print "selected country name ", selected_country
all_cities = selected_country.city_set.all()
for city in all_cities:
print "city name", city.name
result_set.append({'name': city.name})
return HttpResponse(simplejson.dumps(result_set), mimetype='application/json', content_type='application/json')
index.html:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
<script>
$(document).ready(function(){
$('select#selectcountries').change(function () {
var optionSelected = $(this).find("option:selected");
var valueSelected = optionSelected.val();
var country_name = optionSelected.text();
data = {'cnt' : country_name };
ajax('/getdetails',data,function(result){
console.log(result);
$("#selectcities option").remove();
for (var i = result.length - 1; i >= 0; i--) {
$("#selectcities").append('<option>'+ result[i].name +'</option>');
};
});
});
});
</script>
</head>
<body>
<select name="selectcountries" id="selectcountries">
{% for item in countries %}
<option val="{{ item.name }}"> {{ item.name }} </option>
{% endfor %}
</select>
<select name ="selectcities" id="selectcities">
</select>
</body>
</html>
source to share
I was fed up with non-DRY solutions, so I wrote something, perhaps flexible enough for most cases:
It currently only handles flags related to online / AJAX. Ultimately I am planning (perhaps this week or next) to add an offline mode that pushes a bit of processed JS with a widget to track the onchange event of the parent and translate it to the children using a value map -> list (selection). An AJAX solution is great for things like car make / model (1000 options), while a standalone solution is great for product / color (maybe 10 seconds of choice).
source to share
You can use jQuery plugin.
Example: http://codepen.io/anon/pen/EapNPo?editors=101
Html
<select id="id_country" name="country">
<option value="" selected="selected">---------</option>
<option value="1">Colombia</option>
<option value="2">Rusia</option>
</select>
<select id="id_city" name="city">
<option value="" selected="selected">---------</option>
<option value="1" class="1">Bogotá</option>
<option value="2" class="2">Moscú</option>
<option value="3" class="2">San Petersburgo</option>
<option value="4" class="1">Valledupar</option>
</select>
Js
$("#id_city").chained("#id_country");
Create form using models (ForeignKey)
Go to https://axiacore.com/blog/django-y-selects-encadenados/ for a complete tutorial
source to share