[Django]-Django CreateView : Append ForeignKey to CustomForm Data

12👍

You will have to define a modelForm with candidate as excluded field and then set it in form_valid() method.

class ResumeForm(forms.ModelForm):
    class Meta:
        model = Resume
        exclude = ('candidate',)

class ResumeCreateView(CreateView):
    form_class = ResumeForm
    model = Resume

    def form_valid(self, form):
        form.instance.candidate = Candidate.objects.get(user=self.request.user)
        ....

More detailed reference at: Models and request.user

👤Rohan

2👍

I don’t have enough karma to comment but i just wanted to note that this worked for my problem & my only variation (on Rohan’s answer) was that i didn’t need to create a form.

class ChoiceCreateView(generic.CreateView):
model = Choice
template_name = 'polls/choice.html'
fields = ['choice_text']

instead i specify the fields i do want to show in my view rather than exclude them in a form. 🙂

👤ksmskm

1👍

I’ve run into this exact issue before. For a quick fix, include the candidate in your form using a hidden input, like so:

<input type="hidden" name="candidate" id="id_candidate" value="{{ request.user.id }}">

In the future, though, consider using django-crispy-forms instead of writing your forms by hand.

Leave a comment