user3541631
user3541631

Reputation: 4008

Render the FileField as multiple file input field in the form based on multiple choices field

I have 2 models, Product and Document. Document has a FK to Product.

class Document(models.Model):
    product = models.ForeignKey(Product, related_name='documents', on_delete=models.CASCADE)
    document = models.FileField(upload_to=file_upload_to)
    type = models.CharField(max_length=255, choices=DOC_TYPE)

The Document can have different types (data sheet, whitepaper etc).

So, if I have 3 types of documents I want to see in HTML 3 inputs, each input representing a type:

<input name="myFile" type="file">  --> type 1
<input name="myFile" type="file">  --> type 2
<input name="myFile" type="file">  --> type 3
  1. After the form is submitted, I want somehow to know which type of document was it and then, modify the form and select in code the type

I'm thinking on using a custom widget inheriting from File, and add an attribute in each input, and then in save method identify the type

  1. Passing 1) what if I want to let the user add multiple documents for each type, and the number will not be equal for each one of type (a type can have 3, another type 1, and the third one none)

The user will not select the type, he will just upload files, based on UI.

See the example image below, the icons/image are the inputs (behind css done)

Each input represent a choice. In reality is just an input file field per but I create 3 for each choice/type. The user can add as many file per type/choice by click an add (plus sign) near the type/choice icon/image(that is in design)


enter image description here

Upvotes: 2

Views: 546

Answers (1)

Walucas
Walucas

Reputation: 2568

On your view that creates the formset:

for form in formset:

    form.fields['document'].widget.attrs = {'mytype':'whitepaper'}

Then on the POST you capture the attribute to check if that is whitepaper.

Let me know if that works

Upvotes: 1

Related Questions