Home > OS >  Python Django Form "This field is required"
Python Django Form "This field is required"

Time:10-24

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

CodePudding user response:

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>

CodePudding user response:

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...

  • Related