Python django覆盖模块类
我正在使用一个模块,我需要从中扩展一个类Python django覆盖模块类,python,django,Python,Django,我正在使用一个模块,我需要从中扩展一个类 #name.module.py """ Lots of code """ class TheClassIWantToExtend(object): """Class implementation """More code""" 所以在我的django根中,我现在有了 #myCustomModule.py class MySubclass(TheClassIWantToExtend): """Implementation""" 如何确保使用
#name.module.py
""" Lots of code """
class TheClassIWantToExtend(object):
"""Class implementation
"""More code"""
所以在我的django根中,我现在有了
#myCustomModule.py
class MySubclass(TheClassIWantToExtend):
"""Implementation"""
如何确保使用MySubclass而不是模块的原始类
编辑:我应该补充一点,原来的模块是用pip安装模块安装的,它是在一个virtualenv中,你可以简单地告诉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文件中执行以下操作:
然后,要使用这个扩展类,您需要在通常使用父类的地方使用它:
# 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:除了您不能可靠地强制现有代码使用您的类之外。@IgnacioVazquez Abrams:啊!说得好。注意到了。谢谢@伊格纳西奥瓦茨奎兹·艾布拉姆斯你说得很对,这是显而易见的。谢谢。虽然问题已经老了,但我必须说这并没有回答原来的问题。假设模块是pip install,没有实际的方法告诉django使用您的类,如果模块在整个过程中都使用自己的类,那么在任何需要父类的特定实例的方法或类中,您希望扩展父类。@Felipe:谢谢您的评论。在OP发布他们最初的问题时,我认为这是一个恰当的回答。根据他们更新的条目和评论历史的回顾,它不是。我一直保持这种状态,以防对其他人有利。
# 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())