2014-02-09 141 views
0

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

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

"""More code""" 

所以在我的Django的根,我现在有

#myCustomModule.py 
class MySubclass(TheClassIWantToExtend): 
    """Implementation""" 

我怎样才能确保MySubclass代替模块的原班?

编辑:也许我应该补充的是,原来的模块已经安装了PIP安装模块,它是在一个virtualenv中

+0

简答:你不能。 –

+0

@ IgnacioVazquez-Abrams:为什么不呢?你可以使用它们作为基础来扩展核心django模块和类。 – jrd1

+1

@ jrd1:除了你不能可靠地强制现有的代码来使用你的类。 –

回答

0

你可以简单地告诉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中所示),否则在事情发生时很快就会南下他们通常没有工作。