-1

when i upload icon and image then error come

MultiValueDictKeyError at /product/create/
'icon'
Request Method: POST
Request URL:    http://127.0.0.1:8000/product/create/
Django Version: 2.2a1
Exception Type: MultiValueDictKeyError
Exception Value:    
'icon'
Exception Location: C:\Users\Rohit\Anaconda3\lib\site-packages\django-2.2a1-py3.7.egg\django\utils\datastructures.py in __getitem__, line 80
Python Executable:  C:\Users\Rohit\Anaconda3\python.exe
Python Version: 3.7.0

def create(request):
    if request.method == 'POST':
        if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.POST['icon'] and request.POST['image']:
            product=Product()
            product.title=request.POST['title']
            product.body=request.POST['body']
            if request.POST['url'].startswith('https//') or request.POST['url'].startswith('http//'):
                product.url=request.POST['url']
            else:
                product.url= 'https//'+ request.POST['url']

            product.image = request.FILES['image']
            product.icon = request.FILES['icon']
            product.pub_date=timezone.datetime.now()
            product.hunter = request.user
            product.save()
            return redirect('home')


        else:
            return render(request, 'products/create.html',{'error': 'please fill all the detail'})
Alasdair
  • 298,606
  • 55
  • 578
  • 516

3 Answers3

1

you need change this line :

if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.POST['icon'] and request.POST['image']:

to

if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:

in other word change request.POST s for image and icon field to request.FILES

request.FILES['icon'] and request.FILES['image']
hassanzadeh.sd
  • 3,091
  • 1
  • 17
  • 26
0

The problem is this line : product.icon = request.FILES['icon']

When you send the request on your app, there is no 'icon' in request.FILES. So 2 potentials problems. First one is you don't send icon in requesT.FILES in your frontend file. Or the second problem is sometime icon is empty and you are not handle this case.

If the icon is sometime empty you should use this instead:

is_icon = request.POST.get('is_icon ', False)

you have lot of documentation on get function. Here part of the manual :

The get() method returns the value for the specified key if key is in >dictionary.

get() Parameters The get() method takes maximum of two parameters:

key - key to be searched in the dictionary value (optional) - Value to be returned if the key is not found. The default value is None.

Valentin Garreau
  • 963
  • 1
  • 10
  • 32
0

I also come across that in my create.html file, I put it wrong

You should make sure that you do it correctly like this:

that means form-data instead of form_data