对于我目前的Django项目,我构建了一个使用3个ModelForms的页面。
整个页面应该让酒店在网站上注册。 所以第一个ModelForm来自酒店模型
接下来,我希望用户输入2个图像表格,一个主图像和一个背景图像。这两个模型继承自基本的Image类 因此,在这种情况下,两个图像都将使用来自基类的标题字段。
现在当我在表格中输入新酒店并添加2张图片时,两张图片都会得到相同的标题 当我看一下html代码时,这确实有意义,因为输入字段都具有相同的名称=" title"。
对于其余部分,表单的工作方式与预期一致,只是这一个问题 当然,我可以将标题字段放入子类中,如child_class_1_title和child_class_2_title,但这只会破坏整个OOP和DRY原则。
如何确保每个表单都将正确的数据推送到数据库中? 非常感谢。
这是我的表格代码:
class HotelForm(ModelForm):
class Meta:
model = Hotel
fields = ('name', 'address', 'zip_code', 'city', 'website', 'email', 'phone', 'description', 'short_description', 'number_of_rooms', 'facilities',
'activities', 'environment', 'hotel_type')
widgets = {
'facilities': CheckboxSelectMultiple()
}
class HotelGeneralImageForm(ModelForm):
class Meta:
model = HotelGeneralImage
fields = ('title', 'hotel_general_image')
widgets = {
'hotel_general_image': FileWidget()
}
class HotelBackgroundImageForm(ModelForm):
class Meta:
model = HotelBackgroundImage
fields = ('title', 'hotel_background_image')
widgets = {
'hotel_background_image': FileWidget()
}
观点:
@csrf_exempt
def hotel_registration(request):
if request.method == 'POST':
hotel_form = HotelForm(request.POST, instance=Hotel())
hotel_general_image_form = HotelGeneralImageForm(request.POST, instance=HotelGeneralImage())
hotel_background_image_form = HotelBackgroundImageForm(request.POST, instance=HotelBackgroundImage())
if hotel_form.is_valid() and hotel_general_image_form.is_valid() and hotel_background_image_form.is_valid():
new_hotel = hotel_form.save()
new_hotel_general_image = hotel_general_image_form.save(commit=False)
new_hotel_general_image.hotel = new_hotel
new_hotel_general_image.save()
new_hotel_background_image = hotel_background_image_form.save(commit=False)
new_hotel_background_image.hotel = new_hotel
new_hotel_background_image.save()
return HttpResponseRedirect('registered')
else:
hotel_form = HotelForm(instance=Hotel())
hotel_general_image_form = HotelGeneralImageForm(instance=HotelGeneralImage())
hotel_background_image_form = HotelBackgroundImageForm(instance=HotelBackgroundImage())
context = {'hotel_form': hotel_form,
'hotel_general_image_form': hotel_general_image_form,
'hotel_background_image_form': hotel_background_image_form
}
context.update(csrf(request))
return render_to_response('hotel/hotel-registration-form.html', context)
答案 0 :(得分:1)
表单前缀将解决您的问题:
hotel_general_image_form = HotelGeneralImageForm(prefix='general', ...)
hotel_background_image_form = HotelBackgroundImageForm(prefix='background', ...)
这样每个表单都有自己的前缀,因此不会干扰其他表单。
更多文档 - https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.prefix