The administrative interface django allows you to customize access rights to objects of various applications. For any model of any application, you can allow the user three actions: add new objects, edit and delete existing objects.
And what if we want to allow the user to edit only part of the fields? And at the same time leave the opportunity to other users to edit all the fields.
Proxy models will help us. In terminology, a django proxy model is an object that has the interface of a conventional model, but is not tied to a database, or rather, it is tied to data from another model. What is it for?
')
The jango documentation uses the following example. We want the objects in the
auth.User
model
auth.User
have an additional method. To do this, we create a proxy model based on the
auth.User
model, describe this method there and use this proxy model instead of the original one, where
auth.User
.
Let's return to our task. Proxy models are useful in that we can prohibit the user to work with the original model, allow him access to the proxy model, and customize the edit form so that only allowed fields are available.
Let's imagine that we have the following model:
class Article(models.Model): title = models.CharField(...) body = models.CharField(...) tags = models.CharField(...)
We want the editor to enter the admin area, see the list of articles, change tags, but cannot change the title or body of the article.
Let's create a proxy model for starters:
class ArticleEditProxy(Article): class Meta: proxy = True
Now we register this model in
admin.site
and assign it a special form in which only tags are editable.
class ArticleEditProxyForm(forms.ModelForm): class Meta: model = ArticleEditProxy fields = ['tags'] class ArticleEditProxyAdmin(admin.ModelAdmin): list_display = ['title', 'tags'] form = ArticleEditProxyForm readonly_fields = ['title', 'body'] admin.site.register(ArticleEditProxy, ArticleEditProxyAdmin)
Now, when you go to the admin area, the user will be able to see the list of articles and will be able to change tags for any article, he will also see the title and content of the article, but will not be able to change them.
Another nuance. Access rights to objects of various models are implemented in jang through objects of the Permission model. Reading is one object of Permission, record - another, one more - removal. Permission objects for new models are created during the run of the
manage.py syncdb
. If at the time of creating the proxy model your application was controlled through the south, then Permission objects will not be created, the south will not “notice” your proxy model, and the syncdb operation will not work with applications serviced by the south
.You will have to create a migration that will send a post_syncdb signal to your proxy model.
class Migration(SchemaMigration): def forwards(self, orm): db.send_create_signal('myapp', ['ArticleEditProxy'])
Details of the hack with migration, I learned in
this blog.