我设置了一个可以正常工作的CreateView。但是,当我将其中一个模型形式字段('erlaubte_pruefer')动态化时,将不再保存该对象。
我尝试了其他帖子中建议的许多解决方案,例如 -get user variable在get_form_kwargs()中, -在limit the field choices中使用get_form()代替forms.py -不要使用CreateView
但是我无法使其正常工作。我没有收到错误或异常,表单仅再次呈现。
非常感谢您的投入。谢谢!
forms.py
class Checklisten_Reinigung_Form(forms.ModelForm):
class Meta:
model = Checklisten_Reinigung
fields = ['okay',
'raum_verbindung',
'ausfuehrer',
'erlaubte_pruefer'
]
# user should only choose from those objects that were created by himself
def __init__(self, user, *args, **kwargs):
super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
self.fields['erlaubte_pruefer'].queryset =
Pruefer.objects.filter(firmenzugehoerigkeit=user)
views.py
class Checklisten_Reinigung_Create_View(LoginRequiredMixin, CreateView):
template_name = 'checklisten/checklisten_form.html'
def get_context_data(self, **kwargs):
context = super(Checklisten_Reinigung_Create_View,
self).get_context_data(**kwargs)
context['mymodel'] = Checklisten_Reinigung()
return context
# if I leave out get_form() the object is successfully saved
# but the user's choice is not limited
def get_form(self, form_class=None):
form = Checklisten_Reinigung_Form(user=self.request.user)
return form
def form_valid(self, form):
self.object = form.save(commit=False)
try:
self.object.pruefende_firma = self.request.user
self.object.bezeichnung = self.object.bezeichnung
self.object.ausfuehrer = form.cleaned_data['ausfuehrer']
self.object.erlaubte_pruefer =
form.cleaned_data['erlaubte_pruefer']
self.object.okay = form.cleaned_data['okay']
self.object.raum_verbindung= form.cleaned_data['raum_verbindung']
self.object.save()
return HttpResponseRedirect(self.get_success_url())
except:
messages.error(self.request, 'Es ist ein Fehler aufgetreten.')
return self.render_to_response(self.get_context_data(form=form(user=self.request.user)))
def get_success_url(self):
messages.success(self.request, 'Checkliste erfolgreich gespeichert.')
return reverse('checkliste-startseite')
编辑:
谢谢@Daniel Rosemann的回复。我将您的代码包含在我的代码中,但出现此错误:
Traceback:
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\base.py" in view
68. return self.dispatch(request, *args, **kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\contrib\auth\mixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\base.py" in dispatch
88. return handler(request, *args, **kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\edit.py" in get
168. return super().get(request, *args, **kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\edit.py" in get
133. return self.render_to_response(self.get_context_data())
File "C:\Users\Mars\Desktop\morecooking_now\morecooking_now\checklisten\views.py" in get_context_data
372. context = super(Checklisten_Reinigung_Create_View, self).get_context_data(**kwargs)
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\edit.py" in get_context_data
66. kwargs['form'] = self.get_form()
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\edit.py" in get_form
32. form_class = self.get_form_class()
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\edit.py" in get_form_class
93. model = self.get_queryset().model
File "C:\Users\Mars\Anaconda3\lib\site-packages\django\views\generic\detail.py" in get_queryset
73. 'cls': self.__class__.__name__
Exception Type: ImproperlyConfigured at /checklisten/reinigung/neu/
Exception Value: Checklisten_Reinigung_Create_View is missing a QuerySet. Define Checklisten_Reinigung_Create_View.model, Checklisten_Reinigung_Create_View.queryset, or override Checklisten_Reinigung_Create_View.get_queryset().
再次感谢您!
答案 0 :(得分:1)
您已经更改了表单的签名,因此第一个位置参数现在为user
,而不是data
。但是您已经将get_form
定义为仅通过user
,而永远不会通过data
;因此表单永远不会获取任何数据,因此永远不会有效。
改为给用户一个变态:</ p>
def __init__(self, *args, **kwargs): # no user here
user = kwargs.pop('user', None)
super(Checklisten_Reinigung_Form, self).__init__(*args, **kwargs)
self.fields['erlaubte_pruefer'].queryset =
Pruefer.objects.filter(firmenzugehoerigkeit=user)
,然后在视图中,删除您对get_form
的定义,而是定义get_form_kwargs
以通过用户:
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
还请注意,您在form_valid
中做的工作太多;对form.save
的调用已经在表格中设置了字段,例如“ erlaubte_pruefer”和“ okay”,因此您无需手动设置它们。
(最后,盲目地捕获所有错误并只返回模糊的“发生错误”消息是绝对没有用的。这隐藏了日志记录,该日志记录将告诉您发生了什么,并且不会给用户任何有用的信息。仅捕获您知道将要处理的错误;删除该try / except并让Django显示默认错误页面。)