- Save the user link in your model.
models.py:
from django.db import models from django.contrib.auth.models import User class MyModel(models.Model): user = models.ForeignKey(User) ... (your fields) ...
- Force the current user to be saved in this field (when using the administrator).
- Apply any list of these objects (optional), filtered by the current user (when using the administrator)
- Prevent other users from editing (even if they cannot see the object in the list to which they can access its change_form directly)
admin.py:
from django.contrib import admin from models import MyModel class FilterUserAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user obj.save() def get_queryset(self, request):
If you have MyOtherModel with a foreign user key, just subclass MyOtherModelAdmin from FilterUserAdmin in the same way.
If you want some superusers to be able to see something, adjust the queryset () and has_change_permission () parameters according to your own requirements (for example, do not filter / deny editing if request.user.username == 'me'). In this case, you must also adjust save_model () so that your editing does not establish the user and thus “take” the object from the previous user (for example, only install the user if self.user is None (new instance)).
source share