模型形式的Django必填字段 [英] Django required field in model form

查看:38
本文介绍了模型形式的Django必填字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from 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()

在实际电路模型中,字段定义如下:

In the actual Circuit model, the fields are defined like this:

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

我的 views.py 在这里:

My views.py for this is here:

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})

我该怎么做才能不需要这两个字段?

What can I do so that the two fields aren't required?

推荐答案

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

If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:

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

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

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

The redefined constructor won't harm any functionality.

这篇关于模型形式的Django必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆