小编ctj*_*tj2的帖子

如何从 __new__ 参数返回子类

我有一个父类和两个子类 child1(parent) 和 child2(parent) 有点像下面的代码。(编辑以更正确地显示父类正在做某事)

class parent(object):
  name = None

  def __init__(self,e):
    # process the common attributes
    name = e.attrib['name']

  def __new__(cls,e):
    if e.attrib['type'] == 'c1':
      return child1(e)
    elif e.attrib['type'] == 'c2':
      return child2(e)
    else:
      raise 

class child1(parent):
  extra1 = None
  def __init__(self,e):
    super(e)
    # set attributes from e that are specific to type c1

class child2(parent):
  extra2 = None
  def __init__(self,e):
    super(e)
    # set attributes from e that are specific to type c2
Run Code Online (Sandbox Code Playgroud)

目标是能够根据参数的值获得“正确”的类。因此,如果我可以说obj = parent(element)并且obj …

python python-2.7

4
推荐指数
1
解决办法
2126
查看次数

如何在django ModelAdmin中访问内联数据

我需要处理以django管理员表单上传的文件.我在表单中添加了一个文件上传字段:

class ExampleInline(admin.TabularInline):
    model = OtherExample
    extra = 1
class ExampleForm(forms.ModelForm):
    filedata = forms.FileField()
    class Meta:
        model = ExampleModel
class ExampleModelAdmin(admin.ModelAdmin):
    form = ExampleForm
    inlines = [ExampleInline,]
Run Code Online (Sandbox Code Playgroud)

这使表单呈现与我想要呈现的完全相同.Request中返回的数据正是我所期望的.

问题是我想访问内联的内容.

class ExampleAdmin(admin.ModelAdmin):
...
def save_model(self, Request, obj, form, change):
   the_file = form.cleaned_data['filedata']
   # do amazing things to contents of file
Run Code Online (Sandbox Code Playgroud)

此时我想引用用户在内联中选择的结果.无论他们为OtherExample挑选什么.

如何通过表单访问?我不想通过请求,但我愿意这样做.我也愿意考察save_related(self,request, form, formset, change)

django django-models django-forms django-admin

3
推荐指数
1
解决办法
3281
查看次数