Django admin filter by user

I am new to django. I am creating a simple application in which I have users who enter some data and view it later. I need to make django admin show for the user only the data she entered and the data of other users. Can I change it to multiple administration pages?

thanks

+4
source share
2 answers
  • 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): # For Django < 1.6, override queryset instead of get_queryset qs = super(FilterUserAdmin, self).get_queryset(request) return qs.filter(created_by=request.user) def has_change_permission(self, request, obj=None): if not obj: # the changelist itself return True return obj.user === request.user class MyModelAdmin(FilterUserAdmin): pass # (replace this with anything else you need) admin.site.register(MyModel, MyModelAdmin) 

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)).

+12
source

You will need to save the user in each element and query each element with this user as search criteria. You will probably build a base model that all your other models will inherit. To get started, look at the line level permissions in admin .

+1
source

Source: https://habr.com/ru/post/1399887/


All Articles