'Django product update / inline formsets updating a model
I am creating an E-commerce website, I'm having a problem when I'm updating images of the product, I can update the form `but I can't update the images. can you guys tell what am I doing wrong ? this is my code:
views.py
class ProductEditView(UpdateView):
model = Product
form = ProductUpdateForm
fields='__all__'
product_metas = ProductUpdateMetaForm
template_name = 'products/update_product.html'
product_meta_formset = ProductMetaInlineFormset()
meta = product_metas
ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5)
def form_valid(self, form):
response = super(ProductEditView, self).form_valid(form)
if self.request.method == 'POST':
product_meta_formset = self.ProductMetaInlineFormset(self.request.POST, self.request.FILES, instance=self.object)
product_meta_formset.save()
return response
def get_context_data(self, **kwargs):
context = super(ProductEditView, self).get_context_data(**kwargs)
context['product_meta_formset'] = self.ProductMetaInlineFormset(instance=self.object)
return context
forms.py
class ProductUpdateMetaForm(forms.ModelForm):
class Meta:
model = Image
fields = ['image', 'is_feature', ]
ProductMetaInlineFormset = inlineformset_factory(Product,Image,form = ProductUpdateMetaForm ,extra=5,)
update_product.html
<div class="container mt-4">
<form enctype="multipart/form-data" action= "." method="POST" class="ui form">
{% csrf_token %}
<div class="card">
<div class="card-body">
{{ form.non_form_errors }}
{{ form.as_p }}
{{ product_meta_formset.non_form_errors }}
{{ product_meta_formset.management_form}}
{% for form in product_meta_formset %}
<div class="d-flex py-1 inline {{ product_meta_formset.prefix }}">
<div>{{form.image.label}}: {{ form.image }}</div>
<div class="ml-4">{{form.is_feature.label}}: {{ form.is_feature }}</div>
{% if product_meta_formset.can_delete %}
<div class="ml-4">{{ form.DELETE }} {{ form.DELETE.label }}</div>
{% endif %}
</div>
{% endfor %}
</div>
</div>
<button type='submit' class = 'ui positive button mtop'>Update product</button>
</div>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
