Matheus Alves Matheus Alves - 3 days ago 5
Python Question

How to pre-select dropdown on Django?

I already tried other posts with similar problems but the code I'm dealing with was made by a third party and I'm having some small problems. I simply cannot define one of the forms with the initial value I want. How to proceed?

models.py

class Livro(models.Model):
codigo = models.AutoField(primary_key=True)
nome = models.CharField("Nome", max_length=50, unique = True)
autor = models.CharField("Autor", max_length=50, unique = True)
edicao = models.CharField("Edição", max_length=30, unique = True)
disciplina = models.ForeignKey(Disciplina)
tipo = models.CharField("Tipo", max_length=20, choices = Choices.tipo)
ano = models.CharField("Ano", max_length=30, choices = Choices.ano)
situacao = models.CharField("Situação", max_length=30, choices = Choices.situacao, blank = True, null = True)
def __unicode__(self):
return self.nome


views.py

def cadastrar_livro(request):
form = LivroForm(request.POST or None)
if form.is_valid():
salvo = form.save(commit=False)
salvo.situacao = "Ativado"
salvo.save()
return HttpResponseRedirect('/principal')
return render_to_response('cadastrar_livro.html', locals(), context_instance = RequestContext(request))


and on choices.py

class Choices(models.Model):
tipo = (
('1', 'Seriado'),
('2', 'Único'),
)

ano = (
('1', '1º'),
('2', '2º'),
('3', '3º'),
('4', 'Único'),
)

situacao = (
('Ativado', 'Ativado'),
('Desativado', 'Desativado'),
)


I just need situacao to pre select Ativado but can't find any solutions to it. Need help thanks.

Answer

Did you try to set the default argument in the situacao field.

situacao = models.CharField("Situação", max_length=30, choices=Choices.situacao, default=Choices.situacao[1], blank=True, null=True)
Comments