0

I have a form

class EmployeeHistoryForm(forms.ModelForm):
    department = forms.ModelChoiceField(
        label="Подразделение",
        queryset=Department.objects.all()
        )
    post = forms.ModelChoiceField(
        label="Должность",
        queryset=Post.objects.all()
        )
    rank = forms.IntegerField(
        label="Разряд",
        validators=[
            MaxValueValidator(MAX_RANK),
            MinValueValidator(1)
        ])
    start_date = forms.DateField(
        label="Дата начала работы",
        initial=datetime.now().date()
        )

    class Meta:
        model = EmployeeHistory
        exclude = ['employee', 'end_date']

to model

class EmployeeHistory(models.Model):
    employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
    department = models.ForeignKey(Department, on_delete=models.CASCADE)
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    rank = models.IntegerField(
        validators=[
            MaxValueValidator(MAX_RANK),
            MinValueValidator(1)
        ]
    )
    start_date = models.DateField()
    end_date = models.DateField(blank=True, null=True)

employee field is filled from another form and I want to keep end_date None-typed for a while.

This is view:

def add_employee_action(request):
    if request.method == "POST":
        ...
        history_form = EmployeeHistoryForm(request.POST)
        if personal_form.is_valid() and history_form.is_valid():
            ...
            employee.save()

            history=EmployeeHistory(
                    employee=employee,
                    department=Department.objects.filter(
                        pk=request.POST['department']
                    )[0],
                    post=Post.objects.filter(
                        pk=request.POST['post']
                    )[0],
                    rank=request.POST['rank'],
                    start_date=datetime.now().date(),
                    end_date=None
                )
            history.save()
    else:
        ...
        history_form = EmployeeHistoryForm()
    return render(
        request,
        'add_employee.html',
        context={
            ...
            'history_form': history_form,
            }
    )

But when I submit the form have a django.db.utils.IntegrityError: null value in column "end_date" violates not-null constraint DETAIL: Failing row contains (7, 12, 2019-10-26, null, 1, 10, 1). I'm using PostgreSQL.

Note: I've added blank=True, null=True after first migration, then migrate again. May be this will importaint.

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27

1 Answers1

1

According to this question I should keep only null=True. It works!

Pavel Antspovich
  • 1,111
  • 1
  • 11
  • 27
  • I would love some further explanation for this. I am getting the same error, but see nowhere on the linked page that the DateField should be set to only null=True, and when I do so I get the same error. – FlamePrinz Nov 10 '20 at 18:44