How to save or store the documents that a user uploads in my django form?

Viewed 43

I have a django form that accepts complaints from users and saves them in the admin panel. Everything seems to be working perfectly. The form accepts the data and stores them all in the admin panel except for the upload file data. The form does accept a file from the user and seems to submit it but while the other data is getting stored perfectly, The file isn't getting stored. How do I upload and save the file as well?

models.py:

class Complaint(models.Model):
   user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True)
   reportnumber = models.CharField(max_length=500 ,null = True, blank= False)
   eventdate = models.DateField(null=True, blank=False)
   event_type = models.CharField(max_length=300, null=True, blank=True)
   device_problem = models.CharField(max_length=300, null=True, blank=True)
   manufacturer = models.CharField(max_length=300, null=True, blank=True)
   product_code = models.CharField(max_length=300, null=True, blank=True)
   brand_name = models.CharField(max_length = 300, null=True, blank=True)
   exemption = models.CharField(max_length=300, null=True, blank=True)
   patient_problem = models.CharField(max_length=500, null=True, blank=True)
   event_text = models.TextField(null=True, blank= True)
   document = models.FileField(upload_to='static/documents', blank=True, null=True)

   def __str__(self):
       return self.reportnumber

views.py:

def NewComplaint(request):
   user = request.user
   if request.method == 'POST':
       form = ComplaintForm(request.POST)
       print(form)
       if form.is_valid():
           print("hello")
           cmp_obj = form.save(commit=False)
           cmp_obj.user = user
           cmp_obj.save()
       submitbutton= request.POST.get('submit')

       if submitbutton:
           messages.success(request, 'Submitted!')
       context = {'form': form}
       return render(request, 'new.html', context)
   else:
       form = ComplaintForm()
       context = {'form': form}
       return render(request,'new.html',context)

forms.py:

class DateInput(forms.DateInput):
   input_type = 'date'

class ComplaintForm(ModelForm):
   class Meta:
       model = Complaint
       fields = '__all__'
       widgets = {
           'reportnumber': forms.TextInput(attrs={'placeholder': 'Report number'}),
           'event_type': forms.TextInput(attrs={'placeholder': 'Event type'}),
           'eventdate': DateInput(),
           'device_problem': forms.TextInput(attrs={'placeholder': 'Device Problem'}),
           'event_text': forms.Textarea(attrs={'style': 'height: 130px;width:760px'}),
           'manufacturer': forms.TextInput(attrs={'placeholder': 'Enter Manufacturer Name'}),
           'product_code': forms.TextInput(attrs={'placeholder': 'Enter Product Code'}),
           'brand_name': forms.TextInput(attrs={'placeholder': 'Enter Brand Name'}),
           'exemption': forms.TextInput(attrs={'placeholder': 'Enter Exemption'}),
           'patient_problem': forms.TextInput(attrs={'placeholder': 'Enter Patient Problem'}),
       }
    
   def clean(self):
       cleaned_data = super(ComplaintForm, self).clean()
       reportnumber = cleaned_data.get('reportnumber')
       event_text = cleaned_data.get('event_text')
       if not reportnumber and not event_text:
           raise forms.ValidationError('You have to write something!')
       return cleaned_data

template:

<form class="" action="" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <p class="sub-typ-wr">Submit Type</p>
            <a href="/Login/Add-Complaint/Document-Style/"><button type="button" class="btn btn-secondary document-btn">Document</button></a>

            <div class="rep-num">
                <label class="written-label" for="">Report Number</label>
                <div class="written-txt-field">{{form.reportnumber}}</div>
            </div>

            <div class="eve-dte">
                <label class="written-label" for="">Event Date</label>
                <div class="written-txt-field">{{form.eventdate}}</div>
            </div>

            <div class="eve-typ">
                <label class="written-label" for="">Event Type</label>
                <div class="written-txt-field">{{form.event_type}}</div>
            </div>

            <div class="dev-pro">
                <label class="written-label" for="">Device Problem</label>
                <div class="written-txt-field">{{form.device_problem}}</div>
            </div>

            <label class="written-label eve-txt" for="">Event Text</label>

            <div class="Manufacturer">
                <label class="written-label" for="">Manufacturer</label>
                <div class="written-txt-field">{{form.manufacturer}}</div>
            </div>

            <div class="pro-code">
                <label class="written-label" for="">Product Code</label>
                <div class="written-txt-field">{{form.product_code}}</div>
            </div>

            <div class="brand-name">
                <label class="written-label" for="">Brand Name</label>
                <div class="written-txt-field">{{form.brand_name}}</div>
            </div>

            <div class="exem">
                <label class="written-label" for="">Exemption</label>
                <div class="written-txt-field">{{form.exemption}}</div>
            </div>

            <div class="pat-pro">
                <label class="written-label" for="">Patient Problem</label>
                <div class="written-txt-field">{{form.patient_problem}}</div>
            </div>



            <div class="comp-textarea">{{form.event_text}}</div>
            <button type="button" class="btn btn-secondary attach-btn-1"><div class="fas fa-file-upload">{{form.document}}</div></button>
            <button type="submit" name="submit" class="btn btn-secondary save-btn-1"><i class="fas fa-save"></i> Save</button>
        </form>

How do I save the form from the documents filefield? I have given the path where the file should be uploaded but the file isn't getting uploaded there either

1 Answers

You should mention the path if you need too sub-directories .set up media URL .make sure that it's working fine
Then pass request.FILES as parameter:

form = ComplaintForm(request.POST, request.FILES)
Related