Not to allow to delete models in django project for demo product
-
29-06-2021 - |
Вопрос
I have a demo product built on django framework and is running live. Prospective customer will login to the UI with superuser access privilege. I wanted to show the delete option but when they execute the delete option, I want to show the message like 'not allowed for demo login'.
Is there a way to achieve this quickly in django framework. What is the best option to do this.
Thanks Siva
Решение 2
I fixed this by creating a demo user and adding the following code to the middleware class:
if request.user.username == 'demo':
if '/delete' in path:
request.user.message_set.create(message='Delete/Edit option is disabled for demo account.')
return HttpResponseRedirect("../../")
if path.startswith ('/admin/') and request.method == 'POST' and request.POST.has_key('action'):
axnname = request.POST.get('action')
if axnname == 'delete_selected':
request.user.message_set.create(message='Delete/Edit option is disabled for demo account.')
return HttpResponseRedirect(path)
if path.startswith ('/admin/') and request.method == 'POST' and request.is_ajax() is False:
request.user.message_set.create(message='Add/Edit option is disabled for demo account.')
return HttpResponseRedirect("../")
Другие советы
I would create a staff user, definitely not a superuser. This will let you take advantage of Django's builtin permissions, which seems convenient in your case.
Create a user that has permissions to Add and Edit DemoModel, not Delete.
Add a JS file to your change_form via ModelAdmin, or add a custom view
class DemoModelAdmin(admin.ModelAdmin):
class Media:
js = (
'/static/js/mimic_delete.js',
)
admin.site.register(DemoModel, DemoModelAdmin)
In your mimic_delete.js file you can add a jQuery loop to add a delete button to each row in the results_list of the DemoModel changeform and add a hide event onclick or whatever you'd like for a representation.
Another approach could be to bind the model entries to a session and override the ModelAdmin's get_queryset to filter the entries that where created by the user in the current session, cleaning them up after the session expired.