python - 模型表单中的 Django 必填字段

标签 python django forms model widget

我有一个表单,当我不想要它们时,会根据需要显示几个字段。这是来自models.py的表格

class CircuitForm(ModelForm):
    class Meta:
        model = Circuit
        exclude = ('lastPaged',)
    def __init__(self, *args, **kwargs):
        super(CircuitForm, self).__init__(*args, **kwargs)
        self.fields['begin'].widget = widgets.AdminSplitDateTime()
        self.fields['end'].widget = widgets.AdminSplitDateTime()

在实际的Circuit模型中,字段是这样定义的:

begin = models.DateTimeField('Start Time', null=True, blank=True)
end = models.DateTimeField('Stop Time', null=True, blank=True)

我的views.py在这里:

def addCircuitForm(request):
    if request.method == 'POST':
        form = CircuitForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/sla/all')
    form = CircuitForm()    
    return render_to_response('sla/add.html', {'form': form})

我该怎么做才能使这两个字段不再是必需的?

最佳答案

如果您不想修改模型中字段的空白设置(这样做会破坏管理站点中的正常验证),您可以在 Form 类中执行以下操作:

def __init__(self, *args, **kwargs):
    super(CircuitForm, self).__init__(*args, **kwargs)

    for key in self.fields:
        self.fields[key].required = False 

重新定义的构造函数不会损害任何功能。

关于python - 模型表单中的 Django 必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1134667/

相关文章:

python - psycopg2 在/tmp 上的权限被拒绝

python - 没有 “global” 关键字的每个工作人员的永久对象池

django - "select_for_update"从原子 block 调用仍然是 TransactionManagementError

python - 在基于类的 View (CBV) 中引用当前用户

python - 编辑ModelFormSet中的相关对象

javascript - 点击时如何从表单中获取数据?

python - 在 OpenPYXL 中运行 50k 行 Excel 文件的最快方法

python - scikit 总是过度拟合

javascript - 如何使用 javascript 自动提交表单(onevent)?

css - 如何在汇合的表单中设置CSS类或样式?