django“Key'up_file'在MultiValueDict中找不到:{}”

时间:2013-04-17 08:03:40

标签: django-models python-2.7

在我的htmlpage中,我有100个字段 我有一个上传文件的字段,对用户来说是可选的 当我提交所选文件的表格时,其他几个字段留空, 它被保存到db中。

同时当我尝试提交表单而不选择 要上传的文件,因为找不到“”键'up_file'而引发错误 在“”

- models.py -

class js_details(models.Model):
    user = models.ForeignKey(User, unique=True)
    fname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    dob = models.CharField(max_length=20, null=True)
    sec_email = models.EmailField(max_length=50, null=True)
    address1 = models.CharField(max_length=50, null=True)
    address2 = models.CharField(max_length=50, null=True)
    up_file = models.FileField(upload_to='documents', null=True)

- views.py -

def newpost(request):
if request.method == "POST":
        user_id = request.POST.get('user_id')

        fname= request.POST.get('fname')
        lastname= request.POST.get('lastname')
        dob = request.POST.get('dob')
        sec_email = request.POST.get('sec_email')
        address1 = request.POST.get('address1')
        address2 = request.POST.get('address2')
        up_file = request.FILES['up_file']
       p = js_details(user_id=user_id,fname=fname,lastname=lastname,dob=dob,sec_email=sec_email,address1=address1,address2=address2,up-file=up_file)
       p.save()

如何在没有填写文件字段的情况下保存表单。?

欢迎所有人的回答。 提前致谢。

1 个答案:

答案 0 :(得分:0)

严格回答您的问题:您正在请求使用下标访问.FILES(=> request.FILES['up_file']), which indeed raises a KeyError if there's no matchinh key. You should use request.FILES.get('up_file')and check the returned value which will beif the user didn't post a file. Read the Python's doc about映射and dict`了解有关这些数据类型的更多信息。

现在您的代码还有其他问题。第一个是你盲目地接受任何用户输入而没有验证,清理和数据类型转换。使用ModelForm可以解决此问题并简化代码。

另外,作为旁注,你应该坚持使用Django / Python命名约定并使用CapCase作为你的类名。

以下是您的代码的固定版本:

# models.py 
class JsDetails(models.Model):
    # ForeignKey -> OneToOneField, 
    # cf https://docs.djangoproject.com/en/1.4/ref/models/fields/#onetoonefield
    user = models.OneToOneField(User, unique=True)
    fname = models.CharField(max_length=50)
    lastname = models.CharField(max_length=50)
    # I assume "dob" means "date of birth"
    # so CharField -> DateField
    dob = models.DateField(blank=True, null=True)
    sec_email = models.EmailField(max_length=50, blank=True, null=True)
    address1 = models.CharField(max_length=50, blank=True, null=True)
    address2 = models.CharField(max_length=50, blank=True, null=True)
    up_file = models.FileField(upload_to='documents', blank=True, null=True)

# forms.py
from .models import JsDetail
from django import forms

class JsDetailForm(forms.ModelForm):
    class Meta:
        models = JsDetail

# views.py
from .forms import JsDetailForm 
from django.shortcuts import redirect, render

def newpost(request):
    if request.method == "POST":
        form = JsDetailForm(request.POST, request.FILES)
        if form.is_valid():
            newdetail = form.save()
            redirect("/somewhere/to/show/the/result")
        # if the form is not valid it will be redisplayed
        # to the user with error messages

    else:
        form = JsDetailForm()

    return render(
        request, 
        "your/template.htm",
        dict(form=form)
        ) 

此代码恕我直言仍有问题,但这仍然是一个改进。我非常强烈建议您花一些时间做Python教程和Django教程,它将为您节省大量的痛苦和麻烦。