About Empty Mandatory Foreign Keys
By default, if you try to read a mandatory foreign key that hasn't been assigned yet, you will get an ObjectDoesNotExist
exception.
To avoid exception handling, you can use hasattr
:
if not hasattr(post, "user"):
post.user = request.user
Tips and Tricks Programming Databases Django 4.2 Django 3.2 Django 2.2 PostgreSQL MySQL SQLite
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.