【问题标题】:Creating a Dynamic Form in Django在 Django 中创建动态表单
【发布时间】:2021-06-03 16:00:31
【问题描述】:

我目前正在开展一个项目,该项目将拥有一个关于诈骗报告的数据库。在网站的报告部分,我有一个表格,但我希望任何人都能够通过单击按钮添加多个配置文件。例如:

Nickname field: xyz
Steam profile: x
[ + ] <- button for adding more profiles, which when pressed would look something like this:
Nickname field: xyz
Steam profile: x
Steam profile 2: y [ Delete ]
[ + ]

我正在研究 FormSets 和 Inline Formsets,但没有找到符合此特定需求的内容,也没有回答有关存储表单结果的问题。
我将如何为此创建表单?
如何将Steam profile 的多个结果存储到具有steam_profile = models.CharField 的对象中?
我目前的模型:

class Scammer(models.Model):
    #Basic information for display
    steam_id_64 = models.CharField(max_length=17, default='00000000000000000')
    nickname = models.CharField(max_length=64, default='Nickname')
    steam_profile = models.CharField(max_length=512, default='https://www.steamcommunity.com')
    description = models.TextField(default='')
    proof = models.TextField(default='')

    #Date created var for ordering
    date_created = models.DateTimeField(default=timezone.now, blank=True)

    def __str__(self):
        return self.nickname

    def get_absolute_url(self):
        return reverse('dashboard-home')

我的看法:

class ScammerCreateView(CreateView):
    model = Scammer_Unapproved
    template_name='dashboard/report.html'
    fields = ['nickname', 'steam_id_64', 'steam_profile', 'description', 'proof']

我的模板:

{% block content %}
    <div class="report-scammer">
        <form method="POST">
            {% csrf_token %}
            <fieldset>
                <legend>Report a scammer</legend>
                {{ form|crispy }}
            </fieldset>
            <div>
                <button type="submit">Report</button>
            </div>
        </form>
    </div>
{% endblock content %}

【问题讨论】:

    标签: python django forms model


    【解决方案1】:

    将配置文件作为内置 Django 用户模型 或维护一个单独的模型,其中包含指向内置用户模型的链接。现在,诈骗报告表单可以选择使用 ManytoMany 关系字段链接到多个用户帐户。检查下面的官方文档页面,

    [https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/][1]

    【讨论】:

      猜你喜欢
      • 2016-11-11
      • 2012-05-21
      • 2019-05-05
      • 2018-11-17
      • 2011-01-15
      • 2021-03-10
      • 1970-01-01
      • 2021-09-02
      • 1970-01-01
      相关资源
      最近更新 更多