Django 用ModelForm批量保存form表单(非常实用的方法) mfor_verity项目

1.先看一下 Model 非常多

from django.db import models
from users.models import UserProfile


# Create your models here.
class Edc_Project(models.Model):
    project_name = models.CharField(max_length=200, verbose_name="项目名称", default="")
    project_number = models.CharField(max_length=200,verbose_name="项目编号", default="")
    project_user = models.ForeignKey(UserProfile,verbose_name='项目负责人')
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "EDC项目信息"
        verbose_name_plural = verbose_name


class Edc_Center(models.Model):
    center_name = models.CharField(max_length=200, verbose_name="中心名称", default="")
    center_number = models.CharField(max_length=200,verbose_name="中心编号", default="")
    center_user = models.ManyToManyField(UserProfile, verbose_name='中心负责人')
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "EDC中心信息"
        verbose_name_plural = verbose_name


class Edc_Patient(models.Model):
    patient_number = models.CharField(max_length=200,verbose_name="患者编号", default="")
    patient_user = models.ForeignKey(UserProfile, verbose_name='患者负责人',null=True,blank=True)
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "EDC患者信息"
        verbose_name_plural = verbose_name


class Edc_Visit(models.Model):
    visit_name = models.CharField(max_length=200, verbose_name="访视名称", default="")
    visit_number = models.CharField(max_length=200,verbose_name="访视编号", default="")
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "EDC访视信息"
        verbose_name_plural = verbose_name


class Edc_Form(models.Model):
    form_name = models.CharField(max_length=200, verbose_name="表单名称", default="")
    form_number = models.CharField(max_length=200,verbose_name="表单缩写", default="")
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "EDC表单信息"
        verbose_name_plural = verbose_name




class Dr(models.Model):
    """
    发药纪录
    """
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    dr_center = models.ForeignKey(Edc_Center, verbose_name='发药纪录_中心')
    dr_patient = models.ForeignKey(Edc_Patient,verbose_name='发药纪录_病人')
    dr_visit = models.ForeignKey(Edc_Visit, verbose_name='发药纪录_访视')
    date_delivery = models.DateTimeField(verbose_name='发药日期',blank=True, null=True)
    drugs_name = models.CharField(verbose_name='药品名称',max_length=50, blank=True, null=True)
    dose = models.CharField(verbose_name='剂量',max_length=50, blank=True, null=True)
    dosage_form = models.CharField(verbose_name='剂型', max_length=50, blank=True, null=True)
    sign_drug_name = models.CharField(verbose_name='领药人签字', max_length=50, blank=True, null=True)
    drug_user_name = models.CharField(verbose_name='发药人签字', max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "发药纪录"
        verbose_name_plural = verbose_name



# class DrSelect(models.Model):
#     """
#     发药纪录的药品名称和剂量等
#     """
#     id = models.IntegerField(db_column='ID', blank=True, null=True)
#     druge = models.CharField(db_column='DRUGE', max_length=1000, blank=True, null=True)
#     dose = models.CharField(db_column='DOSE', max_length=1000, blank=True, null=True)
#     form = models.CharField(db_column='FORM', max_length=1000, blank=True, null=True)
#
#     class Meta:
#         managed = False
#         db_table = 'DR_SELECT'


class Eg(models.Model):
    """
    本次实验室检测结果
    """
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    eg_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    eg_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    eg_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    date_collection = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    eg_cd4 = models.CharField(verbose_name='CD4',max_length=50, blank=True, null=True)
    eg_cd8 = models.CharField(verbose_name='CD8',max_length=50, blank=True, null=True)
    hiv_viral_load = models.CharField(verbose_name='HIV病毒载量',max_length=50, blank=True, null=True)
    leucocyte_count = models.CharField(verbose_name='白细胞计数',max_length=50, blank=True, null=True)
    total_lymphocyte = models.CharField(verbose_name='总淋巴细胞计数',max_length=50, blank=True, null=True)
    platelet_count = models.CharField(verbose_name='血小板计数',max_length=50, blank=True, null=True)
    eg_hemoglobin = models.CharField(verbose_name='血红蛋白',max_length=50, blank=True, null=True)
    serum_creatinine = models.CharField(verbose_name='血肌酐',max_length=50, blank=True, null=True)
    urea_nitrogen = models.CharField(verbose_name='血尿素氮',max_length=50, blank=True, null=True)
    eg_triglyceride = models.CharField(verbose_name='甘油三酯',max_length=50, blank=True, null=True)
    total_cholesterol = models.CharField(verbose_name='总胆固醇',max_length=50, blank=True, null=True)
    blood_sugar = models.CharField(verbose_name='血糖',max_length=50, blank=True, null=True)
    blood_amylase = models.CharField(verbose_name='血淀粉酶',max_length=50, blank=True, null=True)
    alanine_alt = models.CharField(verbose_name='谷丙转氨酶ALT',max_length=50, blank=True, null=True)
    aspertate_alt = models.CharField(verbose_name='谷草转氨酶AST',max_length=50, blank=True, null=True)
    bilirubin_bil = models.CharField(verbose_name='总胆红素T.BIL',max_length=50, blank=True, null=True)
    eg_hbsag = models.CharField(verbose_name='HBsAg',max_length=50, blank=True, null=True)
    eg_antihcv = models.CharField(verbose_name='anti-HCV',max_length=50, blank=True, null=True)
    drug_resistance = models.CharField(verbose_name='耐药性检测',max_length=50, blank=True, null=True)
    resistance_name = models.CharField(verbose_name='耐药药物名称',max_length=50, blank=True, null=True)

    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "本次实验室检测结果"
        verbose_name_plural = verbose_name


class Ggn(models.Model):
    '''
    肝功能
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    ggn_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    ggn_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    ggn_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采集日期',blank=True, null=True)
    alanine_alt = models.CharField(verbose_name='谷丙转氨酶ALT',max_length=50, blank=True, null=True)
    aspertate_alt = models.CharField(verbose_name='谷草转氨酶AST',max_length=50, blank=True, null=True)
    bilirubin_bil = models.CharField(verbose_name='总胆红素T.BIL',max_length=50, blank=True, null=True)
    direct_bilirubin = models.CharField(verbose_name='直接胆红素(DBIL)',max_length=50, blank=True, null=True)
    total_protein = models.CharField(verbose_name='血清总蛋白(TP)',max_length=50, blank=True, null=True)
    serum_albumin = models.CharField(verbose_name='血清白蛋白(ALB)',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "肝功能"
        verbose_name_plural = verbose_name


class Ncg(models.Model):
    '''
    尿常规
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    ncg_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    ncg_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    ncg_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采集日期',blank=True, null=True)
    acidity_alkalinity = models.CharField(verbose_name='酸碱度(pH)',max_length=50, blank=True, null=True)
    specific_gravity = models.CharField(verbose_name='尿比重(SG)',max_length=50, blank=True, null=True)
    bile_proto = models.CharField(verbose_name='尿胆原(URO)',max_length=50, blank=True, null=True)
    occult_blood = models.CharField(verbose_name='隐血(BLO)',max_length=50, blank=True, null=True)
    ncg_leukocyte = models.CharField(verbose_name='白细胞(WBC)',max_length=50, blank=True, null=True)
    ucg_protein = models.CharField(verbose_name='尿蛋白(PRO)',max_length=50, blank=True, null=True)
    ncg_niaotang = models.CharField(verbose_name='尿糖(GLU)',max_length=50, blank=True, null=True)
    ncg_bilirubin = models.CharField(verbose_name='胆红素(BIL)',max_length=50, blank=True, null=True)
    ncg_ketone = models.CharField(verbose_name='酮体(KET)',max_length=50, blank=True, null=True)
    red_blood = models.CharField(verbose_name='尿红细胞(RBC)',max_length=50, blank=True, null=True)
    urine_colour = models.CharField(verbose_name='尿液颜色(GOL)',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "尿常规"
        verbose_name_plural = verbose_name


class Sxqgn(models.Model):
    '''
    肾小球功能
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    sxqgn_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    sxqgn_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    sxqgn_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    serum_creatinine = models.CharField(verbose_name='血肌酐',max_length=50, blank=True, null=True)
    urea_nitrogen = models.CharField(verbose_name='血尿素氮',max_length=50, blank=True, null=True)
    uric_acid = models.CharField(verbose_name='血尿酸(UA)',max_length=50, blank=True, null=True)
    serum_cystatin = models.CharField(verbose_name='血清胱抑素C(CysC)',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "肾小球功能"
        verbose_name_plural = verbose_name


class Tr(models.Model):
    '''
    本次抗毒治疗治疗处方
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    tr_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    tr_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    tr_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    drugs_name = models.CharField(verbose_name='药品名称',max_length=50, blank=True, null=True)
    unit_dose = models.CharField(verbose_name='单位剂量',max_length=50, blank=True, null=True)
    single_dosage = models.CharField(verbose_name='单次用药量',max_length=50, blank=True, null=True)
    method_taking = models.CharField(verbose_name='服用方法',max_length=50, blank=True, null=True)
    dose_hair = models.CharField(verbose_name='发药量',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "本次抗毒治疗治疗处方"
        verbose_name_plural = verbose_name


class V1A(models.Model):
    '''
    V1A
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    v1a_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    v1a_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    v1a_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    agency_code = models.CharField(verbose_name='治疗机构代码',max_length=50, blank=True, null=True)
    treatment_number = models.CharField(verbose_name='抗病毒治疗号',max_length=50, blank=True, null=True)
    antiviral_therapy = models.CharField(verbose_name='抗病毒治疗类型',max_length=50, blank=True, null=True)
    treatment_code = models.CharField(verbose_name='病人治疗编码',max_length=50, blank=True, null=True)
    card_number = models.CharField(verbose_name='传染病报告卡卡片编号',max_length=50, blank=True, null=True)
    birth_date = models.CharField(verbose_name='出生日期',max_length=50, blank=True, null=True)
    v1a_sex = models.CharField(verbose_name='性别',max_length=50, blank=True, null=True)
    source_treatment = models.CharField(verbose_name='抗病毒治疗费用来源',max_length=50, blank=True, null=True)
    sources_cost = models.CharField(verbose_name='其他费用来源',max_length=50, blank=True, null=True)
    marital_status = models.CharField(verbose_name='婚姻状况',max_length=50, blank=True, null=True)
    hiv_time = models.CharField(verbose_name='确诊HIV抗体阳性时间',max_length=50, blank=True, null=True)
    infection_pathway = models.CharField(verbose_name='感染途径',max_length=50, blank=True, null=True)
    year_tuberculosis = models.CharField(verbose_name='近一年是否患肺结核',max_length=50, blank=True, null=True)
    patient_phthisis = models.CharField(verbose_name='病人是否接受抗结核治疗',max_length=50, blank=True, null=True)
    aids_symptom = models.CharField(verbose_name='近三个月是否出现下列艾滋病相关病症',max_length=50, blank=True, null=True)
    related_diseases = models.CharField(verbose_name='相关疾病/症状',max_length=50, blank=True, null=True)
    other_diseases = models.CharField(verbose_name='其它机会性感染/肿瘤',max_length=50, blank=True, null=True)
    below_diseases = models.CharField(verbose_name='目前病人是否出现以下症状、体征',max_length=50, blank=True, null=True)
    v1a_diseases = models.CharField(verbose_name='症状、体征',max_length=50, blank=True, null=True)
    clinical_stages = models.CharField(verbose_name='目前临床病人WHO临床分期',max_length=50, blank=True, null=True)
    v1a_weight = models.CharField(verbose_name='病人目前体重',max_length=50, blank=True, null=True)
    v1a_height = models.CharField(verbose_name='身高',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "V1A"
        verbose_name_plural = verbose_name


class V1C(models.Model):
    '''
    V1C
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    v1c_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    v1c_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    v1c_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    scheme_antivira = models.CharField(verbose_name='既往接受过几种方案的抗病毒治疗',max_length=50, blank=True, null=True)
    antiviral_name = models.CharField(verbose_name='曾使用的抗病毒药物名称',max_length=50, blank=True, null=True)
    prevent_infect = models.CharField(verbose_name='是否接受过复方新诺明预防机会性感染治疗',max_length=50, blank=True, null=True)
    whether_take = models.CharField(verbose_name='目前是否仍在服用',max_length=50, blank=True, null=True)
    whether_adanon = models.CharField(verbose_name='目前是否使用美沙酮',max_length=50, blank=True, null=True)
    date_antitoxic = models.CharField(verbose_name='抗毒治疗开始日期',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "V1C"
        verbose_name_plural = verbose_name


class V2A(models.Model):
    '''
    V2A
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    v2a_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    v2a_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    v2a_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    patient_died = models.CharField(verbose_name='病人是否死亡或转出',max_length=50, blank=True, null=True)
    cause_termination = models.CharField(verbose_name='终止原因',max_length=50, blank=True, null=True)
    date_death = models.CharField(verbose_name='死亡日期',max_length=50, blank=True, null=True)
    cause_death = models.CharField(verbose_name='死亡原因',max_length=50, blank=True, null=True)
    transfer_date = models.CharField(verbose_name='转出日期',max_length=50, blank=True, null=True)
    flup_content = models.CharField(verbose_name='本次随访内容',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "V2A"
        verbose_name_plural = verbose_name


class V2B(models.Model):
    '''
    v2b
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    v2b_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    v2b_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    v2b_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    clinical_stages = models.CharField(verbose_name='目前病人WHO临床分期',max_length=50, blank=True, null=True)
    aids_disease = models.CharField(verbose_name='自上次访视,是否出现过以下艾滋病相关病症',max_length=50, blank=True, null=True)
    skin_damage = models.CharField(verbose_name='皮肤损害',max_length=50, blank=True, null=True)
    disposal_method = models.CharField(verbose_name='处置方式',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "V2B"
        verbose_name_plural = verbose_name


class V2D(models.Model):
    '''
    V2D
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    v2d_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    v2d_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    v2d_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    infection_treatment = models.CharField(verbose_name='是否接受过复方新诺明预防机会性感染治疗',max_length=50, blank=True, null=True)
    if_adanon = models.CharField(verbose_name='目前是否使用美沙酮',max_length=50, blank=True, null=True)
    clinical_disposal = models.CharField(verbose_name='临床处置',max_length=50, blank=True, null=True)
    change_medicine = models.CharField(verbose_name='换药原因',max_length=50, blank=True, null=True)
    other_dressing = models.CharField(verbose_name='其他换药原因',max_length=50, blank=True, null=True)
    change_reaction = models.CharField(verbose_name='换药具体副反应',max_length=50, blank=True, null=True)
    cause_drug = models.CharField(verbose_name='停药原因',max_length=50, blank=True, null=True)
    other_drug = models.CharField(verbose_name='其他停药原因',max_length=50, blank=True, null=True)
    change_drug = models.CharField(verbose_name='停药具体副反应',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)



    class Meta:
        verbose_name = "V2D"
        verbose_name_plural = verbose_name


class Xcg(models.Model):
    '''
    血常规
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    xcg_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    xcg_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    xcg_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    leucocyte_count = models.CharField(verbose_name='白细胞计数',max_length=50, blank=True, null=True)
    lymphocyte_count = models.CharField(verbose_name='总淋巴细胞计数',max_length=50, blank=True, null=True)
    platelet_count = models.CharField(verbose_name='血小板计数',max_length=50, blank=True, null=True)
    xcg_hemoglobin = models.CharField(verbose_name='血红蛋白',max_length=50, blank=True, null=True)
    neutrophil_count = models.CharField(verbose_name='中性粒细胞计数',max_length=50, blank=True, null=True)
    red_number = models.CharField(verbose_name='红细胞总数',max_length=50, blank=True, null=True)
    red_volume = models.CharField(verbose_name='平均红细胞容积',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "血常规"
        verbose_name_plural = verbose_name


class Xdfm(models.Model):
    '''
    血淀粉酶
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    xdfm_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    xdfm_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    xdfm_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    blood_amylase = models.CharField(verbose_name='血淀粉酶',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "血淀粉酶"
        verbose_name_plural = verbose_name


class Xt(models.Model):
    '''
    血糖
    '''
    formame = models.CharField(verbose_name='Modelform名称',max_length=50, blank=True, null=True)
    xt_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    xt_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    xt_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    blood_sugar = models.CharField(verbose_name='血糖',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = "血糖"
        verbose_name_plural = verbose_name


class Xzsx(models.Model):
    '''
    血脂四项
    '''
    formame = models.CharField(verbose_name='Modelform名称', max_length=50, blank=True, null=True)
    xzsx_center = models.ForeignKey(Edc_Center, verbose_name='中心')
    xzsx_patient = models.ForeignKey(Edc_Patient,verbose_name='病人')
    xzsx_visit = models.ForeignKey(Edc_Visit, verbose_name='访视')
    collection_date = models.DateTimeField(verbose_name='采血日期',blank=True, null=True)
    xzsx_triglyceride = models.CharField(verbose_name='甘油三酯',max_length=50, blank=True, null=True)
    total_cholesterol = models.CharField(verbose_name='总胆固醇',max_length=50, blank=True, null=True)
    low_lipoprotein = models.CharField(verbose_name='低密度脂蛋白',max_length=50, blank=True, null=True)
    high_lipoprotein = models.CharField(verbose_name='高密度脂蛋白',max_length=50, blank=True, null=True)
    add_time = models.DateTimeField(auto_now=True)


    class Meta:
        verbose_name = "血脂四项"
        verbose_name_plural = verbose_name
Model

 

2.ModelForm的定义

from django import forms
from django.forms import ModelForm
from .models import Dr,Eg,Ggn,Ncg,Sxqgn,Tr,V1A,V1C,V2A,V2B,V2D,Xcg,Xdfm,Xt,Xzsx


class DrForm(ModelForm):
    class Meta:
        model = Dr
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class EgForm(ModelForm):
    class Meta:
        model = Eg
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class GgnForm(ModelForm):
    class Meta:
        model = Ggn
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class NcgForm(ModelForm):
    class Meta:
        model = Ncg
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class SxqgnForm(ModelForm):
    class Meta:
        model = Sxqgn
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class TrForm(ModelForm):
    class Meta:
        model = Tr
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V1AForm(ModelForm):
    class Meta:
        model = V1A
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V1CForm(ModelForm):
    class Meta:
        model = V1C
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V2AForm(ModelForm):
    class Meta:
        model = V2A
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V2BForm(ModelForm):
    class Meta:
        model = V2B
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V2DForm(ModelForm):
    class Meta:
        model = V2D
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class V2DForm(ModelForm):
    class Meta:
        model = V2D
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class XcgForm(ModelForm):
    class Meta:
        model = Xcg
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class XdfmForm(ModelForm):
    class Meta:
        model = Xdfm
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class XtForm(ModelForm):
    class Meta:
        model = Xt
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }


class XzsxForm(ModelForm):
    class Meta:
        model = Xzsx
        localized_fields = ('__all__')

        exclude = ['add_time']

        widgets = {}
        error_messages = {
            'protype': {
                'required':'这是个必填项目', #生成错误信息
            },
        }
ModelForm的定义

 

3.View逻辑的写法

from django.shortcuts import render
import os
import re
import json
from mfor_verity.settings import MEDIA_ROOT
from django.contrib.auth.decorators import login_required
# 指定返回给用户的类型
from django.http import HttpResponse
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.generic.base import View
from django.core import serializers
from .forms import DrForm,EgForm,GgnForm,NcgForm,SxqgnForm,TrForm,V1AForm,V1CForm,V2AForm,V2BForm,V2DForm,XcgForm,XdfmForm,XtForm,XzsxForm

from django.forms.formsets import formset_factory
from project_contrast.models import Edc_Project,Edc_Center,Edc_Patient,Edc_Visit,Edc_Form
from users.models import UserProfile
# Create your views here.



class ProjectFormSave(View):
    """
    保存表单信息
    """
    def post(self,request):


        #在model中统一定义一个字段为modelform的名称,
        # 通过前端的填写先任意匹配一个modelfrom得到这个字段的名称后,
        # 进行真正modelform的数据获取
        form = XtForm(request.POST)
        print(form.data)

        # eval() 字符串转变量 代表modelform 如:DrForm
        formset = eval(form.data.get('formame'))
        form = formset(request.POST)


        if form.is_valid():
            #注释为保存外键的写法,前端没有输入外键内容的情况下,本次为前端通过
            #点击赋予值进行隐藏
            # instance = form.save(commit=False)
    
            # instance.xt_center_id = edc_center_id  
            # instance.xt_patient_id = edc_patient_id
            # instance.xt_visit_id = edc_visit_id
            # instance.save()
            form.save()
        else:
            error = form.errors  #错误信息
            # return render(request, 'forms.html', {'form': form, 'error': error})
            print(error)
            return HttpResponse('{"status":"fail"}', content_type='application/json')

        return HttpResponse('{"status":"success"}', content_type='application/json')


    def get(self,request):
        """
        生成前端的表单文件添加一定的样式注意:html中一定要加name属性和model的name一致
        """

        model_form_name = request.GET.get('model_form_name','')

        #字符串转变量
        formset = eval(model_form_name+'Form()')
        print(formset)
        all_html = ''

        for form in formset:
            all_html += '<div class="form-group">' \
                        '<label for="{}" class="col-sm-4 control-label">{}' \
                        '</label><div class="col-sm-8">' \
                        '<input type="text" name="{}" class="form-control" id="{}">' \
                          '</div></div>'.format(form.id_for_label,form.label,form.html_name,form.id_for_label)

        all_datas = {
            'all_html':all_html
        }

        return HttpResponse(json.dumps(all_datas), content_type='application/json')

 

4.URL的写法

    # 返回对照页面
    url(r'^control_page/$', Control_Page.as_view(), name='control_page'),

    #保存提交的表单信息
    url(r'^projectformsave/$', ProjectFormSave.as_view(), name='projectformsave'),

 

5.Jquery的ajax的写法

var model_form_name = '';
//点击右侧表单信息获取相应model生成form表单
$('#id_form_menu>a').each(function(index){
   $(this).on('click',function(){

       //获取model的名称
       model_form_name = $(this).children('span').text();
       console.log(model_form_name);

       $.get('/projectformsave/',{'model_form_name':model_form_name},function(data){
            console.log(data);
            console.log(data.all_html);
            $('#project_form_edc').empty();
            $('#project_form_edc').append(data.all_html);
       })
   })
});




//Ajax异步提交表单提交表单
$('#id_edc_submit').on('click',function(){

    var data = $("#project_form_edc").serialize();

    $.ajax({
        cache: false,
        type: "POST",
        url: "/projectformsave/",
        dataType:'json',
        async: true,
        data:data,

        success: function(data) {


        },
        beforeSend: function(xhr, settings) {
          xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    });

});

 

6.HTML的写法先通过点击来获取表单的html内容,生成表单然后ajax异步提交表单

                <form id = "project_form_edc" action="/projectformsave/" class="form-horizontal" role="form">
{#                    <div class="form-group">#}
{#                        <label for="firstname" class="col-sm-4 control-label">名字</label>#}
{#                        <div class="col-sm-8">#}
{#                            <input type="text" class="form-control" id="firstname">#}
{#                        </div>#}
{#                    </div>#}
{#                    <div class="form-group">#}
{#                        <label for="lastname" class="col-sm-4 control-label">化疗周期</label>#}
{#                        <div class="col-sm-8">#}
{#                            <input type="text" class="form-control" id="lastname">#}
{#                        </div>#}
{#                    </div>#}
{#                    <div class="modal-footer">#}
{#                        <button type="submit" id = "jsLoginBtn" class="btn btn-primary">#}
{#                            提交更改#}
{#                        </button>#}
{#                    </div>#}

                </form>
                <div class="modal-footer">
                    <button type="button" id = "id_edc_submit" class="btn btn-primary">
                        提交表单
                    </button>
                </div>
            </section>

 

posted on 2018-03-03 21:52  星河赵  阅读(763)  评论(0编辑  收藏  举报

导航