Django为隐藏字段内联formset增加了价值

时间:2017-12-13 02:13:04

标签: django django-forms

我正在使用Django 1.11。我试图在内联formset表单中添加一个隐藏字段的值。我尝试在def get_context_datadef form_valid的各个点插入隐藏字段值失败。我使用的代码如下:

views.py

@method_decorator(login_required, name='dispatch')
class DocumentCreate(CreateView):
    model = DocumentClient
    success_url = reverse_lazy('documents')
    form_class = DocumentForm

    def get_context_data(self, **kwargs):
        data = super(DocumentCreate, self).get_context_data(**kwargs)
        if self.request.POST:
            data['docform'] = DocumentFormSet(self.request.POST, self.request.FILES)
        else:
            data['docform'] = DocumentFormSet()
        return data

    def form_valid(self, form):
        context = self.get_context_data()
        docform = context['docform']
        if docform.is_valid():
            self.object = form.save()
            docform.instance = self.object
            docform.save()
            return HttpResponseRedirect('documents')
        else:
            return self.render_to_response(self.get_context_data(form=form))

forms.py

class DocumentForm(ModelForm):
    class Meta:
        model = DocumentClient
        exclude = ()
        widgets = {
            'cnum': HiddenInput(),
        }

    def __init__(self, *args, **kwargs):
        super(DocumentForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            self.fields['cnum'].required = False


class DocumentDetailForm(ModelForm):
    class Meta:
        model = DocumentDetail
        exclude = ()
        widgets = {
            'document_date': DateInput(),
                    }

    def __init__(self, *args, **kwargs):
        super(DocumentDetailForm, self).__init__(*args, **kwargs)
        self.fields['document_description'].required = False

DocumentFormSet = inlineformset_factory(DocumentClient, DocumentDetail, form=DocumentDetailForm, extra=10, can_delete=False)

隐藏字段'cnum'就是我想要在模型中插入值进行捕获的内容。有人能提供有关如何实现这一目标的任何指导吗?非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

class DocumentCreate(CreateView): def get_initial(self): # Get initial value from kwargs (If needed) and save as instance variable. self.cnum_val = self.kwargs.get('cnum_value') def form_valid(self, form): # Insert your desired value to cnum (or you can simply forget get_initial and supply whatever value here) form.instance.cnum = self.cnum_val self.object = form.save() ... self.render_to_response(self.get_context_data(form=form)) ,您试过这个吗?

form.instance

library(shiny) library(shinydashboard) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( tags$style(" body { -moz-transform: scale(0.8, 0.8); /* Moz-browsers */ zoom: 0.8; /* Other non-webkit browsers */ zoom: 80%; /* Webkit browsers */ } ") )) server <- function(input, output, session) {} shinyApp(ui, server) 指的是表单

使用的未保存模型对象

另见here