你可以简单地告诉Django使用你的类,而不是在需要的任何方法或类您希望扩展的父类的特定实例。
例子:
如果这是你的项目:
$ python django-admin.py startproject testdjango
testdjango
├── testdjango
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
你创建你的应用程序(它本身自带的机型):
$ python manage.py startapp utils
testdjango
├── testdjango
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
│
└── utils
├── __init__.py
├── admin.py
├── models.py
├── views.py
└── urls.py
比方说,我们要要扩展UcerCreationForm
,要做到这一点,您需要在您的utils/models.py
文件中执行以下操作:
from django.contrib.auth.forms import UserCreationForm
# Since you wish to extend the `UserCreationForm` class, your class
# has to inherit from it:
class MyUserCreationForm(UserCreationForm):
# your implemenation specific code goes here
pass
然后,要使用这个扩展类,你会使用它,你会正常使用父类:
# UserCreationForm is used in views, so let's say we're in the view
# of an application `myapp`:
from utils import MyUserCreationForm
from django.shortcuts import render
# And, here you'll use it as you had done with the other in some view:
def myview(request, template_name="accounts/login.html"):
# Perform the view logic and set variables here
return render(request, template_name, locals())
虽然这是一个简单的例子,有两件事情要记住:始终在项目设置中注册您的应用程序,并且在改进扩展时,您应该始终检查您尝试扩展的类的源代码(如site-packages/django
中所示),否则在事情发生时很快就会南下他们通常没有工作。
简答:你不能。 –
@ IgnacioVazquez-Abrams:为什么不呢?你可以使用它们作为基础来扩展核心django模块和类。 – jrd1
@ jrd1:除了你不能可靠地强制现有的代码来使用你的类。 –