Tips to improve your django skills - part 1

makemigrations and then sqlmigrate

I only now discovered sqlmigrate and regret not having known about it before. sqlmigrate prints the SQL for your migrations, so run a fast sqlmigrate after creating a new migration. Very often, you will see that this migration is not performing any SQL migrations; for example, if you change a field, you will frequently get the following sqlmigrate output:

BEGIN;  
--  
-- Alter field name on player  
--  
COMMIT;

I recommend giving it a shot if you want to learn more about Django migration. You'll quickly figure out which modifications have an impact on your database and which don't. As a consequence, learning SQL on the go is always a good idea.

Use time zone and stop using date.today()

Most users don't worry about time zone at the start of a project, so they're content to use datetime.datetime.now() and datetime.date.today() . However, you may eventually encounter strange errors in which certain computations appear to be off by two hours or even a day.

I know what it's like to attempt to correct all these errors by making all your thousands of now() and today() calls time zone aware, because I've had to do it twice for larger applications. You'll most likely have to do them one at a time, and you'll always run into difficulties where adding a time zone later is difficult.

This is readily avoided by just using time zones all of the time. Especially because Django is so wonderful at supporting it. So, don't be frightened, and just support time zones, even if you believe you don't need them. Add the setting USE TZ = True and then always call django.utils.timezone.now() or django.utils.timezone.now().date.

More information about Django's time zones can be found here:

Adding forms to views. py

It is advised that you put all of your forms in a separate forms.py file, however since forms are merely a method of styling a view, it makes more sense to put each form at the top of its view. You will be working on the view and the form at the same time, so if your models.py becomes too cluttered, you may transfer some of your models into a second model file. That's true, your models don't all have to be in the same file.

This configuration enables you to work on both your form and your view at the same time.

Closing notes

Thank you for spending the time to read my blog post! I hope these three tips have aided you in improving your Django work. Please let me know in the comments below whether you found these strategies useful or if you've discovered even better solutions, since I'm really interested in your feedback!

follow me on github and twitter

41