Home > Mobile >  How to give access for a model object to a specific user in Django
How to give access for a model object to a specific user in Django

Time:03-21

I am doing an online classroom project in Django where I created a model named create_course which is accessible by teachers. Now I am trying to design this as the teacher who creates a class only he can see this after login another teacher shouldn't see his classes and how to add students into that particular class I created

the course model

class course(models.Model):
    course_name = models.CharField(max_length=200)
    course_id = models.CharField(max_length=10)
    course_sec = models.IntegerField()
    classroom_id = models.CharField(max_length=50,unique=True)

views.py

def teacher_view(request, *args, **kwargs):
    form = add_course(request.POST or None)
    context = {}
    if form.is_valid():
        form.save()
        return HttpResponse("Class Created Sucessfully")
    context['add_courses'] = form
    return render(request, 'teacherview.html', context)

forms.py

from django import forms
from .models import course

class add_course(forms.ModelForm):
    class Meta:
        model = course
        fields = ('course_name', 'course_id', 'course_sec', 'classroom_id')

CodePudding user response:

Add one more field in course model that establish relationship with User model. Hence you can get the details about the teacher who has created course.

    from django.contrib.auth.models import User

    class course(models.Model):
        course_name = models.CharField(max_length=200)
        course_id = models.CharField(max_length=10)
        course_sec = models.IntegerField()
        classroom_id = models.CharField(max_length=50,unique=True)
        created_by = models.ForeignKey(User, on_delete=models.CASCADE)

In your view function, you can check whether logged in user is same as the created of the requested course.

    def teacher_view(request, *args, **kwargs):
        # since this is course specific view, you will be passing an identiier or pk of the course as an argument to this function.
        course_obj = Course.objects.get(id="identifier")
        if request.user == course_obj.created_by:
            # logged in user is same as the creator of the course
        else:
            # redirect

I would prefer creating permissions and having those in specific models. You can give it a try with that too. Let me know, if it doesn't work.

  • Related