使用视图动态更新ModelForm的Meta类字段

时间:2016-03-22 11:07:18

标签: django django-forms django-views metaprogramming modelform

我在查看视图中的某些条件后尝试创建动态表单,我不知道如何处理它。如何从我的视图中填充表单Meta类中的fields属性?

以下是我的views.py和我的forms.py文件。

views.py

如何从我的视图中填充forms.py中的字段列表?

using System;
using System.Resources;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Configuration;
using VBIDE = Microsoft.Vbe.Interop;
using System.Runtime.InteropServices;
using System.IO;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Style;

    private void button1_Click(object sender, EventArgs e)
            {
                Excel.Application xlApp;
                Excel.Workbook xlWorkBook;
                Excel.Worksheet xlWorkSheet;
                object misValue = System.Reflection.Missing.Value;

                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Open(filePath.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


                foreach (Microsoft.Office.Interop.Excel.Worksheet wSheet in xlWorkBook.Worksheets)
                {
                    //Messagebox.show(wSheet.Name.ToString());
                    wSheet.SetBackgroundPicture("http://localhost/QA_red.png");


                }

                xlApp.Caption = "QA Tested";

                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();

                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
            }

private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

forms.py

我不知道该怎么做才能填充我的观点中的字段

    from django.shortcuts import render, get_object_or_404
    from django.http import HttpResponse
    from django import forms

    from .models import Master, Label, Assosiative
    from .forms import LabelForm, MzasterForm, AssosiativeForm

    def master(request,pk):
        associate = get_object_or_404(Assosiative, pk=pk)
        form = MasterForm(request.POST or None)
        if associate.short_text1 == 1:
            form.fields['short_text1'] = forms.CharField(label='Short text 1')
        if associate.short_text2 == 1:
            form.fields['short_text2'] = forms.CharField(label='Short text 2')
        if associate.short_text3 == 1:
            form.fields['short_text3'] = forms.CharField(label='Short text 3')
        if associate.short_text4 == 1:
            form.fields['short_text4'] = forms.CharField(label='Short text 4')
        if associate.num_field1 == 1:
            form.fields['num_field1'] = forms.CharField(label='Number field 1')
        if associate.num_field2 == 1:
            form.fields['num_field2'] = forms.CharField(label='Number field 2')
        if form.is_valid():
            try:
                short_text1 = form.cleaned_data['short_text1']
                short_text2 = form.cleaned_data['short_text2']
                short_text3 = form.cleaned_data['short_text3']
                short_text4 = form.cleaned_data['short_text4']
                num_field1 = form.cleaned_data['num_field1']
                num_field2 = form.cleaned_data['num_field2']
                form.save()
            except Exception, ex:
        return HttpResponse("Error %s" %str(ex))
        return render(request, 'master.html', {'form':form,}) 

2 个答案:

答案 0 :(得分:0)

this question中一样,您可以定义一个创建表单类的方法。查看您的视图,您似乎是基于associate逐个创建字段,而不是创建字段列表。因此,我会使用associate作为get_form_class方法的参数。

def get_form_class(fields_list):
    class MasterForm(ModelForm):
        class Meta:
            model = Master
            fields = fields_list
        ...
    return MasterForm

然后,在您的视图中,使用get_form动态创建表单类,然后实例化它。

def master(request, pk):
    associate = get_object_or_404(Assosiative, pk=pk)
    fields_list = []
    if associate.short_text1 == 1:
        fields_list.append('short_text1')
    if associate.short_text2 == 1:
        fields_list.append('short_text2')
    MasterForm = get_form_class(fields_list)
    form = MasterForm(request.POST or None)
    if form.is_valid():
        ...

答案 1 :(得分:0)

在检查某些条件后动态创建表单

views.py

    def master(request, pk):
        associate = get_object_or_404(Assosiative, pk=pk)
        MasterForm = get_form_class(associate)
        form = MasterForm(request.POST or None)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.INFO, 'Your Form has been posted successfully')
            return HttpResponseRedirect('/')
        return render(request, 'master.html', locals())

将表单字段动态添加到forms.py

中的字段列表类Meta
    def get_form_class(associate, *args, **kwargs):
        class MasterForm(forms.ModelForm):
            def __init__(self, *args, **kwargs):
                super(MasterForm,self).__init__(*args, **kwargs)
            class Meta:
                model = Master
                fields = [] #initialize an empty fields list
                # Append items to the fields list after checking some condition
                if associate.short_text1 == 1:
                    fields.append('short_text1')
                if associate.short_text2 == 1:
                    fields.append('short_text2')
                if associate.short_text3 == 1:
                    fields.append('short_text3')
                if associate.short_text4 == 1:
                    fields.append('short_text4')
                if associate.num_field1 == 1:
                    fields.append('num_field1')
                if associate.num_field2 == 1:
                    fields.append('num_field2')            
         return MasterForm