Django在课堂上订购代码

时间:2013-04-18 08:45:48

标签: python django django-forms

我需要一个更好的解决方案来解决我在下面尝试实现的目标。我有一个表单,此表单需要指定以下项目的代码的顺序...

class ContactCSVModel(CsvModel):
    first_name = CharField()
    last_name = CharField()
    company = CharField()
    mobile = CharField()
    group = DjangoModelField(Group)
    contact_owner = DjangoModelField(User)

例如......

  class ContactCSVModel(CsvModel):
    if form.col1.value == "first_name":
        first_name = CharField()
    elif form.col1.value == "last_name":
        last_name = CharField()

或者

  class ContactCSVModel(CsvModel):
         [column.col1.value] = CharField()
         [column.col2.value] = CharField()

但是这不会起作用,因为它会尝试分配值而不是使它成为first_name = CharField()等

正如你所看到的那样,我最终会再次为col2,col3等做这件事,最后得到'if strong'的'很多'。

有更好的方法,例如?

感谢。

Forms.py

COL_CHOICES = [
    ('NONE', 'No Import'),
    ('first_name', 'First Name'),
    ('last_name', 'Last Name'),
    ('company', 'Company'),
    ('mobile', 'Mobile Number'),
    ('email', 'Email Address'),
    ]


class ConfiguratorForm(forms.Form):
    col1 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col2 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col3 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col4 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')
    col5 = forms.TypedChoiceField(choices=COL_CHOICES, initial='first_name')

这是我现在未修改过的课程:

def import_data(column, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        # IF column == x



        first_name = CharField()
        mobile = CharField()
        last_name = CharField()
        company = CharField()
        group = DjangoModelField(Group)
        contact_owner = DjangoModelField(User)

        class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}

    return ContactCSVModel.import_data(*args, **kw)

1 个答案:

答案 0 :(得分:3)

之后可以将字段添加到模型中,例如:

class ContactCSVModel(CsvModel):
    pass

for form_field in form:
    field_name = form_field.value
    model_field = CharField()
    model_field.contribute_to_class(ContactCSVModel, field_name)

例如(使用Django 1.5):

from django.db import models 

class ContactCSVModel(models.Model): 
    pass 

for field_name in ('first_name', 'mobile', 'last_name'): 
    model_field = models.CharField() 
    model_field.contribute_to_class(ContactCSVModel, field_name) 

print [f.name for f in ContactCSVModel._meta.fields]

# prints:
[u'id', 'first_name', 'mobile', 'last_name']