【问题标题】:dynamically add instances of a model in Django forms在 Django 表单中动态添加模型的实例
【发布时间】:2017-11-21 22:47:47
【问题描述】:

我有以下型号:

from django.db import models
from django.contrib.auth import get_user_model

User = get_user_model()


class CalEvents(models.Model):

    user = models.ForeignKey(User)
    activity = models.CharField(max_length=256, unique=False, blank=True)
    activity_type = models.CharField(max_length=30, unique=False, blank=True)
    activity_code = models.CharField(max_length=30, unique=False, blank=True)

    def __str__(self):
        return "Activity, type and code for the calendar events of @{}".format(self.user.username)

我想知道的是如何使用表单动态添加该模型的实例。我在想像第一个实例有一个表单(带有“activity”、“activity_type”和“activity_code”字段)然后,如果用户单击“加号”(或其他),(s)他可以向数据库添加第二个、第三个...第 N 个实例。

【问题讨论】:

  • 在表单集中动态添加extra 之类的?

标签: django forms model


【解决方案1】:

您可以使用 Django 的内联表单集来实现此功能。

https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#inline-formsets

它将允许您声明一个可动态用于添加模型的多个实例的表单。

【讨论】:

  • 哦,太完美了!谢谢!
猜你喜欢
  • 2016-09-03
  • 2020-03-18
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 2018-09-21
相关资源
最近更新 更多