ValueError while updating form
Published: 2020-08-10 13:00:29

I want to update an object using UpdateView in django. The update was working until I used inline formset. After using this, the weird problem is happening.

views.py:

    class EmployeeUpdateView(LoginRequiredMixin, UpdateView):
        """
        Update a created a employee
        """
    
        login_url = '/authentication/login/'
        template_name = 'employee/employee_update_form.html'
        form_class = EmployeeAddModelForm
        # work_form_class = WorkExperienceForm
        # education_form_class = EducationForm
        work_formset_class = WorkExperienceFormset
        education_formset_class = EducationFormset
        queryset = Employee.objects.all()
    
        # Override default get method
        def get(self, request, *args, **kwargs):
            id_ = self.kwargs.get("id")
            employee = Employee.objects.get(id=id_)
            # work_info = WorkExperience.objects.get(employee=employee)
            # education_info = Education.objects.get(employee=employee)
    
            form = self.form_class(instance=employee)
            # work_form = self.work_form_class(prefix='work_form', instance=work_info)
            # education_form = self.education_form_class(prefix='education_form',instance=education_info)
            work_formset = self.work_formset_class(request.GET or None, instance=employee)
            education_formset = self.education_formset_class(request.GET or None, instance=employee)
    
            print("Employee ID: ", employee)
    
            return render(request, self.template_name, {
                                                        'form': form,
                                                        'work_formset': work_formset,
                                                        'education_formset': education_formset,
                                                        'supervisor_assigned': employee.supervisor_select
                                                        }
                                                    )
        # Override default post method
        def post(self, request, *args, **kwargs):
            id_ = self.kwargs.get("id")
            employee = Employee.objects.get(id=id_)
            # work_info = WorkExperience.objects.get(employee=employee)
            # education_info = Education.objects.get(employee=employee)
    
            form = self.form_class(request.POST, instance=employee)
            # work_form = self.work_form_class(request.POST, prefix='work_form', instance=work_info)
            # education_form = self.education_form_class(request.POST, prefix='education_form',instance=education_info)
            work_formset = self.work_formset_class(request.POST, instance=employee)
            education_formset = self.education_formset_class(request.POST, instance=employee)
    
            # Check form validation
            if form.is_valid() and work_formset.is_valid() and education_formset.is_valid():
                instance = form.save()
                # Save work experience
                for work_form in work_formset:
                    work = work_form.save(commit=False)
                    work.employee_id = instance.id
                    work.save()
    
                # Save education experience
                for education_form in education_formset:
                    education = education_form.save(commit=False)
                    education.employee_id = instance.id
                    education.save()
    
                return redirect('employee:employee-list')
    
            return render(request, self.template_name, {
                                                        'form': form,
                                                        'work_formset': work_formset,
                                                        'education_formset': education_formset
                                                        }
                                                    )

When I press Update button in my update form, 'id' this field is required - error is giving. But 'id' is primary key and it is auto incremental, I can not pass this value. 

models.py:

    class Employee(models.Model):
        """
        Create employee attributes
        """
    
        employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, parent_link=True)
        e_id = models.IntegerField(unique=True, null=True)
        first_name = models.CharField(max_length=128, null=True)
        last_name = models.CharField(max_length=128, null=True) 
    
    class WorkExperience(models.Model):
        """
        Stores employee previous work experiences
        """
        #employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, parent_link=True)
        employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True)
        previous_company_name = models.CharField(max_length=128, null=True)
        job_designation = models.CharField(max_length=128, null=True)
        from_date = models.DateField(null=True)
        to_date = models.DateField(null=True)
        job_description = models.CharField(max_length=256, null=True)
    
    class Education(models.Model):
        """
        Stores employee education background
        """
        #employee_user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, parent_link=True)
        employee = models.ForeignKey('Employee', related_name='edu_employee', on_delete=models.CASCADE, null=True)
        institution_name = models.CharField(max_length=128, null=True)
        degree = models.CharField(max_length=128, null=True)
        passing_year = models.IntegerField(null=True)
        result = models.DecimalField(max_digits=5, decimal_places=2, null=True)

error message:

    ValueError: invalid literal for int() with base 10: 'None'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
        response = get_response(request)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
        response = self.process_exception_by_middleware(e, request)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\views\generic\base.py", line 71, in view
        return self.dispatch(request, *args, **kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\contrib\auth\mixins.py", line 52, in dispatch
        return super().dispatch(request, *args, **kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch
        return handler(request, *args, **kwargs)
      File "C:\Users\ZulkarNayem\Documents\nextgen-hrm\hrm\employee\views.py", line 429, in get
        employee = Employee.objects.get(id=id)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 404, in get
        clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 904, in filter
        return self._filter_or_exclude(False, *args, **kwargs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude
        clone.query.add_q(Q(*args, **kwargs))
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1351, in add_q
        clause, _ = self._add_q(q_object, self.used_aliases)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1378, in _add_q
        child_clause, needed_inner = self.build_filter(
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1312, in build_filter
        condition = self.build_lookup(lookups, col, value)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\sql\query.py", line 1166, in build_lookup
        lookup = lookup_class(lhs, rhs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\lookups.py", line 22, in __init__
        self.rhs = self.get_prep_lookup()
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\lookups.py", line 72, in get_prep_lookup
        return self.lhs.output_field.get_prep_value(self.rhs)
      File "C:\Users\ZulkarNayem\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value
        raise e.__class__(
    ValueError: Field 'id' expected a number but got 'None'.

How can I solve this issue? I think my query is not correct.

I have deleted all migration file and re migrated but same error occurs