Home > Net >  ValueError: Cannot assign "username'": "Comment.created_by" must be a "
ValueError: Cannot assign "username'": "Comment.created_by" must be a "

Time:09-18

I'm trying to create a comment to a model and I'm getting a ValueError when i try to call the User model. I don't know what I am doing wrong, here are my code snippets

models.py

from django.contrib.auth.models import User

class Comment(models.Model):
    *****
    *****
    created_by = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)

views.py

@api_view(['POST'])
def add_comment(request, course_slug, lesson_slug):
    data = request.data
    name = data.get('name')
    content = data.get('content')
    course = Course.objects.get(slug=course_slug)
    lesson = Lesson.objects.get(slug=lesson_slug)
    comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user.username)
    return Response({'message': 'Comment added successfully'})

urls.py

urlpatterns = [
    ****
    ****
    path('<slug:course_slug>/<slug:lesson_slug>/', views.add_comment),
]

[17/Sep/2022 12:37:52] "OPTIONS /api/v1/courses/python-programming/lesson-one/ HTTP/1.1" 200 0 Internal Server Error: /api/v1/courses/python-programming/lesson-one/ Traceback (most recent call last): File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\rest_framework\decorators.py", line 50, in handler return func(*args, **kwargs) File "E:\Web Projects\Learning Management System\src\courses\views.py", line 41, in add_comment comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=author) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\db\models\query.py", line 451, in create obj = self.model(**kwargs) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\db\models\base.py", line 485, in init _setattr(self, field.name, rel_obj) File "E:\Web Projects\Learning Management System\src\venv\lib\site-packages\django\db\models\fields\related_descriptors.py", line 215, in set
raise ValueError( ValueError: Cannot assign "'[email protected]'": "Comment.created_by" must be a "User" instance. [17/Sep/2022 12:37:52] "POST /api/v1/courses/python-programming/lesson-one/ HTTP/1.1" 500 119197

CodePudding user response:

Change your views like this,

@api_view(['POST'])
def add_comment(request, course_slug, lesson_slug):
    data = request.data
    name = data.get('name')
    content = data.get('content')
    course = Course.objects.get(slug=course_slug)
    lesson = Lesson.objects.get(slug=lesson_slug)
    comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user) # updated here
    return Response({'message': 'Comment added successfully'})

Since created_by is an FK you need to pass the user object, not the user.username

comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user)

CodePudding user response:

comment = Comment.objects.create(course=course, lesson=lesson, name=name, content=content, created_by=request.user)

created_by must be a User object, not a string. so try to provide the User object here.

  • Related