Question

I have a CreateView as follows:

class ResumeCreateView(CreateView):
    model = Resume

    def form_valid(self, request, form):
        candidate = Candidate.objects.get(user=self.request.user)
        self.object = form.save(commit=False)
        self.object.candidate = candidate
        self.object.save()
        f = self.request.FILES.get('file')
        data = [{
            'title': self.request['title'],
            'name': f.name,
        }]  
        response = JSONResponse(data, {}, response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

here i am trying to append the candidate instance to the Resume models candidate field which is a ForeignKey to the Candidate model.

But i always receive validation error {'candidate' : 'This field is required'}

  • I am using a custom form not a model form as it uses twitter bootstrap identifiers.

what am i missing ?

Was it helpful?

Solution

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

OTHER TIPS

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. :)

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top