我没有通过表单获得任何数据。我显然错过了一些东西,但我不知道是什么。
I'm following this documentation.
forms.py
class EventRegistrationForm(forms.Form):
tags = forms.TextInput()
class Meta:
model = Event
fields = [
'name', 'description', 'type', 'map_pin', 'location_id', 'location_name', 'address1',
'address2', 'city', 'state', 'zip', 'country', 'admission_fee', 'free_admission', 'online_ticket_url',
'available_parking', 'nearby_transit', 'stream', 'kid_friendly', 'no_underage', 'website_url', 'opportunities'
]
views.py
def save_event(request):
if request.is_ajax() and request.method == "POST":
main_form_data = json.loads(request.POST.get('mainForm'))
print(main_form_data)
main_form = EventRegistrationForm(main_form_data)
if main_form.is_valid():
print("Form is incorrectly returning as valid")
print(main_form.cleaned_data)
输出:
{'online_ticket_url': '', 'state': '', 'city': '', 'stream': '', 'name': 'Test Subject', 'description': '', 'type': None, 'no_underage': 'on', 'map_pin': '', 'available_parking': '', 'opportunities': '', 'address': '', 'free_admission': 'on', 'kid_friendly': 'on', 'nearby_transit': '', 'tags': '', 'location_name': '', 'admission_fee': '', 'website_url': '', 'zip': '', 'location_id': '', 'country': ''}
Form is incorrectly returning as valid
{}
如果有人能说出我被绊倒的地方,我会很感激。
编辑:这是我在shell中获得的。我想我误解了这些应该如何运作:>>> a = EventRegistrationForm({"name":"Adam"})
>>> a.is_valid()
True
>>> a.cleaned_data
{}
答案 0 :(得分:0)
您已在模型中定义了很多字段blank=True
,这就是为什么在没有提供任何值时表单返回有效的原因。如果您阅读文档,blank=True
允许在ModelForms中将字段留空。
您可以在__init__()
方法中覆盖并设置required=True
,
class EventRegistrationForm(forms.Form):
tags = forms.TextInput()
class Meta:
model = Event
fields = [
'name', 'description', 'type', 'map_pin', 'location_id', 'location_name', 'address1',
'address2', 'city', 'state', 'zip', 'country', 'admission_fee', 'free_admission', 'online_ticket_url',
'available_parking', 'nearby_transit', 'stream', 'kid_friendly', 'no_underage', 'website_url', 'opportunities'
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].required = True
答案 1 :(得分:0)
我解决了。出于某种原因,此表单是使用标准表单(forms.Form
)而不是模型表单(forms.ModelForm
)设置的。因此,我的所有领域都没有被注册......
class EventRegistrationForm(forms.ModelForm):
....