简体   繁体   中英

DJANGO - Multiple Users

I am building a platform in django and for the User registration I followed some tutorials, at this point I think it would be nicer if I can add a "new user registration". In my case "students" can register, login and navigate the platform but I would like also to make a new type of user ( staff) where they can registrate as staff, login and visit only one page where they can create some new quiz.

I tried to look online but I can't figure out how to do it from this point I have already created.

Could you please give me some advice/resources on how can I solve this problem?

account/forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class FormRegistrazione(UserCreationForm):
    email = forms.CharField(max_length=30, required=True, widget=forms.EmailInput())

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

account/views.py

from django.shortcuts import render, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from accounts.forms import FormRegistrazione

# Create your views here.

def registrazioneView(request):
    if request.method == "POST":
        form = FormRegistrazione(request.POST)
        if form.is_valid():
            username = form.cleaned_data["username"]
            email = form.cleaned_data["email"]
            password = form.cleaned_data["password1"]
            User.objects.create_user(username=username, password=password, email=email)
            user = authenticate(username=username, password=password)
            login(request, user)
            return HttpResponseRedirect("/")
    else:
        form = FormRegistrazione()
    context = {"form": form}
    return render(request, 'accounts/registrazione.html', context)

core/views.py

from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.list import ListView

# Create your views here.
from quiz.models import Questions
from jobs.models import post_job





def homepage(request):
    return render(request, 'core/homepage.html')

def userProfileView(request, username):
    user= get_object_or_404(User, username=username)
    jobs = post_job.objects.all()
    categories = Questions.CAT_CHOICES
    scores = []
    for category in categories:
        score = Questions.objects.filter(category=category[0], student= request.user).count()
        scores.append(score)
    context = {

    'user' : user, 'categories_scores' : zip( categories,scores),
    'jobs': jobs



    }
    return render(request, 'core/user_profile.html' , context)



class UserList(LoginRequiredMixin, ListView):
    model = User
    template_name = 'core/users.html'

there are basically two ways of going about this depending how serious this is.

The simplest and easier way is to simply give some users access to admin area and allow them to use the /admin area and create Quizzes there provided you registered your Quiz model in admin.py, if you go this route remember to give them only the permissions required and no more, you can do this in the admin area in the user section.

The second more serious way would be to be an approach followed by this excellent article here . If you follow the article it seems to be exactly what you want. For the quiz creation form and view you can simply make a protected view that requires the user to be teacher as show in the article.

Depending on your specific needs and use case (do you trust staff members? How many people do you expected to use it?) I would probably lean more towards the second approach as allowing end users to access your admin area is a bad practice and can be a security vulnerability. It does require you to write more code tho. Hope this helps.

From what I understand from your question, you want to authenticate users and give them permissions (authorisation) accordingly. I personally prefer using JWT tokens for authentication: https://pypi.org/project/djangorestframework-simplejwt/

It is easy to implement and a secure way to authenticate. Django offers multiple ways to do authorisation, you can start from documentations directly: https://docs.djangoproject.com/en/3.0/topics/auth/default/#permissions-and-authorization

Basically, you will be authenticating users on login/signup for their identity and then giving certain permissions based on the role. If the user isn't authenticated, you will throw 401, and if the user is not authorised for performing certain task, you will throw 403.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM