0

I'm having trouble with the image Field in the Django forms module, I'm trying to create a form in a website where the users are able to upload images to the database and I'm using Django built-in form module to create a form page in the HTML page and once the user uploads their data which include some images they would press submit and this should upload it in the backend but for some reason, I'm not getting anything can anyone help???

Here is my code:

def CreateQueries(request):
    queryform = QueryForm() 
    if request.method == 'POST':
        queryform = QueryForm(request.POST, request.FILES)
        if queryform.is_valid():
            title_question = queryform.cleaned_data.get('title')
            first_question = queryform.cleaned_data.get('Query1')
            second_question = queryform.cleaned_data.get('Query2')
            first_image = queryform.cleaned_data.get('Image1')
            second_image = queryform.cleaned_data.get('Image2')

            queries = Queries.objects.create(
                Topic=title_question,
                Q1=first_question,
                Q2=second_question,
                Qimg1=first_image,
                Qimg2=second_image
            )

            queries.save()
            print(queries)


    return render(request, 'Querie/CreateQueries.html', {'form': queryform})

Here is the CreateQueries.html template:

{% extends 'base.html' %}

    {% block content %}
    
    <div class="grid">
        <form class="create-form" action="." method="POST"> {% csrf_token %}
            {{form.as_p}}
            <button type="submit" class="create-input">Submit</button>
        </form>
    </div>
    
    {% endblock%}

Here is the form file code:

from django import forms


class QueryForm(forms.Form):
    Title = forms.CharField(max_length=200)
    Query1 = forms.CharField(max_length=200)
    Query2 = forms.CharField(max_length=200)
    Image1 = forms.ImageField()
    Image2 = forms.ImageField()
  • Please [edit] your question and show the template `CreateQueries.html`. – Abdul Aziz Barkat Jun 05 '21 at 17:48
  • 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) In short your form tag needs the attribute `enctype="multipart/form-data"` – Abdul Aziz Barkat Jun 05 '21 at 18:07
  • 1
    Wow it worked!!! Thank you very much sir I really appreciate it :) – Rodany Antoine Jun 05 '21 at 18:17

0 Answers0