Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python - Permission to view, but not to change! - Django

is it possible to give users the permission to view, but not to change or delete.

currently in the only permissions I see are "add", "change" and "delete"... but there is no "read/view" in there.

I really need this as some users will only be able to consult the admin panel, in order to see what has been added in.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update: Since Django 2.1 this is now built-in.

In admin.py

# Main reusable Admin class for only viewing
class ViewAdmin(admin.ModelAdmin):

    """
    Custom made change_form template just for viewing purposes
    You need to copy this from /django/contrib/admin/templates/admin/change_form.html
    And then put that in your template folder that is specified in the 
    settings.TEMPLATE_DIR
    """
    change_form_template = 'view_form.html'

    # Remove the delete Admin Action for this Model
    actions = None

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    def save_model(self, request, obj, form, change):
        #Return nothing to make sure user can't update any data
        pass

# Example usage:
class SomeAdmin(ViewAdmin):
    # put your admin stuff here
    # or use pass

In change_form.html replace this:

{{ adminform.form.non_field_errors }}

with this:

<table>
{% for field in adminform.form %}
    <tr>
      <td>{{ field.label_tag }}:</td><td>{{ field.value }}</td>
    </tr>
{% endfor %}
</table>

Then remove the submit button by deleting this row:

{% submit_row %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...