0

Issue #1

I'm looking for the best practice in order to declare the additional data in a Django project. Imagine I need to store a huge list of choices to use in app1/models.py (I have seen a lot of best practices keep declaring those choices in the body of the models). In another scenario, Imagine I need to keep tens of config data in order to use them in my views.py. Is it common to declare them in the function/class?

In my opinion, there would be two common methods in order to do that. (Not sure even recommended at all)

Method #1

I can actually keep them all in my settings.py file and access them with importing (like from django.conf import settings).

settings.py:

...

NBA_TEAMS = (
    ("red", "Bulls"),
    ("yellow", "Lakers"),
    ...
)

Method #2

Keep them all in a file named data.py right next to the settings.py, and try importing it at the end of the settings file like this.

settings.py

...

try:
    from .data import NBA_TEAMS, ..
except:
    pass

Issue #2

Is there any best practice for creating modules in a Django project? Imagine I need to create a data validator function that receives string data from a form submission in views.py. Where should I keep those kinds of functions/validators/generators?

views.py

from --- import validateUsername

def submission(request):
    ...
    form = ContactForm(request.POST)
    if validateUsername(form.cleaned_data['username']):
        ...

Is there any best practice for these issues? Thank you.

Sadra
  • 167
  • 1
  • 9

1 Answers1

1

As per my suggestions for both your issues you should create one constants.py and one utils.py file.

Now depends on your use case if you want to use the same constants in multiple apps within your project then define it at the root next to manage.py or if the constants are specific to app then create it under the specific app folder next to views.py file.

Same for utils.py you should define all the utility functions / methods in one utils.py file and use it in all the apps within your project.

Shreeyansh Jain
  • 1,407
  • 15
  • 25