Django form.is_valid() is incorrectly returning false for a missing field

When I submit a form to update a task in my project, the is_valid function returns false, and on the page it says: Error! Please correct the following errors: Description: This field is required.

But when I print the POST request into the console, the description field isn't required, and it does have data.

this is the views.py function:

def task_edit(request, task_id, slug):
    """
    Display an individual task for editing.
    """
    # Retrieve the task instance
    task = get_object_or_404(Task, pk=task_id)
    # Retrieve the job instance
    job = get_object_or_404(Job, slug=slug)
    
    if request.method == "POST":
        # Print out the request.POST dictionary to inspect the data
        print(request.POST)
        
        # Initialize form with task instance and data from request
        add_task_form = AddTaskForm(data=request.POST, instance=task)
        
        if add_task_form.is_valid():
            # Save the form data to the task instance
            task = add_task_form.save(commit=False)
            task.job = job
            task.save()
            messages.success(request, 'Task Updated!')
            return HttpResponseRedirect(reverse('job_detail', args=[slug]))
        else:
            messages.error(request, 'Error updating task!')
    else:
        # Initialize form with task instance
        add_task_form = AddTaskForm(instance=task)

and this is the JS function:

// Handle click event for edit button
$(".edit-button").on("click", function() {
    console.log("Edit Task button clicked");

    var taskId = $(this).data("task_id");
    
    var description = $(this).data("description");
    var tradesRequired = $(this).data("trades-required");
    var tradesmanAssigned = $(this).data("tradesman-assigned");
    var timeRequired = $(this).data("time-required");
    var isCompleted = $(this).data("is-completed");
    var slug = $(this).data("slug");
    console.log(taskId);
    console.log(slug);
    console.log("Trades Required:", tradesRequired);

    // Populate the add_task_form fields with task details
    $("#id_form-0-description").val(description);
    // For trades_required, set the checkboxes based on the received data
    setTradesCheckboxes(tradesRequired);
    $("#id_form-0-tradesman_assigned").val(tradesmanAssigned);
    $("#id_form-0-time_required").val(timeRequired);
    // Set the is_completed checkbox based on the data
    $("#id_form-0-is_completed").prop("checked", isCompleted === "True");

    // Change the submit button name to indicate editing the task
    $("button[type='submit']").attr("name", "edit_task");
    $("button[type='submit']").addClass( "btn-edit" );
    // Show the add_task_form
    $("#add_task_form").show();
    addTaskButton.hide();
    editButtons.innerText = "Update";
    var url = `/tradesman/${slug}/edit_task/${taskId}/`;
    console.log("Edit URL:", url);
    taskForm.attr("action", `edit_task/${taskId}/`);
});

and this is the forms.py code:

class AddTaskForm(forms.ModelForm):
    class Meta:
        model = Task
        fields = ('id', 'description', 'trades_required', 'time_required', 'is_completed')

request.post:

<QueryDict: {'csrfmiddlewaretoken': ['q5VHJpmQ9NASbSjMsfnilC2H1uwgsF61yoQVlvWOje9pNIumBHLRmVY5OLJ7WwJt'], 'form-TOTAL_FORMS': ['1'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-description': ['Remove old worktop'], 'form-0-trades_required': ['Ca'], 'form-0-time_required': ['1 hour'], 'form-0-id': [''], 'edit_task': ['']}>

add_task_form.form.errors:

Error! Please correct the following errors: Description: This field is required.

I am new to programming and Django. Please feel free to ask for any more information!

I have tried to turn the requirement off for all fields in the form, but then when I click submit, the whole task gets cleared of any data.

Back to Top