2017-10-20 17 views
0

私は、ログオンしたユーザーのアクセス許可を文字列としてテンプレートに送信するコンテキストプロセスを構築しました。そのユーザーのパーマに基づいて、私はURLを表示または非表示にします。Django-contextのプロセスクエリが102回繰り返される

しかし、私は

デバッグ(IDの変更を知らないだけで、クエリが理由で102回実行されていることがわかるデバッグツールバーアイブを使用して、重複の各IDの3があるかのように見えます)

SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`id` = 35 
    Duplicated 102 times. 
0.6862959744274587% 
23.41 
Sel Expl 
Connection: default 
/itapp/itapp/sites/views.py in site_detail_files(214) 
    'PageType' : 'files', 
/usr/local/lib/python3.6/contextlib.py in __enter__(81) 
    return next(self.gen) 
/itapp/itapp/itapp/context_processors.py in UserPerms(34) 
    'Perms': str(all_perms), 

機能:

def UserPerms(request): 
    from django.contrib.auth.models import Permission 
    all_perms = [] 
    if str(request.user) != 'AnonymousUser': 
     permissions = Permission.objects.filter(user=request.user) 
     group_permissions = Permission.objects.filter(group__user=request.user) 

     all_perms = [] 
     for p in permissions: 
      all_perms.append(p) 
     for p in group_permissions: 
      all_perms.append(p) 
    return { 
     'Perms': str(all_perms), 
    } 

はsettings.pyにテンプレートに追加

TEMPLATES = [ 
    { 
     'BACKEND': 'django.template.backends.django.DjangoTemplates', 
     'DIRS': [ 
      BASE_DIR + '/templates/', 
      ], 
     'APP_DIRS': True, 
     'OPTIONS': { 
      'debug' : DEBUG, 
      'context_processors': [ 
       'django.template.context_processors.debug', 
       'django.contrib.auth.context_processors.auth', 
       'django.contrib.messages.context_processors.messages', 
       'django.template.context_processors.media', 
       'django.template.context_processors.static', 
       'itapp.context_processors.breadcrumb_history', 
       'itapp.context_processors.UserPerms', 
      ], 
     }, 
    }, 
] 

使用例:

<li><a href="{% url 'sites:site_detail_circuits' SiteID %}">Circuits</a> 
{% if "Permission: sites | Circuit Data | Can add Circuit Data" in Perms %}  
    {% if PageType == 'circuits' %} 
    <ul> 
     <li><a href="{% url 'admin:sites_circuits_add' %}?site_data={{ SiteID }}">Add new circuit</a></li> 

    </ul> 
    {% endif %} 
{% endif %} 
</li> 

答えて

1

Django provides a way to check permissions in the template。権限を含む文字列を作成する必要はありません。

{% if perms.sites.add_circuit_data %} 
{% if PageType == 'circuits' %} 
<ul> 
    <li><a href="{% url 'admin:sites.add_circuit' %}?site_data={{ SiteID }}">Add new circuit</a></li> 

</ul> 
{% endif %} 

あなたはこれが機能するために有効に authコンテキストプロセッサを必要とするが、これはデフォルトであるため、設定は何も変更する必要はありませんファイルを生成しました。

+0

うまくいきました、ありがとうございました! – AlexW

+0

このようにグループをチェックすることも可能ですか? – AlexW

+0

'{%if perms.app.perm_name%}'は['user.has_perm']と同じように動作します(https://docs.djangoproject.com/en/1.11/ref/)。 contrib/auth /#django.contrib.auth.models.User.has_perm)を表示します。ユーザーがその権限を持つグループに属している場合はTrueを返します。スーパーユーザーとアクティブフラグも適切に処理します。 – Alasdair

関連する問題