我有以下表格:
class locationForm(forms.Form):
existing_regions= forms.ModelChoiceField(queryset=Region.objects.none(), label="Region Name", required=False)
region_name = forms.CharField()
location_name = forms.CharField()
street_address = forms.CharField()
city = forms.CharField()
zip_code = forms.CharField()
此表单的以下更新视图:
class UpdateLocation(View):
template_name = "dash/location_update_form.html"
def get(self, request, *args, **kwargs):
loc = kwargs['name']
try:
location = Location.objects.get(name=loc)
form = locationForm(instance=location)
return render(request, self.template_name, {'form': form,'location': location})
except (ValueError, ObjectDoesNotExist):
return redirect(reverse('geofence_manager'))
def post(self, request, *args, **kwargs):
loc = self.kwargs['name']
try:
location = Location.objects.get(name=loc)
form = locationForm (request.POST, instance=location)
if form.is_valid():
form.save()
else:
form = locationForm(request.POST, instance=location)
return render(request, self.template_name, {'location': location, 'form': form})
except (ValueError, ObjextDoesNotExist):
return redirect(reverse('location_manager'))
return redirect(reverse('location_manager'))
我收到关于正在使用的'instance'关键字参数的错误。我相信这与我没有使用Modelform
(我可能是错的)有关。但是我不想使用Modelform
来构建我的表单,那么有什么方法可以解决这个问题吗?
答案 0 :(得分:3)
class locationForm(ModelForm):
class Meta:
model = Location
fields = '__all__'
在您看来:
...
locationForm.base_fields['existing_regions'] = forms.ModelChoiceField(queryset= ...)
form = locationForm()