def foreignKey_add_button(admin_class, field): """ 如果是外键则加上添加按钮 :param admin_class: :param field: 字段 :return: """ btn_ele = "" field_name = field.name # 字段名 field_obj = admin_class.model._meta.get_field(field_name) # 字段对象 models = enabled_admins.get(admin_class.model._meta.app_label) if type(field_obj).__name__ in ["ForeignKey", "ManyToManyField"]: # todo OneToOneField if field_obj.related_model._meta.model_name in models: # 如果对应外键的model注册到enabled_admins里面了则显示添加按钮 btn_ele += "<a href='/kind_admin/%s/%s/add/' class='btn btn-success btn-xs btn-rounded' target='_blank' style='display:inline-block;margin-top:4px;'><i class='fa fa-plus' aria-hidden='true'></i>添加</a>" % ( admin_class.model._meta.app_label, field_obj.related_model._meta.model_name) return mark_safe(btn_ele)
def __new__(cls, *args, **kwargs): for field_name, field_obj in cls.base_fields.items(): if type(field_obj.widget).__name__ != "CheckboxInput": field_obj.widget.attrs["class"] = "form-control" model_field_obj = admin_class.model._meta.get_field(field_name) if field_name in admin_class.readonly_fields and need_readonly: field_obj.widget.attrs["disabled"] = "disabled" if type(model_field_obj).__name__ == "ForeignKey": field_obj.widget.attrs["need_foreignKey_edit"] = "false" field_obj.widget.attrs["tag"] = "foreignKey-edit" related_model = model_field_obj.related_model._meta.model_name # 外键关联的model field_obj.widget.attrs["related_model"] = related_model if related_model in enabled_admins.get( admin_class.model._meta.app_label): field_obj.widget.attrs["need_foreignKey_edit"] = "true" if type(model_field_obj).__name__ == "DateField": field_obj.widget.attrs["class"] = "form-control date-picker" return ModelForm.__new__(cls)