0

i made a form in django with one field required (imagefield) but when I fill it by selecting an image, once I fill it it considers that the form is not valid and asks to fill it again I don't understand why, here is my code below:

view.py:

def success(request):
    return HttpResponse('successfully uploaded')


def contact(request, plage_name):

    name = plage_name
    plage = Spot.objects.get(name__iexact=name)

    if request.method == 'POST':
        form = ContactUsForm(request.FILES)  # ajout d’un nouveau formulaire ici
    
        if form.is_valid():
            print("it's valide")
            plage.photo = form.cleaned_data['photo']
            plage.save()
            return redirect('success')

    else:
        form = ContactUsForm()

    return render(request,
            'pages/Testform.html',
            {'form': form})  # passe ce formulaire au gabarit

form.py

class ContactUsForm(forms.Form):
   photo = forms.ImageField(required=True)

html

<form action="" method="post" novalidate>
{% csrf_token %}
{{ form }}
<input type="submit" value="Envoyer">
</form>

Url.py

urlpatterns = [
    path('contact-us/<path:plage_name>', views.contact, name='contact'),
]
  • 2
    Does this answer your question? [Why is form enctype=multipart/form-data required when uploading a file?](https://stackoverflow.com/questions/1342506/why-is-form-enctype-multipart-form-data-required-when-uploading-a-file) – Abdul Aziz Barkat Oct 24 '22 at 11:07
  • if the form is valid, why are you not calling `form.save()` ? – Zkh Oct 24 '22 at 11:07

2 Answers2

1

I think your error is on the parameters of form init. The first paramters is for POST data, not FILES:

form = ContactUsForm(request.POST, request.FILES)

And after, you have to call form.save(), probably better than make the update yourself...

Lucas Grugru
  • 1,664
  • 1
  • 4
  • 18
1

in views.py

if request.method == 'POST':
        form = ContactUsForm(request.POST,request.FILES) 

in HTML

<form action="" method="post" novalidate enctype="multipart/form-data">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Envoyer">
</form>