[英]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.