Skip to content

Instantly share code, notes, and snippets.

@taizarm
Last active Aug 29, 2015
Embed
What would you like to do?
class PessoaAdminForm(forms.ModelForm):
class Meta:
model = Pessoa
def __init__(self, *args, **kwargs):
super(PessoaAdminForm, self).__init__(*args, **kwargs)
self.fields['city'].choices = [('', '---------')]
if kwargs.has_key('instance'):
if kwargs['instance'].state:
if kwargs['instance'].state.id != 0 and kwargs['instance'].state.id != None: #se o estado estiver selecionado(em caso de edição) já faz o filtro inicial nos municipios
cidades = City.objects.filter(id_state=kwargs['instance'].state.id)
self.fields['city'].choices += ((c.pk, u''+c.title+'') for c in cidades)
class Media:
js = ('/static/meusite/jquery-1.8.2.min.js','/static/meusite/js/cidades_estados.js', )
def clean(self):
cleaned_data = super(PessoaAdminForm, self).clean()
state = cleaned_data.get('state')
city = cleaned_data.get('city')
if state:
cidades = City.objects.filter(id_state=state.pk)
self.fields['city'].choices = [('', '---------')]
self.fields['city'].choices += ((c.pk, u''+c.title+'') for c in cidades)
return cleaned_data
class PessoaAdmin(admin.ModelAdmin):
form = PessoaAdminForm
to_encoding = 'utf-8'
def get_urls(self, *args, **kwargs):
urls = super(PessoaAdmin, self).get_urls(*args, **kwargs)
myurls = patterns('',
(r'^get_cidades/(?P<id_estado>(\d+)?)/$', get_cidades, {}, 'get_cidades'),
)
return myurls + urls
$(document).ready(function(){
$("#id_state").change(function(){
carrega_cidades(0);
});
function carrega_cidades(id_selected) {
var arr;
$.get('/get_cidades/'+$("#id_state").val()+'/', function(data,status)
{
$('#id_city option').remove();
for (i in data) {
var obj = data[i];
if (id_selected == obj.id)
$("#id_city").append($('<option>').attr('value', obj.id).attr('text', obj.title).attr('selected', true).html(obj.title));
else
$("#id_city").append($('<option>').attr('value', obj.id).attr('text', obj.title).html(obj.title));
}
});
}
});
class MeuForm(forms.Form):
nome = forms.CharField(label='* Nome', max_length=255, required=True,)
state = forms.ModelChoiceField(queryset=State.objects.all(), label='Estado',)
city = forms.ModelChoiceField(queryset=City.objects.all(), label="Cidade",)
def __init__(self, *args, **kwargs):
super(MeuForm, self).__init__(*args, **kwargs)
self.fields['city'].choices = [('', '---------')]
class City(models.Model):
id = models.IntegerField(primary_key=True)
id_state = models.ForeignKey('State', db_column='id_state')
title = models.CharField(max_length=50)
iso = models.IntegerField()
iso_ddd = models.CharField(max_length=6)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=1)
def __unicode__(self):
return "%s" % self.title
class Meta:
managed = False
db_table = 'city'
class State(models.Model):
id = models.IntegerField(primary_key=True)
id_country = models.ForeignKey(Country, db_column='id_country')
id_region = models.IntegerField()
title = models.CharField(max_length=35)
letter = models.CharField(max_length=2)
iso = models.IntegerField()
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
status = models.CharField(max_length=1)
def __unicode__(self):
return "%s" % self.letter
class Meta:
managed = False
db_table = 'state'
urlpatterns = patterns('meusite.views',
url(r'^get_cidades/(?P<id_estado>(\d+)?)/$', views.get_cidades, name='get_cidades'),
)
def get_cidades(request, id_estado):
if id_estado:
cidades = City.objects.filter(id_state=id_estado)
else:
cidades = []
response_data = [{'id': '', 'title': '---------'}]
for c in cidades:
response_data.append({'id': c.id, 'title': c.title})
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
@luzfcb

This comment has been minimized.

Copy link

@luzfcb luzfcb commented Jul 20, 2015

apartir do Django 1.8 você pode usar JsonResponse(dicionario) do modulo django.http

o pré de usar a implementação do JsonResponse e não json.dumps, é que o JsonResponse já faz o encode de Date/Time e decimal de forma correta.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment