Home > front end >  Django: 'int' object has no attribute 'course'
Django: 'int' object has no attribute 'course'

Time:07-07

i filter a course using id, i got the profile of the course creator and i want to add the user that purchsed the course the course_creator students, but i keep getting this error 'int' object has no attribute 'course'

views.py

@require_http_methods(['GET', 'POST'])
def payment_response(request, user_course_id=None):
    status=request.GET.get('status', None)
    tx_ref=request.GET.get('tx_ref', None) 
    if status == "successful":
        if user_course_id:
            user_course = UserCourse.objects.filter(id=user_course_id).update(paid=True)

            profile = Profile.objects.get(user=user_course.course.course_creator)
            profile.my_students.add(user_course.user)
            student_profile.my_courses.add(user_course.course)

            student_profile.save()
            profile.save()
            user_course.save()

            return render(request, "payment/payment-success.html")
        else:
            return render(request, "payment/payment-failed.html")
    if status == "cancelled":
        return render(request, "payment/payment-failed.html")

CodePudding user response:

The update() method returns the number of updated rows, you want to get a single result so you can use it further on in the view

user_course = UserCourse.objects.get(id=user_course_id)
user_course.paid = True
user_course.save()

CodePudding user response:

The problem lies on the line-

user_course = UserCourse.objects.filter(id=user_course_id).update(paid=True)

.update() method returns the number of rows updated after applying the update. Since you are filtering by ID, there is only one course that fits the criteria. After updating, Django just returns 1.

If you want to apply update and then use the item, you can do the following-

course_dict = UserCourse.objects.filter(id=user_course_id)
course_dict.update(paid=True)
user_course = course_dict.first()

or something similar.

Meanwhile, it might happen that the course ID you provided is not existent (maybe course is deleted, or id is wrong). It'd be better to do the necessary checks.

  • Related