i need solution for users of the Django admin page - python

I created two users on the django admin page. When one user enters data the other user can see the data.
So,every users can see and change each other datas.
I want each user can only see and change own datas not others.
How can i prevent it?

I think that you don't have to use django admin as user profile. You can create authorization/authentication system on your website, this is the great post about it.
Then you can create user profile for every users, where they can add/edit/delete their private datas.

You can change the attributes (columns) according to different users (based on permission or some user attribute) but can not filter tuples on basis of that.
Example - (in app_name/admin.py)
def get_readonly_fields(self, request, obj=None):
if request.user.is_superuser:
self.readonly_fields = ()
else:
self.readonly_fields = ('id', 'name', 'attr1', 'attr2')
return self.readonly_fields
But looking on the limited info given, i suppose you want to filter tuples. This can only be achieved by making a custom admin page parallel to django's admin (ex - name it staff panel). In its view method filter (using Querysets) according to the school and return's its related data for edit or whatever you want (for ease you can use Model forms).
EDIT: Sorry, i found exactly what you were asking for(hopefully).
class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyModelAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
This returns only the objects related to logged in user on the admin change page.

Related

User can update or delete data which created by others

class StoryViewSet(viewsets.ModelViewSet):
serializer_class = StorySerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
I have viewset with all CRUD functions. The problem is that user can edit or delete stories of another user, I found DjangoModelPermissionsOrAnonReadOnly in permissions, but I cannot even create. I am using author as foreign key in Storymodel. Also I am using rest_framework.authtoken. So, I think there is two options, create own permission or rewrite some permission. Which one is better?
Write a customer object-level permission. Here is an example:
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return obj.author == request.user
And include it to permission_classes list.

How to display all the users created by a particular user in django?

For example: if a user creates n number of users . I want to display the n number of users created by that particular user alone in django .
I can't come up with a solution.
Do i have to create a model like profile with OnetoOnemodel of user?
It's a fair question, but no, you can't guarantee knowledge of who created the user. Users just exist in a database and thus can be created completed outside of Django. What you could do is create a UserAdmin and overwrite save_model to set some field, i.e, creator, as the current user:
# set creator as logged-in user
def save_model(self, request, obj, form, change):
obj.creator = request.user
super(MyUserAdmin, self).save_model(request, obj, form, change)
But this still does not guarantee an audit of any user; only those created through the admin. See the docs for more on admin methods.

How do I separate user accounts in Django ?

I am using Django to create an app that allows recording of medical information however I am having problems with seperating the user accounts so currently all users see the same information entered. Anyone familiar with django knows how to set the proper permissions and roles and is willing to help a newby out?
I want the user to only access to the account the user creates and the records that the user create.
This is my github link
If you are able to to help I would really appreciate it.
If you want to list only the user's records in your /home . You only need to change the query in your home/views.py, from Identity_unique.objects.all() to Identity_unique.objects.filter(user=request.user)
class Identity_view(TemplateView):
def get(self, request):
form = Identity_form()
Identities = Identity_unique.objects.filter(user=request.user)
var = {'form': form, 'Identities': Identities}
return render(request, self.template_name, var)
Or if you want to filter objects in your Django Admin panel you should read this:
Django Documentation: ModelAdmin.get_queryset(request)
Create a custom user model with an extra field user_type.
https://github.com/samimsk/debatehub/blob/master/devdebatehub/UserApp/models.py
Implemented here.

Delete in admin override with confirmation.

I had to override the delete method for admin like so :
def fully_delete_selected_photos(self, request, queryset):
# Code to do my specific delete method.
fully_delete_selected_photos.short_description = "Delete Selected Photos"
class VehiclePhotoAdmin(admin.ModelAdmin):
search_fields = ('listing_id',)
list_display = ('listing_id', 'disp_VehiclePhoto')
actions = [fully_delete_selected_photos]
def get_actions(self, request):
actions = super(VehiclePhotoAdmin, self).get_actions(request)
del actions['delete_selected']
return actions
This works fine but I lost the confirmation of deletion. So when the user selects my "Delete Selected Photos" option it immediate just goes through with the delete. How can I get some kind of confirmation for the overridden deletion? I am confused about the redirections of views in admin.
Thank you for your time!
You can return HttpResponseRedirect in fully_delete_selected_photos method, and make custom view , thats inherit template from admin, and takes queryset parameter, and lists all selected photos.
But if you want to simplify it, add some JavaScript to admin view.

Permissions for a site only

I have a multilingual Django project. Every language is a different subdomain.
So we've decided to use the "sites" application and to create one different site for every language.
On that project, I also have a "pages" application, which is quite similar to a CMS. The user can create pages with content and they'll be displayed in the appropriate language site.
Now I'm looking to be able to manage advanced permissions. What I need to do is to allow, in the admin application a user only to create and update pages for one (or many) specific language/site.
What'd be the cleaner way to do something like that ?
Edit : Here is the solution I've adapted, given by Chris
I create a decorator that's checking if the user is appropriately in the group that has access to the lang.
See Chris' accepted answer for an example of this.
In a "normal" view, I do the following :
def view(self):
# Whatever you wanna do
return render_to_response('page.html', {}, RequestContext(request))
view = group_required(view)
If the user is in the group, it'll return the method. Otherwise, it'll return an "Access Denied" error.
And in my admin, I do the following :
class PageAdmin(admin.ModelAdmin):
list_display = ('title', 'published')
fieldsets = [
(None, {'fields': ['title', 'slug', 'whatever_field_you_have']}),
]
def has_add_permission(self, request):
return in_group_required(request)
admin.site.register(Page, PageAdmin)
Where the in_group_required is a similar method to group_required mentionned above. But will return only true or false depending of if we have access or not.
And because we use them quite much in the previous examples, you'll find above here what I have in my in_group and group_required methods.
def group_required(func):
def _decorator(request, *args, **kwargs):
if not in_group(request):
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
def in_group(request):
language = Language.objects.get(site__domain__exact=request.get_host())
for group in language.group.all():
if request.user in group.user_set.all():
return True
return False
You could create a Group (http://docs.djangoproject.com/en/dev/topics/auth/)
per site / language and add the users to the groups accordingly.
Then, you can check if the request.user.groups belongs to the group.
(You can do this with a decorator:
def group_required(func):
def _decorator(request, *args, **kwargs):
hostname = request.META.get('HTTP_HOST')
lang = hostname.split(".")[0]
if not lang in request.user.groups:
return HttpResponse("Access denied")
return func(*args, **kwargs)
return _decorator
(Correct / modify the code to match your requirements...)
You can override has_add_permission (and related methods) in your ModelAdmin class.
(With similar code like shown above)
If you want to filter the Page objects on the admin index of your page-application,
you can override the method queryset() in ModelAdmin.
This QuerySet returns only those Page objects, that belong to a Site (and therefore Group)
of which the request.user is a member.
Pages.objects.filter(site__name__in=request.user.groups)

Categories