我有一个大目标——用户旅行报告。我为用户提供了界面,可以一一编辑该报告中的某些字段。由于用户可以一次编辑一个字段,因此我创建了根据用户想要编辑的字段创建模型表单的方法。
它是这样工作的:
def createFieldEditorForm(client, field, report_id, request = None):
from django.shortcuts import get_object_or_404
report_instance = get_object_or_404(DriveReport, id = report_id)
class FieldEditorForm(forms.ModelForm):
class Meta:
model = DriveReport
fields = ['id', ]
id = forms.IntegerField(label = _(u"ride_id"), widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
super(FieldEditorForm, self).__init__(*args, **kwargs)
self.build_fields()
def build_fields(self):
if field == 'driver_id':
driver_query = Driver.objects.filter(client = client)
choices = [('', u'------'),]
for driver in driver_query:
choices.append((driver.id, driver.name))
self.fields[field] = forms.IntegerField(
label = _(u"Drivers"),
widget = forms.Select(
choices = choices,
attrs = {'data-name':'driver_id'} ),
required = False)
elif field == 'project_id':
area_query = Area.objects.filter(client = client)
choices = [('', u'------'),]
for area in area_query:
choices.append((area.id, area.name))
self.fields[field] = forms.IntegerField(
label = _(u"Projects"),
widget = froms.Select(
choices = choices,
attrs = {'data-name':'project_id'} ),
required = False)
elif field == 'trip_type':
self.fields[field] = forms.CharField(
label = _(u"Projects"),
widget = forms.Select(
choices = [(key, value) for key, value in TRIP_TYPE_CHOICES.iteritems()],
attrs = {'data-name':'trip_type'} ),
required = False)
else:
self.fields[field] = forms.CharField(required = False, widget = forms.TextInput(attrs = {'data-name':field} ))
if request is None:
return FieldEditorForm(instance = report_instance)
else:
return FieldEditorForm(request, instance = report_instance)
并且在视图中
它是这样的:
if request.method == 'POST':
form = createFieldEditorForm(activeaccount, field_id, ride_id, request.POST)
if form.is_valid():
form.save()
messages.success(request, _("New field value successfully added/updated"))
else:
messages.error(request, _("Value was not saved"))
return feedback_to_json(request, form)
结果是 - 我在浏览器中收到成功消息,但该字段未更新。
我尝试覆盖 form.save() 方法并检查 self.cleaned_data 是否包含 [field] - 确实如此。它就在那里。即使我在保存之前和保存之后打印出表单,我也可以看到,数据已经到达后端,而且一切都很好而且整洁.. 但是该死的值只是没有保存/更新到数据库中