Gabo
Gabo

Reputation: 236

loading choices to choicefield in form in Django

im not being able to load choices in the choicefield, bellow i show you my code: I use a form like this:

class ClientesForm(forms.ModelForm):
    nombre = forms.CharField( help_text="Nombre")
    apellido = forms.CharField(help_text="Apellido")
    ci = forms.IntegerField(help_text="CI")
    estado = forms.ChoiceField(help_text="Estado")

    class Meta:
        model=Clientes
        fields = ('nombre', 'apellido', 'ci', 'estado')

a model like this:

class Clientes(models.Model):
    nombre = models.CharField(max_length=20)
    apellido = models.CharField(max_length=20)
    ci = models.IntegerField(max_length=10, unique=True, default=0)

    ESTADO = Choices('Activo', 'Inactivo', 'Deudor')
    estado = models.CharField(choices=ESTADO, default=ESTADO.Activo, max_length=20)

    def __unicode__(self):
        return self.nombre

and a view to create new clients like this:

def nuevo_cliente(request):
    if request.method == 'POST':
        form = ClientesForm(request.POST)

        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/home')
        else:
            print form.errors
    else:
        form = ClientesForm()

    return render(request, 'nuevo_cliente.html', {'form':form})

the thing is, when i create a new client from admin view i get to choose if the client is 'Activo', 'Inactivo', 'Deudor'. but when I try to create a new client from the view, the choiceField is empty, how do i load choices to the choicefield?

thanks!

Upvotes: 0

Views: 1161

Answers (1)

catavaran
catavaran

Reputation: 45575

If you define choice field in the form class then you have to provide choices argument:

class ClientesForm(forms.ModelForm):
    ...
    estado = forms.ChoiceField(help_text="Estado", choices=Clientes.ESTADO)

But why you redefine model fields in the form? It is unnecessary:

class ClientesForm(forms.ModelForm):
    class Meta:
        model=Clientes
        fields = ('nombre', 'apellido', 'ci', 'estado')

Upvotes: 1

Related Questions