djangodjango-modelsdjango-formschoicefield

How to use a choiceField declared in the model, in a form. django


I have this in my model.py

class marca(models.Model):
    marcas = (
        ('chevrolet', 'Chevrolet'),
        ('mazda', 'Mazda'),
        ('nissan', 'Nissan'),
        ('toyota', 'Toyota'),
        ('mitsubishi', 'Mitsubishi'),
    )

    marca = models.CharField(max_length=2, choices= marcas)
    def __unicode__(self):
        return self.marca

And I need to use it in my form.py I tried this but it doesn't work.

class addVehiculoForm(forms.Form):
    placa                   = forms.CharField(widget = forms.TextInput())
    tipo                    = forms.CharField(max_length=2, widget=forms.Select(choices= tipos_vehiculo))
    marca                   = forms.CharField(max_length=2, widget=forms.Select(choices= marcas))

Solution

  • Move your choices to be above the model, in the root of your models.py:

    marcas = (
            ('chevrolet', 'Chevrolet'),
            ('mazda', 'Mazda'),
            ('nissan', 'Nissan'),
            ('toyota', 'Toyota'),
            ('mitsubishi', 'Mitsubishi'),)
    
    class Marca(models.Model):
    
        marca = models.CharField(max_length=25,choices=marcas)
    

    Then in your file where you declare the form:

    from yourapp.models import marcas
    
    class VehiculoForm(forms.Form):
    
         marca = forms.ChoiceField(choices=marcas)
    

    I also fixed some other problems for you:

    If you are just creating a form to save records for Marca model, use a ModelForm, like this:

    from yourapp.models import Marca
    
    class VehiculoForm(forms.ModelForm):
         class Meta:
             model = Marca
    

    Now, django will render the choice field automatically.