如何在Django中具有两个ForeignKey字段的ModelForm中保存模型 [英] How to save a model in ModelForm with two ForeignKey fields in Django

查看:45
本文介绍了如何在Django中具有两个ForeignKey字段的ModelForm中保存模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个链接到Estados的模型Listaflor和另一个名为Flora2Estado的模型,我使用ModelMultipleChoiceField制作了一个表单.它可以成功保存到Listaflor中,但是什么也没有保存到Flora2Estado中,我该怎么办?

There is a model Listaflor linked to Estados with another model named Flora2Estado, i made a form with ModelMultipleChoiceField. It saves successfully into Listaflor but nothing into the Flora2Estado, what can i do about this?

forms.py

class FloForm(forms.ModelForm):
    familia = forms.ModelChoiceField(queryset=Familia.objects.all().order_by('familia_nome').filter(aprovado=1))
    Especie = forms.CharField(label="Nome da espécie*")
    estados = forms.ModelMultipleChoiceField(queryset=EstadosM.objects.all().order_by('nome_abbr'))
    class Meta:
        model = Listaflor
        ordering = ["estados",]
        fields = ['Especie','estados']

views.py

def CreateFlo(request):
    form = FloForm()
    if request.method == 'POST':
        form = FloForm(request.POST)
        if form.is_valid():
            Listaflor = form.save(commit=False)
            Flora2Estado = form.save(commit=False)
            Listaflor.save()
            Flora2Estado.save()
  
    return render(request,'accounts/enviar_flora.html')

models.py

models.py

class Flora2Estado(models.Model):
    estado = models.ForeignKey(EstadosM, models.CASCADE)
    especie = models.ForeignKey(Listaflor, models.CASCADE)
    flora2estado = models.AutoField(primary_key=True)
    class Meta:
        managed = False
        db_table = 'flora2estado'
        unique_together = (('estado', 'especie'),)

欢迎您提供任何帮助我撰写更好的帖子的提示,祝您生活愉快!

Any tips on helping me making a better post is welcome, have a good day!

View.py已更新:返回验证错误!

View.py updated: returning Validation error!

def CreateFlo(request):    
    EstadosInlineFormSet  = inlineformset_factory(Listaflor, Flora2Estado, form=Flo2Form)
    Form = FloForm(request.POST)
    storeForm = FloForm(request.POST)
    if Form.is_valid():
        new_store = storeForm.save()
        florInlineFormSet = EstadosInlineFormSet(request.POST or None, request.FILES or None, instance=new_store)

        if florInlineFormSet.is_valid():
            florInlineFormSet.save()
    context = {'form': Form}
    return render(request,'accounts/enviar_flora.html', context)

models.py:

models.py:

class Flora2Estado(models.Model):
    estado = models.ForeignKey(EstadosM, models.CASCADE)
    especie = models.ForeignKey(Listaflor, models.CASCADE)
    flora2estado = models.AutoField(primary_key=True)
    class Meta:
        managed = False
        db_table = 'flora2estado'
        unique_together = (('estado', 'especie'),)
class Listaflor(models.Model):
    especie_id = models.AutoField(primary_key=True)
    familia = models.ForeignKey(Familia, models.DO_NOTHING, db_column='familia_id', blank=True, null=True)
    Especie = models.CharField(db_column='especie', max_length=255, blank=True, null=True) 

我尝试过:

def CreateFlo(request):
    form = FloForm()
    if request.method == 'POST':
        form = FloForm(request.POST)
        if form.is_valid():
            listafor = form.save()
            estados = form.cleaned_data.get('estados')
            for estado in estados:
                Flora2Estado.objects.create(especie=listafor, estado= estado)
    texto="..."
    context = {'floForm': form,'texto': texto}
    return render(request, 'accounts/enviar_flora.html', context)

得到错误:

django.db.utils.IntegrityError:(1062,键"PRIMARY"")

django.db.utils.IntegrityError: (1062, "Duplicate entry '18-3256' for key 'PRIMARY'")

推荐答案

您可以尝试从表单的 cleaned_data 中提取 estados ,如下所示:

You can try to extract out the estados from form's cleaned_data, like this:

def CreateFlo(request):
    form = FloForm()
    if request.method == 'POST':
        form = FloForm(request.POST)
        if form.is_valid():
            listafor = form.save()
            estados = form.cleaned_data.get('estados')
            for estado in estados:
                Flora2Estado.objects.create(especie=listafor, estado= estado)
            # or you can use bulk_create: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#bulk-create
  
    return render(request,'accounts/enviar_flora.html')

更新

很难确定您要从哪个模型得到错误,但是我的假设是Listaflor模型.您可能有一个主键字段,其默认值为"18-XXXX".使用FloForm创建Listaflor实例时,您没有提供任何主键值,因此它将默认值用作主键,从而引发Integrity错误.要解决此问题,您可以使用动态函数生成主键的值,也可以使用

Update

It is really hard to tell for which model you are getting the error, but my assumption is Listaflor model. It is a possibility that you have a primary key field in which default value is "18-XXXX". When you are creating Listaflor instance using the FloForm, you are not providing any primary key value, so it is taking the default value as primary key, hence throwing Integrity error. To solve this you can either use a dynamic function to generate the value of primary key or use UUIDField/AutoField to generate primary key automatically.

这篇关于如何在Django中具有两个ForeignKey字段的ModelForm中保存模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆