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',
)
...
我的目標是能夠創造出新的車型從動物以後繼承,將它們添加到種類元組來完成。這可以完成嗎?
感謝您的幫助!
謝謝丹尼爾,我會研究它。 –