0

I have the following view

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)

and following 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')

When I save the form, form saved successfully. I can see the saved values of hotel and parent in admin, but when I re-open the update form page, other fields returns but hotel and parent fields return blank. Any ideas?

4

1 回答 1

0

我像下面这样处理它

视图.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)

表格.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)
于 2013-07-05T13:02:52.727 回答