Multi Value DictKey Error in django while getting files in Django

Viewed 18

So, I have this simple django code in which a user uploads a image to change his user image but whenever I am trying to initiate the function it throws a multi value dict key error.

Views.py

    def image(request):
    email = request.user.email
    img = request.FILES['image']
    users = get_user_model()
    User = users.objects.get(email=email)
    User.image = img
    User.save()
    return redirect('settings')

I tried changing request.FILES('image') to request.FILES.get('image') but it would only delete the previous file in that object not to put the new file there.

I am using a custom user model aswell so here is my models.py also

class NewUser(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True,)
    user_name = models.CharField(max_length=150, unique=False)
    first_name = models.CharField(max_length=150, blank=True)
    last_name = models.CharField(max_length=150, blank=True)
    image = models.ImageField(upload_to = 'pics')
    DOB  = models.CharField(max_length =12, default=timezone.now)
    start_date = models.CharField(max_length =12,default=timezone.now)
    about = models.TextField( max_length=500, blank=True)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_buss = models.BooleanField(default=False)
    phone = models.CharField(max_length=12)
    otp = models.CharField(max_length=6, null=True)
    otp_g = models.CharField(max_length=15, null=True)
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name','first_name']
    objects =  CustomAccountManager()

    def __str__(self):
         return self.user_name
class CustomAccountManager(BaseUserManager):
    def create_superuser(self, email,user_name, first_name,password, **other_fields):
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)
        if other_fields.get('is_staff') is not True:
            raise ValueError('SuperUser must have is_staff as true')
        if other_fields.get('is_active') is not True:
                raise ValueError(_('SuperUser must have is_active as true'))
        if other_fields.get('is_superuser') is not True:
                raise ValueError('SuperUser must have is_SuperUser as true')
        return self.create_user(email,user_name, first_name, password, **other_fields)
    def create_user(self, email,user_name, first_name, password, **other_fields):
        if not email:
            raise ValueError('please provide an email')
        email = self.normalize_email(email)
        user = self.model(email=email,user_name = user_name, first_name=first_name, **other_fields )
        user.set_password(password)
        user.save()
        return user

My Html code

            <div class="pl-sm-4 pl-2" id="img-section">
                <form action="image" method="get">
                <input class="image" type="file" name="image"><br>
                <input type="submit" value="UPLOAD" class="upload"><br>
                </form>
            </div>

The error is as below


Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/image?image=IMG-20220529-WA0015.jpg

Django Version: 3.2
Python Version: 3.10.0
Installed Applications:
['cloth.apps.ClothConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'background_task']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\sudes\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__
    list_ = super().__getitem__(key)

During handling of the above exception ('image'), another exception occurred:
  File "C:\Users\sudes\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\sudes\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "E:\clotho\clotho\cloth\views.py", line 587, in image
    img = request.FILES['image']
  File "C:\Users\sudes\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /image
Exception Value: 'image'
0 Answers
Related