简体   繁体   中英

Not able to submit data from model form with multiple files django

I am trying to add multiple files through use of two models and forms. Have tried to update but not able to make it work. On submission of form, there are no errors, but nothing is posted to database.

Please help.

Also, how do I define users as full name in drop downs in forms? Tried formfields approach but not working. Also, form not showing empty label

models.py

class Case(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name= 'caseclients' )
    statute = models.ForeignKey(Statute, on_delete=models.CASCADE)
    financial_year = models.ForeignKey(Financialyear, on_delete=models.CASCADE)
    proceeding = models.ForeignKey(Proceeding, on_delete=models.CASCADE)
    case_title = models.CharField(max_length=200)
    initiated_on = models.DateField(auto_now=False, auto_now_add=False)
    communication_received_on = models.DateField(auto_now=False, auto_now_add=False)
    first_date_of_hearing = models.DateField(auto_now=False, auto_now_add=False)
    limitation_period = models.CharField(max_length=500, blank=True)
    amount_involved = models.IntegerField(null=True,blank=True)
    person_responsible = models.ForeignKey(User, on_delete=CASCADE, related_name = 'person_responsible')
    assisted_by = models.ManyToManyField(User, related_name = 'assisted_by', blank=True)
    brief_of_case = models.TextField(max_length=1000)
    status = models.CharField(choices=[('Open','Open'),('Close','Close')],default='Open', max_length=100)
    def __str__(self):
        return self.case_title

class CaseFiles(models.Model):
    attachment = models.FileField(upload_to='casefiles/')
    case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name= 'casefiles')
forms.py

class CaseFilesCreationForm(ModelForm):
    class Meta:
        model = CaseFiles
        fields = ['attachment']
      
        attachment = forms.FileField,

        widgets= {
            'attachment': forms.ClearableFileInput(attrs={'multiple': True, 'class': 'form-control form-control-light','type': 'file',}),
        }


class CaseCreationForm(ModelForm):
    class Meta:
        model = Case
        fields = '__all__'
      
        client = forms.ModelChoiceField(queryset=Client.objects.all(), to_field_name="name_of_client", empty_label="Select Client",),
        statute = forms.ModelChoiceField(queryset=Statute.objects.all(), to_field_name="statute", empty_label="Select Statute",),
        financial_year = forms.ModelChoiceField(queryset=Financialyear.objects.all(), to_field_name="financialyear", empty_label="Select Financial Year",),
        proceeding = forms.ModelChoiceField(queryset=Proceeding.objects.all(), to_field_name="proceeding", empty_label="Select Proceeding",),
        person_responsible = UserModelChoiceField(queryset=User.objects.all(),to_field_name="first_name"),
        assisted_by = UserModelMultipleChoiceField(queryset=User.objects.all(),to_field_name="first_name"),

        widgets= {
            'client': forms.Select(attrs={'class': 'form-select form-select-light',}),
            'statute': forms.Select(attrs={'class': 'form-select form-select-light',}),
            'financial_year': forms.Select(attrs={'class': 'form-select form-select-light',}),
            'proceeding': forms.Select(attrs={'class': 'form-select form-select-light',}),
            'case_title': forms.TextInput(attrs={'class': 'form-control form-control-light',}),
            'initiated_on': forms.DateInput(attrs={'class': 'form-control form-control-light', 'type': 'date',}),
            'communication_received_on': forms.DateInput(attrs={'class': 'form-control form-control-light', 'type': 'date',}),
            'first_date_of_hearing': forms.DateInput(attrs={'class': 'form-control form-control-light', 'type': 'date',}),
            'limitation_period': forms.TextInput(attrs={'class': 'form-control form-control-light',}),
            'amount_involved': forms.NumberInput(attrs={'class': 'form-control form-control-light',}),
            'person_responsible': forms.Select(attrs={'class': 'form-select form-select-light',}),
            'assisted_by': forms.Select(attrs={'class': 'select2 form-control select2-multiple form-select-light', 'data-toggle': 'select2', 'multiple': True}),
            'brief_of_case': forms.Textarea(attrs={'class': 'form-control form-control-light', 'rows':4}),
            'status': forms.Select(attrs={'class': 'form-control form-control-light',}),
        }
views.py

def createcase(request):
    if request.method == 'POST':
        form = CaseCreationForm(request.POST)
        file_form = CaseFilesCreationForm(request.POST, request.FILES)
        files = request.FILES.getlist('attachment')
        if form.is_valid() and file_form.is_valid():
            case_instance = form.save()
            case_instance.save()
            for f in files:
                file_instance = CaseFiles(attachment=f, case=case_instance)
                file_instance.save()
    else:
        form = CaseCreationForm()
        file_form = CaseFilesCreationForm()
    return render(request, 'cases/createcase.html',{'form':form, 'file_form':file_form})

Try changing your code to this. Frankly i don't understand what you were trying to do there but you performed a bunch of operations without saving the forms. So.. worth a shot.

    def createcase(request):
    if request.method == 'POST':
        form = CaseCreationForm(request.POST)
        file_form = CaseFilesCreationForm(request.POST, request.FILES)
        files = request.FILES.getlist('attachment')
        if form.is_valid() and file_form.is_valid():
            form.save() 
            file_form.save()
    else:
        form = CaseCreationForm()
        file_form = CaseFilesCreationForm()
    return render(request, 'cases/createcase.html',{'form':form, 'file_form':file_form})

Also you wanna make sure that in your html your form looks like this:

<form action="" method="post" enctype="multipart/form-data">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM