如何访问作为模型传递的modelForms字段

时间:2011-04-20 17:03:39

标签: django modelform

forms.py

class BandForm(forms.ModelForm):
    time_from = forms.ChoiceField(choices=[(8,  "08:00"),(9, "09:00"),(10, "10.00"),(11,  "11:00"),
                                           (12, "12:00"),(13, "13:00"),(14, "14:00"),(15, "15:00"),
                                           (16, "16:00"),(17, "17:00"),(18, "18:00"),(19, "19:00"),
                                           (20, "20:00"),(21, "21:00"),(22, "22:00"),(23, "23:00")])
    time_to   = forms.ChoiceField(choices=[(8,  "08:00"),(9,  "09:00"),(10, "10:00"),(11, "11:00"),
                                           (12, "12:00"),(13, "13:00"),(14, "14:00"),(15, "15:00"),
                                           (16, "16:00"),(17, "17:00"),(18, "18:00"),(19, "19:00"),
                                           (20, "20:00"),(21, "21:00"),(22, "22:00"),(23, "23:00")])
    class Meta:
        model = Entry1
        exclude = ('created','date')

views.py的一部分

if request.method == "POST":
        form = BandForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            if year and month and day:
                form.date = datetime.date(int(year),int(month),int(day))
                form.save()

假设我想在forms.py中为我的班级Bandform

做一些验证

def clean_fieldname(self): ....

通常会传递这样的参数 - self.cleaned_data.get('field_name')。因此,如果我尝试获取self.cleaned_data.get('time_from') - 每个事情都很有效。但是如果我尝试获取self.cleaned_data.get('date'),我会返回None。

为什么?

答案

Django Modelform (with excluded field) 从Post i提供的唯一有点不清楚的是,你必须访问forms.py中的实例作为self.instance.fieldname但不能访问self.cleaned_data.get('fieldname')。

1 个答案:

答案 0 :(得分:0)

排除在外:

exclude = ('created','date')

您排除date字段在表单中可见。这可以解释为什么您无法访问cleaning_data中的date。尝试从排除元组中删除date并在模板中呈现它以查看它是否显示。