【问题标题】:How to implement a form with nested fields?如何实现带有嵌套字段的表单?
【发布时间】:2019-12-02 10:47:53
【问题描述】:

有两个相关的模型

class Skill(models.Model):
    """Information about an employee's skills."""

    LEVELS = (
        ('basic', 'Basic'),
        ('intermediate', 'Intermediate'),
        ('advanced', 'Advanced'),
        ('expert', 'Expert'),
    )

    employee = models.ForeignKey(
        Employee, on_delete=models.CASCADE, related_name="employee_skills")
    technology = models.ForeignKey(Technology, on_delete=models.CASCADE)
    year = models.CharField('common year using amount ', max_length=4)
    last_year = models.CharField('Last year of technology using ', max_length=4)
    level = models.CharField("experience level", max_length=64, choices=LEVELS)

class Technology(models.Model):
    """Technologies."""

    name = models.CharField('technology name', max_length=32, unique=True)
    group = models.ForeignKey(Techgroup, on_delete=models.CASCADE, related_name="group")

关键在于,每种技术对于所有权级别、经验年限和上次使用时间都有其自身的含义。 我制作了一个允许一次编辑一种技术的表单。

forms.py

class SkillEditForm(forms.ModelForm):
    YEAR_CHOICES = [(r, r) for r in range(1, 11)]
    LAST_YEAR_CHOICES = [(r, r) for r in range(1980, datetime.datetime.now().year + 1)]
    year = forms.CharField(
        widget=forms.Select(choices=YEAR_CHOICES),
    )
    last_year = forms.CharField(widget=forms.Select(choices=LAST_YEAR_CHOICES))

    class Meta:

        model = Skill
        fields = ['technology', 'level', 'last_year', 'year']

数据库中有几十种技术。现在我想实现一次在一个窗口中编辑所有技术的能力,这样用户就不必按 10 次按钮来添加技术。

像这样的:

technology1   level last_year  year
......
......
technology_N   level last_year  year

<button>

这就是我坚持如何实现它的地方。我将不胜感激。

【问题讨论】:

  • 没有纯粹的django解决方案,你需要使用javascript。

标签: python django django-models django-forms django-templates


【解决方案1】:

要在单个视图中编辑多个模型,您必须根据这些模型渲染和处理多个 ModelForm。
在多个模型实例上创建/更新操作的常见解决方案是 django's formsets
我建议您使用inline formsetsinlineformset_factory,因为它确实让事情变得更容易。
不要忘记在模板中包含management form,因为这会在处理表单集时造成很多麻烦。

如果您不想编写太多 JavaScript,那么在前端,django-dynamic-formset 之类的东西就可以完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多