Django instantiate a file field using model form

I am unable to instantiate a file field from the model form

model.py

class ModelA(models.Model):
    image_fileA = ResizedImageField()
    pdf_fileB = models.FileField()
    pdf_fileC = models.FileField()

forms.py

class FormA(ModelForm):
    class Meta:
        model = modelA
        fields = ['image_fileA', 'pdf_fileB', 'pdf_fileC']
        widgets = {
            'image_fileA': forms.FileInput(),
            'pdf_fileB': forms.FileInput(),
            'pdf_fileC': forms.FileInput(),
        }

views.py

def viewA(request, pk):
    template = 'app/edit.html'
    a = modelA.objects.get(id=pk)
    form = FormA(instance=a)
    if request.method == 'POST':
        form = FormA(request.POST, request.FILES, instance=a)
        if form.is_valid():
            form.save()
            return redirect('page')
    context = {'a': a, 'form': form, }
    return render(request, template, context)

edit.html

<form action="" method="POST" enctype='multipart/form-data'>
    {% csrf_token %}

    {%if a.image_fileA%}
    <img src="{{a.image_fileA.url}}">
    {{form.group_logo}}
    {%else%}Not Available{%endif%}

    {% if a.pdf_fileB%}
    <a href="{{a.pdf_fileB.url}}"></a>
    {{form.pdf_fileB}}
    {%else%}Not Available{%endif%}

    {% if a.pdf_fileC%}
    <a href="{{a.pdf_fileC.url}}"></a>
    {{form.pdf_fileC}}

    <button type="submit">Save</button>
</form>                

What I have tried

I had to use if else...~~~ to enable file upload in case the file was not available. Have also attached a URL link to enable one to see uploaded files.

Errors

I expect all fields to have form instances but when i try to save the form without editing I get the following error 'File' object has no attribute 'content_type'

Hence the form is only saved when all fields are edited.

Can somebody guide where am doing it wrongly.

Expectattions

When on the editing page, one should be able to see all data attached to respective fields. Editing or not editing the form should save successfully without errors

Back to Top