Tuesday, July 19, 2016

Django : InlineFomsets with FileField, overwrite forms.ModelForm Function

I have a model Product and a model Document. The document has a foreign key to the product.


I want the user to upload multiple files in the same form for adding/editing Product.


I modified and example from net, it is working, but not with a FileField.


I know that I need to add request.File but until now I didn't added where is needed, because is not working.


models


class Product( models.Model):       #default attributes     name = models.CharField(max_length=200,db_index=True)     short_description = models.CharField(max_length=160)     description = models.TextField()    class Document(models.Model):        product = models.ForeignKey('products.Product', on_delete=models.CASCADE)      document = models.FileField(upload_to=upload_to)


forms


class DocumentModelForm(forms.ModelForm):     class Meta:         model = Document         fields = ['document']      DocumentInlineFormSet = forms.inlineformset_factory(     Product,     Document,     fields=('document', 'id'),     extra=0,     can_delete=False,     min_num=1, validate_min=True,  max_num=3, validate_max=True,

)


class ProductModelForm(forms.ModelForm):     class Meta:         model = Product         fields = [          'name',          'short_description',          'description',      ]    def __init__(self, *args, **kwargs):      super().__init__(*args, **kwargs)      self.checks = DocumentInlineFormSet(          instance=self.instance, prefix='checks',          data=self.data if self.is_bound else None)    def is_valid(self, commit=True):      product_valid = super().is_valid()      checks_valid = self.checks.is_valid()      return product_valid and checks_valid    def save(self,commit=True):      product = super().save(commit=commit)      product._checks = self.checks.save(commit=commit)      return product

template


<form method="POST" action="" enctype="multipart/form-data">      {% csrf_token %}      {{ form}}      {{ form.checks.management_form }}          {{ form.checks }}         <input type="submit" class="button" value="Submit">   </form>

views are normal

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/eb6d1b67-ad71-42fd-a826-af2669c470a1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment