在下面的模型中,如何访问程序" CURRENT USER EMAIL ID"中提到的查询集中的当前用户详细信息。

时间:2018-05-21 07:37:02

标签: django

的ModelForm

class Build_kbform(ModelForm):   
  share_with=forms.ModelMultipleChoiceField(queryset=User.objects.filter
  (id__in=S etupuser.share_KB_with.through.objects.values_list
  ("user_id").filter(setupuser_id=Setupuser.objects.values_list
  ("id",flat=True).filter(email_id="CURRENT USER EMAIL ID")[0])) 
  ,widget=forms.CheckboxSelectMultiple)knowledge = forms.Textarea()
 class Meta:
    model=Buildkb
    exclude=["email"]

的FormView

class Build_Kb(FormView):
  template_name = "pkm_templates/buildkb.html"
  form_class = Build_kbform
  success_url = '/thanks/'
  def form_valid(self, form):
    share_with=form.cleaned_data.get("share_with")
    instance = Buildkb.objects.create(keywords=keywords)
    for user in share_with:
        instance.share_with.add(user)
        instance.save()
    return redirect("/")

我使用基于类的视图而不是基于函数的视图。有任何简单的方法来访问模型中的当前用户详细信息。我熟悉访问具有基于功能的视图的请求对象,但问题是基于类的视图。 我应该回到基于功能的观点。

1 个答案:

答案 0 :(得分:0)

您可以在Build_kbform中传递用户并覆盖其__init__方法,然后根据需要更新查询集。像这样:

# forms.py
class Build_kbform(ModelForm):
   # your fields here
   share_with = forms.ModelMultipleChoiceField(queryset=User.objects.all(), widget=forms.CheckboxSelect....)

   def __init__(self, *args, **kwargs):
      current_user = kwargs.pop('user', None)
      super(Build_kbform, self).__init__(*args, **kwargs)

      if current_user is not None:
         # Modify the queryset here as you see fit
         self.fields['share_with'].queryset = User.objects.filter(
             email_id=currentuser.email_id
         )

在您的视图中,您需要覆盖get_form_kwargs方法并传递当前用户。如下所示:

# views.py
class Build_Kb(FormView):

   def get_form_kwargs(self):
      kwargs = super(Build_Kb, self).get_form_kwargs()
      kwargs['user'] = self.request.user
      return kwargs

   def form_valid(self):
      # Your implementation here
      ...