Django MultiValueDictKeyError位于/ student_form

时间:2019-03-10 00:38:38

标签: django

我是Django的新手,我创建了一个模型并尝试从前端发布数据。 以下是我的view.py

def studentForm(request):
      userProfile = StudentProfileForm.objects.create(FirstName=request.POST['userFirstName'] LastName=request.POST['userLastName'], GreScore= request.POST['userGreScore'], IELTSTOEFL=request.POST['userIeltsToefl'],WorkEx=request.POST['userWorkEx'],ResearchDone=request.POST['userResearch'])
      userProfile.save()
      return render(request,'register/bg-pages.html')

以下是我的模特

class StudentProfileForm(models.Model):
    FirstName = models.CharField(max_length=255)
    LastName = models.CharField(max_length=255)
    GreScore = models.IntegerField()
    IELTSTOEFL = models.IntegerField()
    WorkEx = models.IntegerField()
    ResearchDone = models.IntegerField()

以下错误: 请求

Method: GET
Request URL:    http://127.0.0.1:8000/student_form
Django Version: 2.1.5
Exception Type: MultiValueDictKeyError
Exception Value:    
'userFirstName'
Exception Location: C:\Users\AB\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\datastructures.py in __getitem__, line 79
Python Executable:  C:\Users\AB\AppData\Local\Programs\Python\Python37-32\python.exe
Python Version: 3.7.1
Python Path:    
['D:\\AB\\UOR_everything\\semester_2(winter_2019)\\Software_Engineering\\login_registration',
 'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip',
 'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs',
 'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib',
 'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32',
 'C:\\Users\\AB\\AppData\\Roaming\\Python\\Python37\\site-packages',
 'C:\\Users\\AB\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages']
Server time:    Sun, 10 Mar 2019 00:35:51 +0000

1 个答案:

答案 0 :(得分:1)

如果缺少您的POST参数之一,除非将.get()与后备参数一起使用,否则将收到错误消息。另外,您在,方法中缺少.create()

示例:

name = request.POST.get('name', '')  # This will get the name value, or be an empty string if empty

尝试一下:

def studentForm(request):
    if request.METHOD == 'POST':  # This will protect you against GET requests
        first_name = request.POST.get('userFirstName', '')
        last_name = request.POST.get('userLastName', '')
        gre_score = request.POST.get('userGreScore', '')
        ieltstoefl = request.POST.get('userIeltsToefl', '')
        work_ex = request.POST.get('userWorkEx', '')
        research_done = request.POST.get('userResearch', '')

        # `userProfile.save()` is unnecessary bc `.create()` already does this
        userProfile = StudentProfileForm.objects.create(FirstName=first_name, LastName=last_name, GreScore=gre_score, IELTSTOEFL=ieltstoefl, WorkEx=work_ex, ResearchDone=research_done)

        return render(request,'register/bg-pages.html')