1
我正面临Django一个有趣的情况,我希望有人会看到这个解决方案,或者至少可以给我一个提示。使Django ModelForm模型通用?
我想使ModelForm模型通用。我不知道这是不是应该做的事,但是在这里。
这工作得很好:
元组参考模型
# settings.py
SPECIES = (
('TIG', 'Tiger'),
('SHR', 'Shark'),
)
URL,创建一个Animal对象
# urls.py
from django.conf.urls.defaults import patterns, include, url
urlpatterns = patterns('species.views',
url(r'^add/$', 'add_animal', name='add_animal'),
)
的动物模型和它的两个孩子
# models.py
from django.db import models
from django.conf import settings
class Animal(models.Model):
name = models.CharField(max_length=100)
nickname = models.CharField(max_length=100)
species = models.CharField(max_length=3, choices=settings.SPECIES)
class Tiger(Animal):
fangs_size = models.IntegerField()
class Shark(Animal):
color = models.CharField(max_length=20)
显示通过GET参数选择了正确的模型形式
的图。
# views.py
def add_animal(request):
if request.method == "GET":
if request.GET['model_name']:
model_name = request.GET['model_name']
else:
model_name = 'Animal'
print "Model name is: %s" % model_name
model = get_model("species", model_name)
form = AnimalForm(model=model)
return create_object(
request,
model=model,
post_save_redirect=reverse('index'),
template_name='species/my_form.html',
)
模板
# my_form.html
<!doctype html>
<html>
<head>
<title>Adding an animal</title>
</head>
<body>
<h1>Add an animal to the farm</h1>
<form>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
</body>
</html>
当我访问/加?MODEL_NAME =虎,我得到显示正确的形式。
现在,假设我想隐藏昵称字段。然后我需要使用自定义的ModelForm。如何使用正确的模型进行实例化?这是我的问题。
这是表格?
# forms.py
from species.models import Animal
from django import forms
class AnimalForm(forms.ModelForm):
class Meta:
model = Animal
def __init__(self, *args, **kwargs):
model = kwargs.pop('model')
super(AnimalForm, self).__init__(*args, **kwargs)
self.Meta.model = model
的意见变成:
# views.py
...
model = get_model("species", model_name)
form = AnimalForm(model=model)
return create_object(
request,
# model=model, # Need for customization
# form_class=AnimalForm, # With the class name, how to pass the argument?
form_class=form, # Not sure this can be done, I get this error: 'AnimalForm' object is not callable
post_save_redirect=reverse('index'),
template_name='species/my_form.html',
)
...
我的目标是能够创造出新的车型从动物以后继承,将它们添加到种类元组来完成。这可以完成吗?
感谢您的帮助!
谢谢丹尼尔,我会研究它。 –