Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Django Form "This field is required"

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'),
]

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading