【问题标题】:Django form - How to autofill field from anotherDjango表单 - 如何从另一个自动填充字段
【发布时间】:2021-12-31 15:30:45
【问题描述】:

我想通过在name field 中提取其值来自动填充我的Kpi fieldd 例如:这里kpi = name.split("-")[6] 等于CPC 字符串。请问我该怎么做?

class UserCampaigns(models.Model):
    dsp_choices =(
        ('Amazon', 'Amazon'),
        ('Amobee', 'Amobee'),
        ('AppNexus', 'AppNexus'),
        ('Digiteka', 'Digiteka'),
        ('DV 360', 'DV 360'),
    )
    kpi_choices = (
        ('CPA', 'CPA'), ('CPC', 'CPC'),
        ('CPD', 'CPD'), ('CPL', 'CPL'),
        ('CPM', 'CPM'), ('CPV', 'CPV'),
        ('CTR', 'CTR'), ('Vsibility', 'Visibility'),
        ('VTR', 'VTR'), ('LTR', 'LTR'),
    )
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.ForeignKey(CampaignNamingTool, on_delete=models.CASCADE)
    dsp = models.CharField(max_length=30, choices=dsp_choices)
    budget = models.DecimalField(max_digits=20, decimal_places=2)
    kpi = models.CharField(max_length=10) #choices=kpi_choices)
    start_date = models.DateField()
    end_date = models.DateField()

【问题讨论】:

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


    【解决方案1】:

    你可以这样做:

    <select id="kpi">
        <option>...</option>
    </select> 
    
    <input id="kpi_input">
    
    <script>
        const kpiSelection = document.getElementById("kpi");
        const kpiInput = document.getElementById("kpi_input");
    
        var kpiValue = kpiSelection.options[kpiSelection.selectedIndex].text;
        kpiInput.value = kpiValue.split('-')[6]
    </script>
    

    获取所选选项的文本并设置输入字段的值。将此创建为将在所选选项更改时触发的函数。

    【讨论】:

    • 谢谢,我的 django forms.py 中已经有了输入字段。有没有可能在 django 模型中做到这一点?
    • @aba2s 如果它基于仅取决于所选选项的固定值,您可以从表单中排除该字段,但在保存之前在视图中处理所选值。如果没有并且您不想使用 JS,那么当用户更改所选选项时,您将如何重新加载表单。
    猜你喜欢
    • 2011-02-25
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2021-10-05
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多