Kari dime
Kari dime

Reputation: 78

How to make a ModelForm with many to many relationship in Django?

I'm making a form that needs to send multiple "estados", and I need it to be able to send one or even 5 items at once.

I have 3 tables connected by "estados" with an intermediary "flora2estado" table: models.py:

class Listaflor(models.Model):
    especie_id = models.AutoField(primary_key=True)
    estados = models.ManyToManyField(Estados, through='Flora2Estado')

class Flora2Estado(models.Model):
    estado = models.ForeignKey(Estados, models.DO_NOTHING, primary_key=True)
    especie = models.ForeignKey('Listaflor', models.DO_NOTHING)

Class Estados(models.Model):
    estado_id = models.AutoField(primary_key=True)
    estado_nome = models.CharField(max_length=100, blank=True, null=True)

views.py

def CreateFlo(request):
    form = FloForm()
    if request.method == 'POST':
        form = Flo(request.POST)
        if form.is_valid():
            Listaflor = form.save(commit=False)
            Listaflor.aprovado_id = 2
            Listaflor.save()
    context = {'form': form}
    return render(request,'accounts/flora_form.html', context)

forms.py:

class FloForm(forms.ModelForm): 
       class Meta:
        model = Listaflor
        fields = ['Especie','familia','estados' ]
        exclude = ["aprovado"]

Upvotes: 2

Views: 1966

Answers (1)

Allen Shaw
Allen Shaw

Reputation: 1492

I guess you need ModelMultipleChoiceField. Please refer to https://stackoverflow.com/questions/2216974/django-modelform-for-many-to-many-fields here

Upvotes: 2

Related Questions