Django重写模块类

2024-05-05 16:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个模块,我需要从中扩展一个类。在

#name.module.py
""" Lots of code """
class TheClassIWantToExtend(object):
   """Class implementation

"""More code"""

所以在我的django根中,我现在

^{pr2}$

如何确保使用MySubclass而不是模块的原始类?在

编辑:我应该补充一下,原来的模块已经安装了pip install module,并且它在一个virtualenv中


Tags: 模块ofdjangonamepyobjectmorecode
1条回答
网友
1楼 · 发布于 2024-05-05 16:08:29

只需告诉django改用您的类,在任何需要扩展父类的特定实例的方法或类中。

示例:

如果这是您的项目:

$ python django-admin.py startproject testdjango

testdjango
├── testdjango
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

然后创建应用程序(它有自己的模型):

^{pr2}$

假设我们要扩展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)否则当事情不能正常工作时,事情会很快停止。在

相关问题 更多 >