Matheus Alves
Matheus Alves

Reputation: 5

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.

Upvotes: 0

Views: 726

Answers (2)

mirek
mirek

Reputation: 1350

Dynamically you can set .initial = in Form's __init__:

class FormChooseRegulation(forms.Form):
    regulation = forms.ChoiceField(required=True, label=_('Regulation'))

    def __init__(self, *args, **kwargs):
        regulations = kwargs.pop('regulations', ())
        regulation_last = kwargs.pop('regulation_last', None)
        super().__init__(*args, **kwargs)
        self.fields['regulation'].choices = regulations
        if regulation_last:
            self.fields['regulation'].initial = regulation_last

called in view:

def regulation_selection(request):
    regulations = list(Regulation.objects.values_list('id', 'label'))
    form_regulation = FormChooseRegulation(
                regulations=regulations,
                regulation_last=request.session.get('regulation_id')
            )

Upvotes: 0

Rag Sagar
Rag Sagar

Reputation: 2374

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[0][1], blank=True, null=True)

Upvotes: 1

Related Questions