Home > database >  Associating user id to courses that the user create
Associating user id to courses that the user create

Time:02-18

My django project basically allows users to create its own courses. So, I am trying to associate a user id to the courses that the user created so that it will display only the courses that the user has created when the user wanted to view all the courses that he/she has created. However, it returns an error saying "Cannot assign "1": "Course.user_id_id" must be a "User" instance.". I have been trying to find the solution for days & could not figure out.

models.py

class Users(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)
    profile_pic= models.ImageField(upload_to='media/profile_pic',null=True,blank=True)
    address = models.CharField(max_length=40)
    mobile = models.CharField(max_length=20,null=False)
    Country = models.CharField(max_length=20,null=False, blank=True)
    Company = models.CharField(max_length=20,null=False, blank=True)
    City =  models.CharField(max_length=20,null=False, blank=True)
    State =  models.CharField(max_length=20,null=False, blank=True)
    Zip_Code =  models.IntegerField(blank=True, default="1")
    Telephone =  models.IntegerField(blank=True, default="1")
    Extension =  models.CharField(max_length=20,null=False, blank=True)
    @property
    def get_name(self):
        return self.user.first_name " " self.user.last_name
    @property
    def get_id(self):
        return self.user.id
    def __str__(self):
        return self.user.first_name

class Course(models.Model):
    CATEGORY = (
                ('IT & Software', 'IT & Software'),
                ('Mathematics', 'Mathematics'),
                ('Science', 'Science'),
                ('English', 'English'),
                ('Bahasa Melayu', 'Bahasa Melayu'),
                )

    LEVEL = (
            ('Easy', 'Easy'),
            ('Intermediate', 'Intermediate'),
            ('Advanced', 'Advanced'),
            )

    LANGUAGE = (
               ('English', 'English'),
               ('Bahasa Malaysia', 'Bahasa Malaysia'),
               ('Chineese', 'Chineese'),
               )

    CERTIFICATE = (
                  ('Yes', 'Yes'),
                  ('No', 'No'),
                  )
    user_id_id = models.ForeignKey(User, on_delete = models.CASCADE)
    media = models.ImageField(upload_to = 'media/course')
    title = models.CharField(max_length=300, null = False)
    subtitle = models.CharField(max_length=500, null = False)
    description = models.CharField(max_length=5000, null = False)
    language = models.CharField(max_length=20, null = False, choices=LANGUAGE)
    level = models.CharField(max_length=20, null = False, choices=LEVEL)
    category = models.CharField(max_length=30, null = False, choices=CATEGORY)
    subcategory = models.CharField(max_length=20, null = False)
    price = models.FloatField(null = True)
    roles_responsibilities = models.CharField(max_length=2500, null = False)
    timeline_budget = models.CharField(max_length=250, null = False)
    req_prerequisite = models.CharField(max_length=2500, null = False)
    certificate = models.CharField(max_length=5, null = False, choices=CERTIFICATE)
    slug = AutoSlugField(populate_from='title', max_length=500, unique=True, null=True)

    def __str__(self):
        return self.title

views.py

def createCourse(request):
    user = request.user
    print(user)
    form = CourseForm()
    if request.method == 'POST':
        form = CourseForm(request.POST or None, request.FILES)
        if form.is_valid():
            course = form.save(commit=False)
            course.user_id_id = user.id
            course.save()
            messages.success(request, "Course was successfully created!")
            print('success!')
            return redirect('viewcourse')
        else:
            print('fail')
            messages.error(request, "Please correct the error below!")
    context = { 'form': form }
    return render(request, 'courses/create_course.html', context)

def viewCourse(request):
    user_id = request.user
    user_id = user_id.id
    courses = Course.objects.filter(user_id_id = user_id)
    context = { 'courses': courses }
    print(courses)
    return render(request, 'courses/view_courses.html', context)

CodePudding user response:

It's expecting a User instance. You need either

course.user_id_id = user

or

course.user_id_id_id = user.id   # eeek!

You really need to change that name! Django convention would be

class Course(models.Model):
    ...
    user = models.ForeignKey(User, on_delete = models.CASCADE)

and then

course.user_id = user.id     # makes sense

CodePudding user response:

You would have to do something like this to get the courses of a user:

from .models import User 

def viewCourse(request):
    user_id = User.objects.get(user=request.user)
    courses = Course.objects.filter(user_id_id = user_id)
    context = { 'courses': courses }
    print(courses)
    return render(request, 'courses/view_courses.html', context)
  • Related