使用django-notifications时如何修复'on_delete'位置参数缺失错误?
Looks like you're hitting a compatibility snag between your Django version and the older django-notifications package. Let's break down why this happens and how to fix it quickly:
Why the Error Occurs
Starting with Django 2.0, the ForeignKey field requires an explicit on_delete parameter to define what happens when the related object is deleted (e.g., cascade delete, block deletion, etc.). The version of django-notifications you're using was built for older Django versions and doesn't include this mandatory parameter in its model code—hence the TypeError pointing to line 170 of notifications/models.py.
Solution 1: Upgrade to a Compatible Package (Recommended)
The original django-notifications package is no longer actively maintained. Instead, use the community-supported fork django-notifications-redux, which supports Django 2.0+ and includes the required on_delete parameters out of the box:
- Uninstall the outdated package:
pip uninstall django-notifications - Install the updated fork:
pip install django-notifications-redux - Double-check your
INSTALLED_APPSinsettings.pystill includes'notifications'(the app name stays the same for the fork):INSTALLED_APPS = [ # ... your other apps 'notifications', ] - Run migrations to sync the database schema with the updated model:
python manage.py migrate
Solution 2: Manually Patch the Old Package (Not Recommended)
If you absolutely need to stick with the original django-notifications package, you can manually add the on_delete parameter to the problematic line. Note that this change will be overwritten if you update the package later:
- Open the file referenced in the error:
C:\Python36\lib\site-packages\notifications\models.py - Locate line 170, which looks like this:
recipient = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='notifications') - Add the
on_delete=models.CASCADEparameter (you can pick other options likePROTECTorSET_NULLbased on your needs):recipient = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='notifications', on_delete=models.CASCADE) - Save the file and restart your Django server.
Quick Notes on on_delete Options
models.CASCADE: Delete the notification when the related user is deleted (most common use case)models.PROTECT: Block deleting the user if there are linked notificationsmodels.SET_NULL: Set therecipientfield toNULL(requires addingnull=Trueto the field definition)
内容的提问来源于stack exchange,提问作者paula moreno gutierrez

