Django:显示Generic ModelForm或预定义窗体 [英] Django: Display Generic ModelForm or predefined form

查看:161
本文介绍了Django:显示Generic ModelForm或预定义窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个模型,各有各的领域。对于2个模型,我使用通用形式(通过Django的create_object)来请求数据很好。我写了一个接受模型名称的函数,并将用户发送到通用形式

  url(r'^ add _(?P< ; $ name $)
$ b def generic_add(request,modelname):
mdlnm_model = models.get_model('catalog',modelname)
返回create_object(request,
model = mdlnm_model,
template_name ='create.html',
post_save_redirect ='/ library /',
extra_context = {'func' '+ modelname},
login_required ='True'

第三个模型,我有一个ModelForm类定义,以便当用户看到窗体时,我可以省略这个模型中的一个字段。

  url(r'^ create_actor / $',create_object,Actor_Input,name ='db_actor_create'),

Actor_Input = {
'form_class':ActorForm,
'template_name':'create.html',
'post_save_redirect':'/ library /',
'extra_context ':{'func':'Create Actor'},
'login_required':'True'
}

class ActorForm(forms.ModelForm):
class Meta:
model = Actor
fields =('name','age','height','short_description',
'long_description')

Django是否有一种方法显示定义的ModelForm(如果存在),但是如果还没有定义表单,则会显示完全通用的表单?我预计会创建更多的模型,而不是为每个单独的模型创建一个url,需要以Actor的方式分割出来。



所以放一个不同的方法,我想改变generic_add函数,所以它将使用ActorForm(如果它存在),否则通用的ModelForm。我知道如何检查ActorForm类的存在,但如果我想要这样做是动态的呢?像是检查:modelname +'Form'是否存在。我不确定如果存在的话,将用户动态地发送到预定义的表单。



任何建议?有没有更好的方法来看这个问题?

解决方案

这是我可能会如何处理你想要做的事情:

  url(r'^ add _(?P< model_name> \w +)/ $',generic_add),






  model_presets = {
'Actor':{
'extra_context':{'func':'Create Actor'},
'form_class':ActorForm,
'login_required':True,
'post_save_redirect':'/ library /',
'template_name':'create.html'
},
'default':{
'extra_context':{'func ':'哎呀,如果你看到\
这个,应该被覆盖了!',
'form_class':没有,
'login_required':True,
'model':None,
'post_save_redirect':'/ library / ',
'template_name':'create.html'
}
}

def _create_object_conf_helper(request,model_name):
如果model_presets中的model_name:
conf = model_presets [model_name]
else:
try:
named_model = models.get_model('catalog',model_name)
除了:
#在这里保护你的应用程序!
conf = model_presets ['default']
conf ['model'] = named_model
conf ['extra_context'] ['func'] ='创建%s'%model_name
conf ['request'] = request
return conf

def generic_add(request,model_name):
return create_object(** _ create_object_conf_helper(request,model_name))

我没有测试过,但应该可以正常工作,让我知道如果不是我想要的在我自己的项目中使用类似的东西。



此外,您还可以进一步,并为model_presets dict创建另一个层,以允许类似的帮助函数为您可能正在使用的任何其他通用视图创建配置。



BTW,没有必要用引号将True括住,只需记住将T大写,而不是rue,它将解析为1位布尔常量。使用'True'使用(粗略)最小32位作为字符串。两者都将在if语句中测试,因此这不是一个很大的交易。另一方面,使用'False'将无法按预期的方式工作,这是一个不是布尔值的字符串,因此也将被测试为true。



请参阅 http://docs.python.org/library/stdtypes.html#truth-价值测试


I have 3 models with various fields in each. For 2 of the models, I'm fine with using a generic form (through Django's create_object) to request data. I wrote a function that accepts the model name and sends the user to the generic form

url(r'^add_(?P<modelname>\w+)/$', generic_add),

def generic_add(request, modelname):
    mdlnm_model = models.get_model('catalog',modelname)
    return create_object(request,
        model = mdlnm_model,
        template_name = 'create.html',
        post_save_redirect = '/library/',
        extra_context = {'func': 'Create ' + modelname},
        login_required =  'True'
    )

For the 3rd model, I have a ModelForm class defined so that I can omit one of the fields in this model when the user sees the form.

url(r'^create_actor/$', create_object, Actor_Input, name='db_actor_create'),

Actor_Input = {
   'form_class': ActorForm,
   'template_name': 'create.html',
   'post_save_redirect': '/library/',
   'extra_context': {'func': 'Create Actor'},
   'login_required': 'True'
}

class ActorForm(forms.ModelForm):
    class Meta:
          model = Actor
          fields = ('name','age','height','short_description',
                   'long_description')

Is there a way for Django to display the defined ModelForm if it exists but otherwise display the fully generic form if a defined form has not been made? I anticipate creating many more models, and would rather not create a url for every single model that needs to be split out the way Actor is.

So put a different way, I want to alter the generic_add function so it will use the ActorForm (if it exists) but otherwise the generic ModelForm. I know how to check for the existance of the ActorForm class, but what if I want that to be dynamic as well? Something like checking if: modelname + 'Form' exists. I'm unsure how to dynamically send the user to a predefined form if one exists.

Any suggestions? Is there a better way to look at this problem?

解决方案

Here is how I would probably approach what you are trying to do:

url(r'^add_(?P<model_name>\w+)/$', generic_add),


model_presets = {
    'Actor': {
        'extra_context': {'func': 'Create Actor'},
        'form_class': ActorForm,
        'login_required': True,
        'post_save_redirect': '/library/',
        'template_name': 'create.html'
    },
    'default': {
        'extra_context': {'func': 'Oops, something went wrong if you are seeing \
                                   this, it should have been overwritten!'},
        'form_class': None,
        'login_required': True,
        'model': None,
        'post_save_redirect': '/library/',
        'template_name': 'create.html'
    }
}

def _create_object_conf_helper(request, model_name):
    if model_name in model_presets:
        conf = model_presets[model_name]
    else:
        try:
            named_model = models.get_model('catalog', model_name)
        except:
            # do something here to protect your app!
        conf = model_presets['default']
        conf['model'] = named_model
        conf['extra_context']['func'] = 'Create %s' % model_name
    conf['request'] = request
    return conf

def generic_add(request, model_name):
    return create_object(**_create_object_conf_helper(request, model_name))

I haven't tested this but it should work fine, let me know if it doesn't as I may want to use something similar in my own projects down the road.

Additionally you could also take this a step further and create another layer to the model_presets dict to allow a similar helper function to create configs for any other generic views you may be using.

BTW, it isn't necessary to enclose True in quotes, just remember to capitalize the T and not the rue and it will resolve to the 1 bit boolean constant. Using 'True' uses a (rough) minimum of 32 bits as a string. Both will test true in an if statement and thus this it isn't that big of a deal. On the other hand using 'False' won't work as expected as once again this is a string not a boolean and thus will also test as true.

See http://docs.python.org/library/stdtypes.html#truth-value-testing .

这篇关于Django:显示Generic ModelForm或预定义窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆