我有以下观点
class ProductUpdateView(BaseProductUpdateView):
form_class = ProductForm
slug_field = "id"
def form_valid(self, form):
form.instance.hotel = form.cleaned_data["hotel"]
form.instance.parent = form.cleaned_data["parent"]
return super(ProductUpdateView, self).form_valid(form)
以下表格:
class ProductForm(BaseProductForm):
hotel = forms.ModelChoiceField(queryset=Hotel.objects.all(), widget=forms.TextInput)
parent = forms.ModelChoiceField(queryset=Product.objects.all(), widget=forms.TextInput, required=False)
class Meta:
model = Product
exclude = ('slug', 'parent', 'hotel', 'status', 'score', 'product_class',
'recommended_products', 'related_products',
'product_options', 'attributes', 'categories')
保存表单时,表单已成功保存。我可以在admin中看到hotel和parent的保存值,但是当我重新打开更新表单页面时,其他字段会返回,但是hotel和parent字段返回空白。有任何想法吗?
答案 0 :(得分:0)
我像下面那样处理它
views.py
class ProductUpdateView(BaseProductUpdateView):
form_class = ProductForm
slug_field = "id"
def get_form_kwargs(self, **kwargs):
kwargs = super(ProductUpdateView, self).get_form_kwargs(**kwargs)
kwargs['initial']['hotel'] = self.get_object().hotel.id if \
self.get_object().hotel else None
kwargs['initial']['parent'] = self.get_object().parent.id if \
self.get_object().parent else None
return kwargs
def form_valid(self, form):
form.instance.hotel = form.cleaned_data["hotel"]
form.instance.parent = form.cleaned_data["parent"]
return super(ProductUpdateView, self).form_valid(form)
forms.py
class AutoCompleteModelChoiceField(forms.ModelChoiceField):
widget = forms.TextInput
def clean(self, value):
value = super(AutoCompleteModelChoiceField, self).clean(value)
return value
class ProductForm(BaseProductForm):
hotel = AutoCompleteModelChoiceField(queryset=Hotel.objects.all())
parent = AutoCompleteModelChoiceField(queryset=Product.objects.all(),
required=False)