13 ms·
Things I do every time I start a Django project
- NaturalPhallacy 4y agoI found this a lot more interesting than the submission article: https://12factor.net/ https://12factor.net/
- instb3at 4y agoI don't know why no one mentioned this. https://cookiecutter-django.readthedocs.io https://cookiecutter-django.readthedocs.io I use a modified version of this for all my projects. This one comes with all the goodies
- pratyushmittal 4y agoYup, a custom cookiecutter template saves ton of time. I created this one to create a production ready Django project in few minutes: https://github.com/Mittal-Analytics/django-cookiecutter https://github.com/Mittal-Analytics/django-cookiecutter Things this does: - README.md: setup readme with development setup - Django split settings: split settings for local, testing and production - Split requirements: split requirements.txt for local and production - Pre-commit hooks: setup pre-commit hooks for black and pyflakes - django-envoiron: database config and secrets in environment - editorconfig: sensible tab/space defaults for html, js and python files - remote-setup: setup hosting on uberspace - git push deployment: `git push live` makes the changes live - github actions for tests: run tests automatically on Github
- hdlothia 4y agoGood advice
- ttymck 4y agoReally sensible, straightforward recommendations. Nothing flashy. Honestly I think these should be defaults (or at least configurable options) of the project generator. I guess you could use cookiecutter, but it's not really worth it.
- kubami 4y agoThis depends. If you start a new project often it is much better to use a template.
- zmdgg 4y agoall great bits of advice except the first. keep your secrets out of your environment! especially when you aren't providing any additional safety advice like making sure DEBUG is off
- runnerup 4y agoWhere should you put secrets instead? Obviously not the filesystem.
- thaumasiotes 4y ago> Obviously not the filesystem. How would you avoid that? Even this article, which recommends keeping your secrets in environment variables, tells you to implement that by storing them in the filesystem. The advice isn't to avoid storing your secrets in the filesystem; it's to avoid storing them in version control. It is apparently an exercise for the reader to figure out why it's better to read your secrets out of the environment, which read them from a file you provided, than to read them from your own file yourself.
- e12e 4y agoIf you use bitwarden - you can set them via bitwarden cli, eg: export DATABASE_URL="$(bw get password my_app/db_url/prod)" And put that in a startup script (that can go in version control).
- thaumasiotes 4y agoWhere is bitwarden getting the password from?
- deleted 4y ago[deleted]
- BiteCode_dev 4y agoAnd what happens on reboot ? Then you get to hardware solutions, and a small website is not going to want that.
- Apreche 4y agoReasonable. Personally I just made a template project to get everything off the ground in one step, even the production environment and repository. https://github.com/Apreche/djangogoboot https://github.com/Apreche/djangogoboot
- theptip 4y agoIf you do this a lot you should look into ‘startapp —-template’ which lets you bake in boilerplate like this. https://docs.djangoproject.com/en/4.0/ref/django-admin/#cmdoption-startapp-template https://docs.djangoproject.com/en/4.0/ref/django-admin/#cmdo... One minor point on app names. They are really hard/annoying to change once you have production data, because your DB tables will always be appname_modelname, and renaming tables is a real PITA. You can set the model to point to a nonstandard table, but then your project has a confusing non-Djangonic wart that will annoy you forever more. For this reason I think ‘core’ is a safer option, unless you are certain what your app should be named. Naming after one domain model is likely to be too specific. (I strongly recommend against multiple apps until you have functionality you need to commonize between projects, as refactoring models between apps is a nightmare if you get the boundaries wrong.)
- chomp 4y ago> For this reason I think ‘core’ is a safer option, unless you are certain what your app should be named. Yep, this is what I do. It’s rare that I make anything that can be shared cross-app (most Django apps I make are super simple CRUD-types), so every one of my Django apps has a ‘core’. I also recommend this approach.
- saila 4y agoRegarding apps, I was just thinking you could create a directory structure like this, essentially eschewing the whole concept of Django "apps": <project> src/ <package>/ models/ __init__.py # Import all model classes (necessary for Django to find them) some_model.py # Define SomeModel class views/ __init__.py some_view.py # Views for SomeModel settings.py # Add "<package>" to INSTALLED_APPS urls.py You still need to register the top level package as an app for Django to find things, but then you don't have to deal with Django's concept of apps beyond that. All your tables will be named <package>_<model> by default, which seems nice. If it turns out later you need resusable "apps" for some reason, you could always add an apps/ subpackage for them. I haven't tried this in a real project, so I don't know if there are any downsides, but it seems like a decent approach.
- xwowsersx 4y agoHow often does one start a new Django project? I've been working on the same project for a couple years...
- mod 4y agoI started dozens of rails projects when doing client work. We occasionally chose Django, too.
- BiteCode_dev 4y ago5 times a year if you are a freelancer.
- kolanos 4y agoThe first two can be covered by this helpful library. [0] [0]: https://github.com/joke2k/django-environ https://github.com/joke2k/django-environ
- adiyatmubarak 4y agoI used Django, and personally I don't like Django startaproject command that not allow us to create project that contains dash "-". Also default appname has the same name with the project name can confusing the new comer in Django. I always structures my project like this when start my Django project. $ mkdir -p my-example-project/src $ cd my-example-project/src $ django-admin startproject youtube_downloader . so all Django related will be under src folder.
- abalaji 4y agoThat's actually a Python convention issue rather than a Django issue. Python convention dictates preference for underscores. This is because dashes cannot be used in a module name.
- adiyatmubarak 4y agoYes, because default Django app name by default using the same name with Django project name.
- hsbauauvhabzb 4y agoI’ve never really understood the concept of an ‘app’, in some projects I’m sure in makes sense but it not being transparent by default in a new project seems silly. Am I missing something here?
- knicholes 4y agoSay you want to easily create a comments app or ratings that you can associate with any other model in your project. Write that app once and use in many places. Or maybe something that sucks to write that may be error-prone, like auth, especially social auth which may change frequently. Maintaining one app and sharing it is way better than everyone trying to keep up with the changes themselves. Or take a look at https://djangopackages.org/ https://djangopackages.org/ for examples of apps people like to share.
- edmundsauto 4y agoCan't you just keep the logic for your comments app in the monoapp and use it with everything? I understand if you want to distribute your app for others to incorporate, but otherwise it felt like the documentation overemphasizes the "app" aspect. It's a reasonable structure but more of a guideline... unless you want to reuse in other codebases
- zach_garwood 4y agoI think many (most?) Django apps only ever need one app. I think the fact that it's front and center in Django is a bit if a distraction that makes people think they _have_ to use multiple apps.
- switch007 4y ago100% agree. It’s a distraction
- nojs 4y agoI used to build everything with one giant “monoapp” and completely ignore that aspect of Django, which worked pretty well. Eventually though you need to split up your models into multiple files, and then your views, and admin, and so on, and it turns out there’s a lot of benefits of just segregating things into “apps” from the beginning. The only real downside I’ve noticed in practice is the omni-file-search feature in my IDE is harder to use, because you now have 7 “models.py” and it’s a bit harder to quickly navigate to the right one. If you split up files without using apps (just normal Python imports), you don't have the same problem with all the names being duplicated. The pitch that you can "reuse" apps across projects always seemed weird to me, because that's basically never something you actually want to do/can do easily without major surgery.
- davepeck 4y agoStraightforward, useful advice. I pretty much do all of these when I start new Django projects. The need for a custom User model makes me a little sad every time because, well, single `name` fields (rather than `first_name`, `last_name`) and email-for-username do feel to me like more sensible defaults circa 2022.
- ethanpil 4y agoI'm curious as to why you think a single name field is better than the traditional separate first and last?
- Daishiman 4y agoPer https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-... , names have far too much ambiguity to consider that two fields is necessary or sufficient to encapsulate that information.
- mdisc 4y agoMaybe for consumer apps, but for a lot of enterprise apps that have to be compatible with existing APIs or domain-specific data standard that require two name fields, that’s not really a viable approach.
- silviogutierrez 4y agoIf you want a batteries-included, zero-config Django + React framework, check out https://www.reactivated.io https://www.reactivated.io . It incorporates most of these best practices, along with React server side rendering in addition to regular Django templates. Full disclosure: I'm the creator.
- greenie_beans 4y agothis is cool, thanks for sharing. this (https://www.reactivated.io/documentation/philosophy-goals/ https://www.reactivated.io/documentation/philosophy-goals/) fits my bias so i'm def gonna try it. curious how it works at a low level, too
- singhrac 4y agoSame, I agree with many of the thoughts there. When you get a moment, would you mind writing a guide on how to deploy it to Render.com? It sounds like the Heroku of 2022.
- silviogutierrez 4y agoTheoretically, the Dockerfile should "just work"™ with Render.com as well. Right now I focus on fly.io only because their free tier offers PostgreSQL without time limits. Render, I believe, only does so for a period of time. See here: https://github.com/silviogutierrez/reactivated/blob/main/development/Dockerfile https://github.com/silviogutierrez/reactivated/blob/main/dev... https://github.com/silviogutierrez/reactivated/blob/main/development/scripts/launch.sh https://github.com/silviogutierrez/reactivated/blob/main/dev... https://github.com/silviogutierrez/reactivated/blob/main/development/scripts/deploy.sh https://github.com/silviogutierrez/reactivated/blob/main/dev...
- ryanisnan 4y agoThis looks great!
- lordofgibbons 4y agoIf you're doing server-side rendering, why do it in React SSR instead of Django templates? I've seen this pattern a lot recently but haven't figured out what the extra complexity gets you
- nojs 4y agoI would add to this list: convert your template engine to Jinja2. I held out for a long time on this, and now I would not go back. The purist approach ("keep logic out of templates") sounds good, but in practice leads to spaghetti hacks with weird additional template tags to do simple things, a bunch of additional context variables with no meaning, etc.
- 41b696ef1113 4y agoAs another hold-out on Jinja, what pushed you over the edge? Half of the appeal to me in Django is that if you follow the easy path, one project should look like another. Breaking conventions for a few template niceties has not seemed worth it (although, I am not a front end guy, and survive on very barebones presentation).
- nojs 4y ago> what pushed you over the edge? Using Tailwind without a frontend js framework. I needed a way to create lightweight “components” ala React but on the backend, because otherwise you’re either copy pasting classes like mad or (ab)using tailwind’s @apply.
- jereze 4y agoHow do you create your components in Jinja2? Using the include tag?
- nojs 4y agoI am using {% macro %}
- drcongo 4y agoI've been gradually removing all use of Jinja macros from our projects as they make debugging so much more painful. Everything now goes in template globals, which lets you debug them the same as anything else, gives far clearer stack traces and lets you do clever things with caching.
- focom 4y agoAnd also install Django Extensions (https://django-extensions.readthedocs.io/en/latest/ https://django-extensions.readthedocs.io/en/latest/) It makes the Django CLI comparable to rails. Notably the reset_db and shell_plus command
- drcongo 4y agoshell_plus is fantastic.
- rajasimon 4y agoEvery time whenever I start a new project. 1. django-environ 2. celery 3. channels 4. apps structure https://rajasimon.io/blog/django-project-structure/ https://rajasimon.io/blog/django-project-structure/ To setup all the "Hello World" take long time.
- awinter-py 4y ago7. completely rewrite the auth system because it's not sufficiently flexible, chafe at the boilerplate, then port the backend to a different framework + miss the admin system a little
- the_cat_kittles 4y agopainfully true
- BiteCode_dev 4y agoDjango-allauth usually got you covered, but in the rare case it doesn't, creating a micro service just for auth is a way better alternative than a complete rewrite.
- BiteCode_dev 4y agoI do pretty much the same, which makes me think it should be django default startup template. I would also do: - install django_extensions and django_debug_toolbar - rename the admin URL route to contain a uuid - setup black, mypy, pylint, ipdb, ipython, dotenv and doit (I do so for all my python projects) - manage.py createsuperuser Also, very often : - setup celery (locally with fs backend) - setup vitejs - install sentry and mailtrap plugins - install django-allauth - install DRF And currently exploring: - replace DRF with django ninja
- deleted 4y ago[deleted]
- awongh 4y agoOne thing I never figured out was dependency management. Some others are linking to two scoops of django and other starter templates, it seems like none of them get past a kludgy set or requirements.txt files. I want something easy to use like ruby bundler or npm. I want to be able to specify my dependencies and install them in one command, and specify if something is production or local in that same command.
- h3ctic 4y agoHave you tried Poetry? (https://python-poetry.org https://python-poetry.org)
- Arcanum-XIII 4y agoAnd a way to manage the update of them… currently doing this blindly, running the test suite after each updated package hoping nothings broken. Slow and frustration prone with “sorry this package require packagex version 1 but packagew require it to be 2 now”
- mrweasel 4y agoOut of curiosity, and because I rather prefer pip and the requirements.txt file over npm or anything Ruby has to offer, what issues do you encounter with dependency management in Django/Python. Granted, trying to build your own reusable modules for Django is not a great experience. In these cases the tools feels rather restrictive.
- Gordonjcp 4y ago> I want to be able to specify my dependencies and install them in one command "pip install -r requirements.txt" If you have different requirements, you can use a different file. Obviously this is only for development, and if you package your Python code properly then you can install the whole damn thing as a package.
- lmns 4y agoI use pip-tools with venvs for that and can‘t complain. It pins dependencies and you can create different requirements.txts for local dev and production (production for me is usually dev minus some debugging tools). It‘s not particularly fancy, but it gets the job done.
- Gordonjcp 4y agoThings I do every time I start a Django project: 1) bring up Django project 2) populate db with example data 3) "Wow auto admin is so cool! 4) Right anyway, let's get to work 5) mkdir my_real_project && cd !! && pip install flask
- guender 4y ago
- TedShiller 4y agoThe first thing I do when I start a Django project is to not use Django.
- jeremycarter 4y agoWhich is good. Imagine trying to scale a Django app when more than just 5 concurrent users are hitting it. Step 1, don't use Python.
- 8b16380d 4y agoit’s not that bad
- Jaxtek 4y agoWhat else do you use then?
- revskill 4y agoWhy not ... expressJS + typescript + React then ? Not sure what's the point of using Django, except for You only know Python reason
- nasir 4y agoReally irrelevant comment. Moreover, the "You only know Python" reason is a very strong argument.
- sajrar 4y agoIt is almost like one could leverage python and all the amazing libraries to compute interesting things. It is almost like we can actually build web apps that do more than CRUD.
- andrewingram 4y agoShort answer: Django comes with so much out of the box that you end up reinventing a lot of wheels if you go with a pure JavaScript/TypeScript approach.
- senko 4y agoUsing a boilerplate template can really speed things up, and more importantly, avoid forgetting to set up (or change from default) something that's hard to change later, like the user model. I do a lot of Django+DRF projects and built https://apibakery.com/ https://apibakery.com/ to help with the initial scaffolding and defining the models (started as my internal tool, later opened it up to the public).
- guico 4y agoWhy don't you make a project template instead and start from there? That's what I do, complete will all the dependencies I always need (like Celery, Allauth, etc)