Django and stackoverflow noob here. I'm making an election information app, and I want to allow the currently logged-in user to be able to declare himself and only himself as a candidate in an election.

I'm using Django's built-in ModelForm and CreateView. My problem is that the Run for Office form (in other words, the 'create candidate' form) allows the user to select any user in the database to make a candidate.

I want the user field in the Run for Office to be automatically set to the currently logged-in user, and for this value to be hidden, so the logged-in user cannot change the value of the field to someone else.

views.py

class CandidateCreateView(CreateView):
    model = Candidate
    form_class = CandidateForm
    template_name = 'candidate_create.html'

    def form_valid(self, form):
        f = form.save(commit=False)
        f.save()
        return super(CandidateCreateView, self).form_valid(form)

forms.py

class CandidateForm(forms.ModelForm):
    class Meta:
        model = Candidate

models.py

class Candidate(models.Model):
    user = models.ForeignKey(UserProfile)
    office = models.ForeignKey(Office)
    election = models.ForeignKey(Election)
    description = models.TextField()

    def __unicode__(self):
        return unicode(self.user)

    def get_absolute_url(self):
        return reverse('candidate_detail', kwargs={'pk': str(self.id)})

Thanks for reading. I've been stuck on this problem a couple days now, and would really appreciate your help. If you need more info, please lemme know.

up vote 35 down vote accepted
  1. Remove user field from rendered form (using exclude or fields, https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#selecting-the-fields-to-use )

    class CandidateForm(forms.ModelForm):
        class Meta:
            model = Candidate
            exclude = ["user"]
    
  2. Find user profile and set user field in the create view.

    class CandidateCreateView(CreateView):
        ...
        def form_valid(self, form):
            candidate = form.save(commit=False)
            candidate.user = UserProfile.objects.get(user=self.request.user)  # use your own profile here
            candidate.save()
            return HttpResponseRedirect(self.get_success_url())
    
  • Dang, that was easy. I was trying things like "candidate.user = self.request.user" before, but obviously that doesn't work. This will come in handy for other forms I have to make, thanks a lot! – Mitch Downey Aug 15 '13 at 7:04
  • Why is candidate.user = self.request.user not a working ? Isn't self.request.user a user object too ? – tilaprimera Dec 20 '15 at 9:22
  • Because self.request.user is User instance, but Candidate.user is UserProfile instance. – nmb.ten Dec 21 '15 at 12:14
  • This approach will integrate user into form itself stackoverflow.com/questions/4141408/… – Igor Yalovoy Mar 8 '17 at 19:11
  • 1
    I am using crispy form. I have to changed the last line to 'return super(CanndidateCreateView, self).form_valid(form)' in order for the redirect to work. – Jason Ching May 14 '17 at 4:09

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.