我正在尝试以编程方式设置电路的值,而不是在我的表单中这是一个选项。
我以前使用form_valid做过这个,但我刚刚意识到电路值是必需的,那么表单可能无效,无法将字段添加到?
目前,当我将form.errors输出到我的模板时,我需要获得电路字段
这是视图
class AddFile(CreateView):
form_class = FileForm
template_name = "circuits/file_form.html"
@method_decorator(user_passes_test(lambda u: u.has_perm('circuitfiles.add_file')))
def dispatch(self, *args, **kwargs):
self.site_id = self.kwargs['site_id']
self.circuit_id = self.kwargs['circuit_id']
self.refer = self.kwargs['refer']
self.site = get_object_or_404(SiteData, pk=self.site_id)
self.circuit = get_object_or_404(Circuits, pk=self.circuit_id)
return super(AddFile, self).dispatch(*args, **kwargs)
def get_success_url(self, **kwargs):
return reverse_lazy("circuits:edit_circuit", args=(self.circuit_id, self.site_id, self.refer))
def form_valid(self, form):
form.instance.circuit = self.circuit
return super(AddFile, self).form_valid(form)
def get_form_kwargs(self, *args, **kwargs):
kwargs = super().get_form_kwargs()
kwargs['is_add'] = True
return kwargs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['SiteID']=self.site_id
context['circuit_id']=self.circuit_id
context['circuit_name']='{} {}'.format(self.circuit.provider.provider,self.circuit.circuit_type.circuit_type)
context['SiteName']=self.site.location
context['refer']=self.refer
context['FormType']='Add'
context['active_circuits']='class="active"'
return context
这是表格:
class FileForm(forms.ModelForm): 类Meta: model = SiteFiles fields = ['site_image','site_file','file_name','file_type']
def __init__(self, *args, **kwargs):
super(FileForm, self).__init__(*args, **kwargs)
self.helper = FormHelper(self)
self.helper.form_id = 'file_form'
self.helper.form_method = 'POST'
self.helper.add_input(Submit('submit', 'Save', css_class='btn-primary'))
self.helper.layout = Layout(
Div(
Div(
Div(
Div(HTML('<i class="fa fa-camera-retro fa-fw"></i> Add File or Photo'), css_class='panel-heading'),
Div(
Field('site_image', placeholder='Image'),
Field('site_file', placeholder='File'),
Field('file_name', placeholder='Display Name'),
Div('file_type', title="File Type"),
css_class='panel-body'
),
css_class='panel panel-default',
),
css_class='col-lg-3'
),
css_class='row'
),
)
答案 0 :(得分:0)
class FileForm(forms.Form):
circuit = forms.WhateverField(required=False)
def save(self, *args, **kwargs):
circuit_value = my_value
# or circuit_value = kwargs.pop('my_key')
if not circuit_value:
raise SomeError
self.circuit = circuit_value
super(MakeATransferForm, self).__save__(*args, **kwargs)
class AddFile(CreateView):
...
def post/dispatch():
self.form.save(my_key=self.circuit)