How do I set user field in form to the currently logged in user?

前端 未结 2 987
夕颜
夕颜 2020-12-04 18:24

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 electi

2条回答
  •  忘掉有多难
    2020-12-04 19:06

    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())
      

提交回复
热议问题