·

How to split views.py to several smaller files in Django

Published at 2024-05-01 14:11:30Viewed 321 times
Professional article
Please reprint with source link

When your views.py is too large, it becomes much more difficult to manage your code. So you might want to split views.py into several subviews, each of which contains a single sort of views.

To split views.py, you could follow the following steps. Your original views.py might look like this:

import ...

def view1(request):
    pass

def view2(request):
   pass

Now, create a new folder subviews aside with views.py , i.e. /Django/mysite/MyAPI/subviews. Next, create __init__.py, viewsa.py, and viewsb.py in the folder subviews to form the following folder/file structure :

subviews/
   __init__.py
   subviews1.py
   subviews2.py

subviews1.py :

from .views import *

def view1(request):
    pass

subviews2.py :

from .views import *

def view2(request):
    pass

__init__.py :

from subviews1 import *
from subviews2 import *

Then this would work the same as a single views.py file. Don't forget to change the urls.py file before you reloading Django.

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

[antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.

I'm getting this error when using MessageWarning: [antd: Message] You are calling notice in render which will break in React 18 concurrent mode. Please trigger in effect instead.Here is my code:import { message } from 'antd'; export default function Page() { const [messageApi, contextHolder] = message.useMessage(); const res = await fetch("/api/...", { method: "POST", }); if (!res.ok) { messageApi.error("Error! Fail to login!"); } return ( <Home> ... </Home> ) }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved