led4966
led4966

Reputation: 49

Django file field update causing error even though not required

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)

Upvotes: 1

Views: 309

Answers (2)

Anoop
Anoop

Reputation: 1435

This will solve the problem.

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

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599856

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.

Upvotes: 1

Related Questions