Whiteox
Whiteox

Reputation: 39

unable to get data from django form

forms.py

class ScanForm(forms.Form):
   image = forms.ImageField()
   xml_file = forms.FileField()
   description = forms.CharField(max_length=500)

views.py

def home(request):
  form = ScanForm()
  if request.method == 'POST':
    form = ScanForm(request.POST, request.FILES)
    if form.is_valid():
      image = form.cleaned_data['image']
      xml_file = form.cleaned_data['xml_file']
      description = form.cleaned_data['description']
  return render(request,'app/home.html',{'form':form})

home.html

<form enctype="multipart/form-data" method = "POST">
   {% csrf_token %}
   {{ form|crispy }}
   <input type="submit" value="Submit" class="btn btn-success btn-lg"/>
 </form>

only description is printed on the terminal values of image and xml_file i get is None or NoneType

Upvotes: 0

Views: 130

Answers (1)

binpy
binpy

Reputation: 4194

Especially for your both image and xml_file fields can be access by using request.FILES[key_name]. the form.cleaned_data only used for non-file payloads.

for example in your case should be:

if form.is_valid():
    image = request.FILES['image']
    xml_file = request.FILES['xml_file']
    description = form.cleaned_data['description']

For more information about it, you can directly check to this docs: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/

Upvotes: 2

Related Questions