Search code examples
djangopython-3.7

'QueryDict' object has no attribute 'first_name'


Have AttributeError 'QueryDict' object has no attribute 'first_name' Get examples from here. I'm don't understand what is the problem

models.py

class Employee(models.Model):
    first_name = models.CharField(max_length=30)
    second_name = models.CharField(max_length=30)
    patronymic = models.CharField(max_length=30)
    birth_date = models.DateField()

views.py

def edit_employee_action(request, employee_id):
    if request.method == "POST":
        form = AddEmployeeForm(request.POST)
        if form.is_valid():
            edited = Employee.objects.filter(pk=employee_id)
            edited.update(
                first_name = request.POST.first_name,
                second_name = request.POST.second_name,
                patronymic = request.POST.patronymic,
                birth_date = request.POST.birth_date
            )
    else:
        form = AddEmployeeForm()
    form = AddEmployeeForm()
    return render(
        request,
        'edit_employee.html',
        context={'form': form}
    )

The parameter employee_id is correct (debugged).


Solution

  • You are using incorrectly the request.POST. It is actually a `dictionary. Try the following.

    def edit_employee_action(request, employee_id):
        if request.method == "POST":
            form = AddEmployeeForm(request.POST)
            if form.is_valid():
                edited = Employee.objects.filter(pk=employee_id)
                edited.update(
                    first_name = request.POST.get('first_name'),
                    second_name = request.POST.get('second_name'),
                    patronymic = request.POST.get('patronymic'),
                    birth_date = request.POST.get('birth_date')
                )
        else:
            form = AddEmployeeForm()
        form = AddEmployeeForm()
        return render(
            request,
            'edit_employee.html',
            context={'form': form}
        )
    

    This way even if the key does not exist you'll get a None value instead of an exception. Also be sure that the key values are the same in your template.