# 实时编辑功能 list_editable = [‘reason_one‘, ‘low_price‘, ‘fbm_display‘] # 因为这个字段后期要加一些显示的逻辑,所以需要自定义,但是又希望能支持实时编辑 def fbm_display(self, row): return row.artificial_confirm_stock_no_fbn field = Goods.artificial_confirm_stock_no_fbn fbm_display.short_description = ‘补FBM‘
1. 修改models
class Goods(models.Model): ‘‘‘ 商品表 ‘‘‘ artificial_confirm_stock_no_fbn = models.IntegerField(verbose_name=‘人工海外补货‘, default=-1) # 在表中添加一个函数,函数名要跟自定义字段的名字相同 def fbm_display(self): return ‘artificial_confirm_stock_no_fbn‘
2.修改 /xadmin/util.py
def lookup_field(name, obj, model_admin=None): opts = obj._meta try: f = opts.get_field(name) except models.FieldDoesNotExist: # For non-field values, the value is either a method, property or # returned via a callable. if callable(name): attr = name value = attr(obj) elif ( model_admin is not None and hasattr(model_admin, name) and name not in (‘__str__‘, ‘__unicode__‘) ): attr = getattr(model_admin, name) value = attr(obj) else: if is_rel_field(name, obj): parts = name.split("__") rel_name, sub_rel_name = parts[0], "__".join(parts[1:]) rel_obj = getattr(obj, rel_name) if rel_obj is not None: return lookup_field(sub_rel_name, rel_obj, model_admin) attr = getattr(obj, name) if callable(attr): value = attr() else: value = attr f = None # 在这里添加以下代码,目的是为了添加filed if hasattr(obj, name): field = getattr(obj, name)() opts = obj._meta f = opts.get_field(field) # 添加结束 else: attr = None value = getattr(obj, name) return f, attr, value
3.修改xadmin/plugins/editable.py
@filter_hook def get(self, request, object_id): model_fields = [f.name for f in self.opts.fields] # fields = [f for f in request.GET[‘fields‘].split(‘,‘) if f in model_fields] # 将上面的代码注释,改成下面代码,如果不改这段代码,目的是将自定义的字段名称替换成数据库中的字段名称,如果使用自定义的字段名称,form不识别字段类型,前端会不显示input框 fields = [] for f in request.GET[‘fields‘].split(‘,‘): if f in model_fields: fields.append(f) else: if hasattr(self.model, f): fields.append(getattr(self.model, f)(self)) # 结束 defaults = { "form": self.form, "fields": fields, "formfield_callback": self.formfield_for_dbfield, } form_class = modelform_factory(self.model, **defaults) form = form_class(instance=self.org_obj) helper = FormHelper() helper.form_tag = False helper.include_media = False form.helper = helper s = ‘{% load i18n crispy_forms_tags %}<form method="post" action="{{action_url}}">{% crispy form %}‘ + ‘<button type="submit" class="btn btn-success btn-block btn-sm">{% trans "Apply" %}</button></form>‘ t = template.Template(s) c = template.Context({‘form‘: form, ‘action_url‘: self.model_admin_url(‘patch‘, self.org_obj.pk)}) return HttpResponse(t.render(c))
这样就修改完成了
原文:https://www.cnblogs.com/wtil/p/12528271.html