【问题标题】:Django: How to add ManyToMany Value in form from other ModelDjango:如何从其他模型中添加多对多值
【发布时间】:2020-07-28 07:58:33
【问题描述】:

所以我有 2 个模型。 成分和配方。 我想添加一个带有弹出窗口的加号按钮,它将在此页面上打开一个模式,这将让我创建一个成分。 我不希望用户必须先创建成分然后再创建食谱。

我的模特:

class Recipe(models.Model):
    name = models.CharField(max_length=100, blank=False)
    ingredient = models.ManyToManyField('Ingredient',)
    for_persons = models.IntegerField(null=False)
    instruction = models.TextField(blank=True)

    def get_absolute_url(self):
        return reverse('Rezept-Detail', kwargs={'pk': self.pk}) 

class Ingredient(models.Model):
    name = models.CharField(max_length=100, blank=False)
    quantity = models.IntegerField(null=False, blank=False)
    UNIT_CHOICES = (
        ("ML", "Milliliter"),
        ("L", "Liter"),
        ("KG", "Kilogramm"),
        ("PCK", "Packung"),
        ("P", "Portion"),
    )
    unit = models.CharField(
        max_length=20,
        choices=UNIT_CHOICES
    )

    def __str__(self):
        return self.name

我的表格:

class RecipeForm(forms.ModelForm):
    class Meta:
        model = models.Recipe
        fields = ['name', 'ingredient', 'for_persons', 'instruction']

有人知道,如何解决这个问题?

【问题讨论】:

    标签: python django django-models django-forms many-to-many


    【解决方案1】:

    在调用成分添加视图的表单操作中添加一个按钮,如下所示,我建议使用表单助手。在 FormActions 中,您可以更新带有模式的弹出窗口。 您可以使用此链接 (https://django-crispy-forms.readthedocs.io/en/latest/form_helper.html) 来查看表单助手

    class RecipeForm(forms.ModelForm):
    
        def __init__(self, user, *args, **kwargs):
            super(RecipeForm, self).__init__(*args, **kwargs)
    
            self.helper = FormHelper()
            self.helper.form_show_labels = True
            self.helper.layout = Layout(
    
               //some code for the fields goes here
    
                FormActions(
                    Submit('save', _('Save')),
                    HTML(
                        '<a href="link for the add ingredient" >' + _('New Ingredient ') + '</a>'),
    
                )
            )
        class Meta:
            model = models.Recipe
            fields = ['name', 'ingredient', 'for_persons', 'instruction']
    

    【讨论】:

    • 你能解释一下,用户来自哪里,你对这些字段的代码是什么意思?从未使用过 Crispy 表单...
    • 如果有会话,可以忽略我添加的用户。您只需要使用表单助手,就可以编写 html,让您编写一个锚点来打开模式。
    • 好的,试试这个:) THX
    猜你喜欢
    • 1970-01-01
    • 2017-01-10
    • 2021-08-25
    • 2019-09-05
    • 2023-03-19
    • 2012-03-26
    • 1970-01-01
    • 2019-04-20
    • 2020-08-01
    相关资源
    最近更新 更多