I know that there is a lot of answers on this question, but i am new in Django and i dont know how to implement these solutions. First what i want to do. This is 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")
In frontend page I want to choose one region and select with districts will show districts of this region. This 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 write here only simple one. I use for this solution from this website http://www.devinterface.com/blog/en/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/ . But still select with districts is not working. I try to write method all_json_models to this class in views but still its not calling this method. Is here any one who can tell me why? Thx a lot