在Django中将选项加载到选择字段中

时间:2023-01-14 19:36:20

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?

问题是,当我从管理员视图创建一个新客户端时,我可以选择客户端是“Activo”,“Inactivo”,“Deudor”。但是当我尝试从视图创建一个新客户端时,choiceField为空,我如何将选择加载到选择域?

thanks!

谢谢!

1 个解决方案

#1


1  

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

如果在表单类中定义选择字段,则必须提供choices参数:

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')

#1


1  

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

如果在表单类中定义选择字段,则必须提供choices参数:

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')