我正在嘗試製作一個小型網站,其中有三種類型的用戶["client" , "volunteer" , "coordinator"]
。每種類型的用戶對它可以訪問的視圖都有限制。所有三個用戶都有不同的登錄頁面。如何在Django中處理多個用戶類型
方法1:要做到這一點,我添加了一個關鍵會議category
,分配登錄在上面給出userTypes,並在任何一個視圖稱爲之一,檢查用戶是否可以訪問視圖。
的login.html:
{% extends "base.html" %}
{% block content %}
{% if form.errors %}
<p class="error"> Sorry , invalid</p>
{% endif %}
<form action="/login_volunteer/authenticate/" method="post">{% csrf_token %}
<label for="username"> Username : </label>
<input type="text" name="username" value="" id="username">
<label for="password"> Password : </label>
<input type="password" name="password" value="" id="password">
<input type="hidden" name="category" value="volunteer" id="category">
<input type="submit" value="login" />
</form>
{% endblock %}
view.py:
def hello(request):
name = "abhishek"
if request.session.session_key is None:
html = '<html><body>Session is expired</body></html>'
return HttpResponse(html)
try:
if not request.POST.get('category') == 'volunteer
html = '<html><body>You are Not allowed here</body></html>'
return HttpResponse(html)
except :
print "error"
html = '<html><body>Hi this is awesome</body></html>'
return HttpResponse(html)
方法2:我以爲我可以創建自定義的用戶類,而不是僅僅使用Django提供的默認User
並在登錄時將CustomUser分配給request.user
。然後當視圖被調用時,我檢查is_Client或is_Volunteer。
customUser.py:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class VolunteerUser(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_volunteer = models.BooleanField(default=False)
class ClientUser(AbstractBaseUser):
"""
Custom user class.
"""
email = models.EmailField('email address', unique=True, db_index=True)
joined = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_Client = models.BooleanField(default=False)
所以我的問題是,這些方法是完成手頭的任務最好的方法是什麼?有沒有其他方法可以解決這個問題?
我也關心安全性,我覺得第一種方法比第二種方法更不安全。
個人而言,我更喜歡使用Django內置的「Group」模型。 https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.Group –