Django instantiate a file field using model form

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

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

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(),

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():
            return redirect('page')
    context = {'a': a, 'form': form, }
    return render(request, template, context)


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

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

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

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

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

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.


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.


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