簡體   English   中英

將 kwargs 從 CBV 傳遞到 Django 中的 Form

[英]Passing kwargs from CBV to Form in Django

我有一個ModelForm需要一個用戶傳入,以便可以更新查詢集。 我正在重寫ModelForm__init__方法,如下所示:

    def __init__(self, *args, **kwargs):
        #  override init to get user's casino's EmployeeType queryset
        self.user = kwargs.pop('user')
        print(self.user)
        super(MemoForm, self).__init__(*args, **kwargs)
        self.fields['receiver'].queryset = EmployeeType.objects.filter(
            casino=self.user.casino
        )

View中,我有一個get和一個post方法。 我正在嘗試這樣傳遞**kwargs

class VideoUploadView(LoginRequiredMixin, View):
    """
    Display a form for uploading videos.
    """

    form_class = VideoUploadForm
    success_url = '/videos'
    template_name = 'videos/video_upload.html'

    def get(self, request, *args, **kwargs):
        form = self.form_class()
        return render(
            request, 
            self.template_name,
            {'form': form, 'user': self.request.user}
        )

CreateView中,您可以使用get_form_kwargs方法傳入**kwargs 它是如何在普通View中完成的? 我們應該使用__init__方法嗎? 上面顯示的方式似乎不起作用,因為*args**kwargs似乎都是空的。

這些View的內置方法。

我真的不明白為什么你在這里也不使用 FormView ,所以你仍然可以覆蓋get_form_kwargs 你真的不應該直接定義get (或post )。

但是,答案很簡單:您只需將您的 kwargs 直接傳遞給表單:

form = self.form_class(user=request.user)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM