Django Model form is showing invalid with initialized values and file

59 Views Asked by At

I have a model like this:

class Cohortpdfs(models.Model):
    id = models.AutoField(primary_key=True,editable=True)
    title= models.CharField(max_length=200,validators=[MaxLengthValidator(100)])
    content=models.FileField()
    cohort_id=models.ForeignKey(Cohort,on_delete=models.CASCADE,default=0,db_constraint=False)

I want to initialize and save data from views.

views.py:

    if requests.method == 'POST':  
        initialvalue={
            'cohort_id':id,
            'title':requests.POST.get('title'),
            'content':requests.FILES['content'],
        }
              
        if contentform.is_valid():     
            print("form valid")
        else:
            print("FORM ERROR")

Forms.py

class CohortpdfsForm(forms.ModelForm):

    class Meta:
        model = Cohortpdfs

        fields = [
            "title","content","cohort_id",
        ]

        widgets={
            'title' : forms.TextInput(attrs={'class': 'form-control','max_length':20}),
            'content': forms.FileInput(attrs={'class': 'form-control'}),
            'cohort_id': forms.TextInput(attrs={'type': 'hidden'}),
        }

This is showing my form is not valid. How can I initialize the form with the uploaded file(PDF) and save it into the model database?

0

There are 0 best solutions below