# Using data from Foreign Key before final save of form.

**URL:** <https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799>\
**Category:** Using the ORM\
**Created:** [August 5, 2023, 10:25am UTC](https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799 "2023-08-05T10:25:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![PLR06157](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plr06157/32/14716_2.png) [@PLR06157](https://forum.djangoproject.com/u/PLR06157)\
**Post date:** [August 5, 2023, 10:25am UTC](https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799/1 "2023-08-05T10:25:03Z")

</div>

Hey!

I’m having a model to create position per employee in the company (to remain history of the given employee’s positions):

```auto
class EmployeePosition(models.Model):
    position_date_from = models.DateField(blank=True, null=True)
    position_date_to = models.DateField(blank=True, null=True)
    is_current_position = models.BooleanField(default=True)
    employee_position = models.ForeignKey(Position, on_delete=models.DO_NOTHING)
    employee_name = models.ForeignKey('Employee', on_delete=models.DO_NOTHING, blank=True, null=True, related_name='position')

```

I have following form for the model:

```auto
class EmployeePositionForm(ModelForm):
    class Meta:
        model = EmployeePosition
        fields = ['position_date_from', 'position_date_to', 'is_current_position', 'employee_position', 'employee_name']

```

When saving the new position I’m trying to verify if the previous position wasn’t closed, before starting the new position.

```auto
def create_employee_position(request):
    employee_position_form = EmployeePositionForm(request.POST or None)
    position_date_from = PositionDateFromForm(request.POST or None)
    position_date_to = PositionDateToForm(request.POST or None)
    if request.method == "POST":
        if employee_position_form.is_valid() and position_date_from.is_valid() and position_date_to.is_valid():
            selected_date_from = position_date_from.cleaned_data['position_date_from']
            selected_date_to = position_date_to.cleaned_data['position_date_to']
            employee_position_form.save(commit=False)
            print(f"employee_position_form.employee_name: {employee_position_form.employee_name}")
            employee_position_form.position_date_from = selected_date_from
            employee_position_form.position_date_to = selected_date_to
            positions = EmployeePosition.objects.all()
            for position in positions:
                if position.employee_name == employee_position_form.employee_name:
                    if position.position_date_to.blank:
                        return render(request, 'error_position.html', {'position': position})
                    else:
                        if position.position_date_to < employee_position_form.position_date_from:
                            employee_position_form.save()
                        else:
                            return render(request, 'error_position_date.html',
                                          {'position': position, 'employee_position_form': employee_position_form})
                else:
                    employee_position_form.save()

            return redirect(list_employee_positions)
        else:
            print(f"employee_position_form.errors: {employee_position_form.errors}")
            print(f"position_date_from.errors: {position_date_from.errors}")
            print(f"position_date_to.errors: {position_date_to.errors}")
    context = {
        'employee_position_form': employee_position_form,
        'position_date_from': position_date_from,
        'position_date_to': position_date_to,
    }

    return render(request, 'create_employee_position.html', context)

```

Unfortunately I’m getting following error from Django:  
`'EmployeePositionForm' object has no attribute 'employee_name'`

Apparently I do not understand some logic, or I’m missing something here. Why it says that attribute is not there while it is defined in the model and the form?

Thanks in advance for your support.

---

<div class="post-metadata">

**Author:** ![cehceh](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/cehceh/32/3415_2.png) [@cehceh](https://forum.djangoproject.com/u/cehceh)\
**Post date:** [August 5, 2023, 10:45am UTC](https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799/2 "2023-08-05T10:45:53Z")

</div>

The error in this line

```auto
print(f"employee_position_form.employee_name: {employee_position_form.employee_name}")

```

Try to make

```auto
for field in employee_position_form:
   print('My_Form_Fields_And_Errors::', field.name, field.errors)

```

You will get all fields of your Form with errors if any

Also to use it as you described in your code

> [@PLR06157](#):
>
> ```auto
> employee_position_form.position_date_from = selected_date_from
> employee_position_form.position_date_to = selected_date_to
> 
> ```

You have to do like this

```auto
if employee_position_form.is_valid():
     save_employee_position_form = employee_position_form.save(commit=False)
     save_employee_position_form.YOUR_FORM_FIELD = WHAT_YOU_WANT
     save_employee_position_form.save()
     # After saving Your_Form you can 
     save_employee_position_form.position_date_from = selected_date_from
     save_employee_position_form.position_date_to = selected_date_to

```

Hope it helps

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [August 5, 2023, 11:18am UTC](https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799/3 "2023-08-05T11:18:14Z")

</div>

> [@PLR06157](#):
>
> `'EmployeePositionForm' object has no attribute 'employee_name'`
> 
> Apparently I do not understand some logic, or I’m missing something here. Why it says that attribute is not there while it is defined in the model and the form?

The issue is that you’re trying to get a value from a bound field in a form - for that you need to use the `cleaned_data` attribute in the same way that you are using it to retrieve the values from the `position_date_from` and `position_date_to` forms.

Likewise, further down, when you do this:

> [@PLR06157](#):
>
> `employee_position_form.save(commit=False)`

that function call returns the instance of EmployeePosition being saved - it’s _that_ object that you need to perform further work on, not the `employee_position_form` object.

Review the docs and examples at [Creating forms from models | Django documentation | Django](https://docs.djangoproject.com/en/4.2/topics/forms/modelforms/#the-save-method)

---

<div class="post-metadata">

**Author:** ![PLR06157](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plr06157/32/14716_2.png) [@PLR06157](https://forum.djangoproject.com/u/PLR06157)\
**Post date:** [August 5, 2023, 7:27pm UTC](https://forum.djangoproject.com/t/using-data-from-foreign-key-before-final-save-of-form/22799/4 "2023-08-05T19:27:22Z")

</div>

Thank you very much!
