Splitting views.py and urls.py into a directory rather than single files

89 views
Skip to first unread message

Simon Connah

unread,
Sep 18, 2023, 8:28:29 AM9/18/23
to django...@googlegroups.com
Hi,

I have an app which has a lot of views and URLs and keeping them in just one file makes it really hard to manage because it is so long. I'd like to make a views and URLs folder which will allow me to break up views and URLs into different categories but I'm not sure what the best way to go about doing that is.

Can someone point me in the right direction please?

Thank you!

Simon.
signature.asc

Asim Sulehria

unread,
Sep 18, 2023, 8:36:08 AM9/18/23
to django...@googlegroups.com
You can just directly declare an array of URL Patterns in a separate file and then import that file in the url files you want to make the main urls file

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/4svI0xN0uu53BvHzhG9Aa1qvI61v1qPlQOhkOLpaJPRXX1Jysfu-BOmrFlBsDOfHfKRHwTaXJNmKFApZ1W13jQLdpVvXQDEPdWq87T-ILR8%3D%40protonmail.com.

Simon Connah

unread,
Sep 18, 2023, 9:00:37 AM9/18/23
to django...@googlegroups.com
Thank you! That got it working!

------- Original Message -------
signature.asc

Asim Sulehria

unread,
Sep 18, 2023, 9:05:29 AM9/18/23
to django...@googlegroups.com

SYED ZAKIR HOSSAIN

unread,
Sep 18, 2023, 6:34:39 PM9/18/23
to django...@googlegroups.com
I am using an app and it is uploaded to pythonanywhere.com. This app contains 570 + views, 550+ urls. I organise all views in alphabetical order.I am comfortable with the backend. Hope it will be useful for you.

Mike Dewhirst

unread,
Sep 18, 2023, 8:05:15 PM9/18/23
to django...@googlegroups.com
I like the following method because it lets me start a project with a single file of views per app and then later when it grows, split it into named files in a 'views' directory - without needing to adjust other code which imports them.

1. Create a views directory in the app dir

2. Create __init__.py in the new directory

3. Move the monster views.py into ./views renaming it to original.py or something similar.

4. Split original.py into as many useful individual views files as desired - including separate utilities file(s) etc.

5. In __init__.py import each view used by your urls.py using lines like ...

   from .filename import ViewName

Obviously, multiple views can be grouped into the same file so long as they are imported into views.__init__.py

6. In urls.py you can then say ...

    import appname.views as appname_views

... if that's not what you do already!


--
(Unsigned mail from my phone)

Reply all
Reply to author
Forward
0 new messages