我想使用django将图像保存在文件夹中,但出现此错误

时间:2019-10-28 12:34:27

标签: python django django-models django-forms django-views

我想使用django将图像保存在文件夹中,但出现此错误:

MultiValueDictKeyError at /lunchpk/signup/

我需要解决所有帮助,将得到帮助

我也看到了更多问题,但我没有得到正确的答案,所以请回答我的问题,不要将其添加到重复项中

这是我的views.py

def signup(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        profile_form = NewForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()

            profile = profile_form.save(commit=False)
            profile.user = user

            if 'Profile_Image' in request.FILES:
                profile.Profile_Image = request.FILES['profile_pics']
                # profile.Dish_Image = request.FILES['Dish_pic']

            profile.save()

            registered = True

        else:
            print(user_form.errors,profile_form.errors)
    else:
        user_form = UserForm()
        profile_form = NewForm()

    return render(request,'html/signup.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered})

这是我的model.py

class UserInfo(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)

    Profile_Image = models.ImageField(upload_to='profile_pics',null=True, blank=True)
    Dish_Image = models.ImageField(upload_to='Dish_pic',null=True, blank=True)
    Dish_Name = models.CharField(max_length=10,)

    def __str__(self):
        return self.user.username

这是我的forms.py

from django import forms
from django.contrib.auth.models import User
from .models import *

class UserForm(forms.ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    class Meta:
        model = User
        fields = ('username','email','password')

class NewForm(forms.ModelForm):

    class Meta:
        model = UserInfo
        fields = ('Profile_Image','Dish_Image','Dish_Name')

1 个答案:

答案 0 :(得分:1)

您正在请求request.FILES中的密钥'profile_pics',但它不存在。

在常规词典中,您会收到KeyError。但是,可以有多个具有相同名称的请求参数,因此Django使用了MultiValueDict,它具有自己的MultiValueDictKeyError。

我认为您希望使用request.FILES['Profile_Image']而不是request.FILES['profile_pics']