0

I want to accept an optional image from the user and pass it via my form, but it keeps popping up with multivaluedictkeyerror (i have added the enctype = "multipart/form-data") ps. im new to django

this is my views.py

def notes(request):
    if request.method == "POST":
        form =NotesForm(request.POST, request.FILES or None)
        if form.is_valid():
            notes  = Notes(user=request.user, title = request.POST['title'],description=request.POST['description'], pictures= request.FILES['pictures'])        #pictures= request.FILES['pictures']
            notes.save()
        messages.success(request,f"Notes added for {request.user.username} successfully!")
    else:
        form=NotesForm()
    notes=Notes.objects.filter(user=request.user)       #when logged in user wants to access all created notes, stores in notes variable
    context= {'notes':notes , 'form':form}
    return render(request,'dashboard/notes.html',context)


this is my models.py

from django.db import models
from django.contrib.auth.models import User

class Notes(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE) 
    title = models.CharField(max_length=200)
    pictures=models.ImageField(null=True,blank=True, upload_to="images/")
    description= models.TextField()

template,

<p class="description m-5 p-5">
                {{notes.description}}
                <br><center>
                {% if notes.pictures %}
                    <img class="fit-picture" style="border: 1px solid #555; max-width:80%; max-height:80%;" src = "{{ notes.pictures.url }}"> 
                {% endif %}               
            </p>

I accepted the passed value through request.Files[''], but it is a compulsory field, and i wanted an optional

  • 1
    you speak about **enctype** but your html does not contains form... – Lucas Grugru Dec 28 '22 at 08:56
  • I have added the enctype to my form (template) that submits the data, I've just not attached that template to this above code. The template that ive specified here, just contains displaying of said picture – Shawn Thomas Dec 28 '22 at 15:07
  • I have used, ***pictures= request.FILES.get('pictures')***, to sort this problem. Never been prouder of myself even though its such a small debugging task :) – Shawn Thomas Dec 28 '22 at 15:17

0 Answers0