# Automatically Foreign Key in Form. How??

**URL:** <https://forum.djangoproject.com/t/automatically-foreign-key-in-form-how/25546>\
**Category:** Forms & APIs\
**Created:** [November 22, 2023, 11:50am UTC](https://forum.djangoproject.com/t/automatically-foreign-key-in-form-how/25546 "2023-11-22T11:50:48Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![nimdagh](https://avatars.discourse-cdn.com/v4/letter/n/e274bd/32.png) [@nimdagh](https://forum.djangoproject.com/u/nimdagh)\
**Post date:** [November 25, 2023, 6:26am UTC](https://forum.djangoproject.com/t/automatically-foreign-key-in-form-how/25546/3 "2023-11-25T06:26:23Z")

</div>

Hello Sorry for late reply. I did as you said but it’s not working. Can you guide me. I am messing up in views I guess.

Views

```python
# Apply Views
class ApplyView(generic.edit.CreateView):
    form_class = forms.CandidateForm
    template_name = 'pages/Apply.html'
    slug_field = 'candidateid'
    slug_url_kwarg = 'candidateid'

    def get_initial(self, *args, **kwargs):
        initial = super(ApplyView, self).get_initial(**kwargs)
        initial['designation'] = self.kwargs['designation_id']  
        return initial

    def form_valid(self, form):
        form.instance.designation_jobid = self.kwargs['jobid']
        item = form.save()
        self.candidateid = item.candidateid
        return super(ApplyView, self).form_valid(form)

    def get_success_url(self):
        return reverse('applysuccess', kwargs={'candidateid': self.candidateid})

```

Urls

```python
    path('viewjobs/<slug:jobid>/apply', views.ApplyView.as_view(), name="apply"),

```

---

_[View the full topic](https://forum.djangoproject.com/t/automatically-foreign-key-in-form-how/25546)._
