3

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 ?

Amyth
  • 32,527
  • 26
  • 93
  • 135

3 Answers3

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

Q Caron
  • 952
  • 13
  • 26
Rohan
  • 52,392
  • 12
  • 90
  • 87
  • Hey Rohan, i am aware that it works with a ModelForm, sorry i forgot to mention that i am using a Custom form. Is there a work around for Custom Forms. ? – Amyth Nov 08 '12 at 09:54
  • @Amyth, I don't think it will work without defining a model form as suggested. Without that django framework will create form that requires `candidate` field as well, which is not present when you POST. – Rohan Nov 08 '12 at 10:19
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
  • 81
  • 1
  • 3
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.

Ankur Sethi
  • 3,508
  • 5
  • 23
  • 17
  • 1
    This is a bad idea: you should set such fields on the server side, e.g. in the view's POST. Users may submit a different user id and you just don't want that to happen. – Q Caron Sep 09 '16 at 08:12