Django file field update causing error even though not required

◇◆丶佛笑我妖孽 提交于 2019-12-24 06:48:09

问题


I have an app that serves to update certain fields of a model. There are 4 possible fields that could be updated: resolution, upload4, upload5, and upload6. The upload fields are NOT required. If I do not include the request.FILES line, the uploaded file will not be saved to the database, but it seems like because I've included it, I need to always upload the 3 files, even though they are not required. The exception I am getting is "MultiValueDictKeyError" on the POST. How can I fix this? I want the option to add 3 files, but I don't want to have to every time. I understand how to make a field not required, I don't know how to code the request.FILES to understand that it is not required.

views.py

@login_required(login_url='/login/')
def report(request, case_id):

    form = ReportForm()
    case = get_object_or_404(Incident, pk=case_id)

    # if this is a POST request we need to process the form data            
    if request.POST:

        # create a form instance and populate it with the data from the request:
        form = ReportForm(request.POST)

        if form.is_valid():
            resolution = (form.cleaned_data['resolution'])      # grabbing action_taken from user input
            case.resolution = resolution
            case.upload4 = request.FILES['upload4']
            case.upload5 = request.FILES['upload5']
            case.upload6 = request.FILES['upload6']
            case.status = Status.objects.get(status='closed')
            case.save(update_fields=['resolution', 'status', 'upload4', 'upload5', 'upload6'])
            context = { 'case': case,
                        'form': form}
            return HttpResponseRedirect(reverse('dashboard_app:dashboard'))

    template = "report.html"
    #form = CaseForm()
    context = { 'case': case,
                'form': form}   

    return render(request, template, context)

回答1:


The point is that you are ignoring the validation that form does, and going straight back to the data from the request. So, yes, that will break if the forms are not there. But this is exactly why we use forms.

case.upload4 = form.cleaned_data['upload4']

etc.

It would be even easier if you used a ModelForm; then you could pass case as the instance argument of the form, and just do form.save(), replacing almost all the code inside your is_valid block.




回答2:


This will solve the problem.

case.upload4 = request.FILES.get('upload4')
case.upload5 = request.FILES.get('upload5')
case.upload6 = request.FILES.get('upload6')


来源:https://stackoverflow.com/questions/37171746/django-file-field-update-causing-error-even-though-not-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!