Reputation: 641
In my project, I have 2 models named Students and Teachers. These two models are a OneToOne field to User. I have 3 applications : home (index page, faq, about...), teachers (interface for teacher, manage her courses, edit profil ...) and students (interface for students, profil ...)
I have one login form (in application home), and I want to use it for log in teachers and students, and redirect to the correct application after authentication. What is the best way for doing that ? I think to create two groups (teachers and students) and assign to the correct group after registration form, and in log in form, just check the group ?
PS: Student can create an account, but for teacher, our team creates accounts, so we don't have a registration form for teachers
Upvotes: 0
Views: 393
Reputation: 821
If relation to User table is OneToOne, you can access it from user.student or user.teacher, so you would do it...
def login_view(request):
if form.is_valid():
# get user from form
_user = form.get_user()
user = authenticate(form.cleaned_data['username'], form.cleaned_data['password'])
login(request, user)
if hasattr(user, 'student'):
# You'll return to student app
return redirect('studen:home')
# else
return redirect('teacher:home')
EDIT
decorators.py
...
from django.contrib.auth.decorators import user_passes_test
def group_required(*args):
if args:
def decorator(user):
if user.is_staff or user.is_superuser:
return True
return user.is_authenticated() and user.groups.filter(name__in=args).exists()
else:
decorator = lambda x: x.is_authenticated()
return user_passes_test(decorator)
...
And use it...
...
@group_required('student')
def home_student(request):
# some code
@group_required('teacher', 'student'):
def common_view_for_all(request):
# some code
...
Upvotes: 1