Django Part 2, 10-Getting current user's profile

I have an issues with the error return 1048, “Column ‘user_id’ cannot be null” and check the code in the finish lesson but still are not able to find the solution.

…/store/Serializers.py

class CustomerSerializer(serializers.ModelSerializer):
user_id = serializers.IntegerField(read_only=True)

class Meta:
    model = Customer
    fields = ['id', 'user_id', 'phone', 'birth_date', 'membership']

…/store/views.py

class CustomerViewSet(CreateModelMixin, RetrieveModelMixin, UpdateModelMixin, GenericViewSet):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

@action(detail=False, methods=['GET', 'PUT'])
def me(self, request):
    (customer, created) = Customer.objects.get_or_create(user_id=request.user.id)
    if request.method == 'GET':
        serializer = CustomerSerializer(customer)
        return Response(serializer.data)
    elif request.method == 'PUT':
        serializer = CustomerSerializer(customer, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

…/store/models.py

class Customer(models.Model):
MEMBERSHIP_BRONZE = ‘B’
MEMBERSHIP_SILVER = ‘S’
MEMBERSHIP_GOLD = ‘G’

MEMBERSHIP_CHOICES = [
    (MEMBERSHIP_BRONZE, 'Bronze'),
    (MEMBERSHIP_SILVER, 'Silver'),
    (MEMBERSHIP_GOLD, 'Gold'),
]
phone = models.CharField(max_length=255)
birth_date = models.DateField(null=True, blank=True)
membership = models.CharField(
    max_length=1, choices=MEMBERSHIP_CHOICES, default=MEMBERSHIP_BRONZE)
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

def __str__(self):
    return f'{self.user.first_name} {self.user.last_name}'

@admin.display(ordering='user__first_name')
def first_name(self):
    return self.user.first_name

@admin.display(ordering='user__last_name')
def last_name(self):
    return self.user.last_name

class Meta:
    ordering = ['user__first_name', 'user__last_name']

…/core/serializers.py
class UserCreateSerializer(BaseUserCreateSerializer):
class Meta(BaseUserCreateSerializer.Meta):
fields = [‘id’, ‘username’, ‘password’, ‘email’, ‘first_name’, ‘last_name’]

class UserSerializer(BaseUserSerializer):
class Meta(BaseUserSerializer.Meta):
fields = [‘id’, ‘username’, ‘email’, ‘first_name’, ‘last_name’]

ERROR MESSAGE!!!
Traceback (most recent call last):
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/core/handlers/exception.py”, line 55, in inner
response = get_response(request)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/core/handlers/base.py”, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/views/decorators/csrf.py”, line 54, in wrapped_view
return view_func(*args, **kwargs)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/rest_framework/viewsets.py”, line 125, in view
return self.dispatch(request, *args, **kwargs)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/rest_framework/views.py”, line 509, in dispatch
response = self.handle_exception(exc)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/rest_framework/views.py”, line 469, in handle_exception
self.raise_uncaught_exception(exc)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/rest_framework/views.py”, line 480, in raise_uncaught_exception
raise exc
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/rest_framework/views.py”, line 506, in dispatch
response = handler(request, *args, **kwargs)
File “/Users/rogerlooser/Documents/Privat_Roger/Schule/Python/storefront/store/views.py”, line 91, in me
(customer, created) = Customer.objects.get_or_create(user_id=request.user.id)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/manager.py”, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/query.py”, line 935, in get_or_create
return self.create(**params), True
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/query.py”, line 671, in create
obj.save(force_insert=True, using=self.db)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/base.py”, line 812, in save
self.save_base(
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/base.py”, line 863, in save_base
updated = self._save_table(
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/base.py”, line 1006, in _save_table
results = self._do_insert(
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/base.py”, line 1047, in _do_insert
return manager._insert(
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/manager.py”, line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/query.py”, line 1790, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/models/sql/compiler.py”, line 1660, in execute_sql
cursor.execute(sql, params)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/src/django-debug-toolbar/debug_toolbar/panels/sql/tracking.py”, line 230, in execute
return self._record(self.cursor.execute, sql, params)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/src/django-debug-toolbar/debug_toolbar/panels/sql/tracking.py”, line 154, in _record
return method(sql, params)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/backends/utils.py”, line 103, in execute
return super().execute(sql, params)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/backends/utils.py”, line 67, in execute
return self._execute_with_wrappers(
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/backends/utils.py”, line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/backends/utils.py”, line 89, in _execute
return self.cursor.execute(sql, params)
File “/Users/rogerlooser/.local/share/virtualenvs/storefront-JGOY8xqq/lib/python3.10/site-packages/django/db/backends/mysql/base.py”, line 80, in execute
raise IntegrityError(*tuple(e.args))
django.db.utils.IntegrityError: (1048, “Column ‘user_id’ cannot be null”)
[26/Dec/2022 15:16:38] “GET /store/customers/me/ HTTP/1.1” 500 206743
/Users/rogerlooser/Documents/Privat_Roger/Schule/Python/storefront/store/views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks…

Maybe somebody of you guys find the issue

Hi @Trycos, I was having the same issue after the lesson when sending requests to “/store/customers/me” route.

The reason is we have allowed non-authenticated requests to “/me” route and it expects the user to be authenticated.

In non-authenticated requests, request.user returns an AnonymousUser class object and request.user.id returns None. And, in “/me” action of CustomerViewSet at line:

(customer, created) = Customer.objects.get_or_create(user_id=request.user.id)

user_id argument is given None value which raises the Exception because user_id cannot be null when creating a customer.

To solve this we should not allow non-authenticated requests to “/me” action and here is how I did it:

def get_permissions(self):
    if self.request.method == "GET" and self.action != "me":
        return [AllowAny()]
    return [IsAuthenticated()]

I added another check self.action != "me" in get_permissions function of CustomerViewSet.

I have presently facing @Trycos issues and there seems to be no way out. I tired @nauman implementations but the AllowAny() and IsAuthenticated() call got highlighted. Please guys, help is really needed here.
Thanks.

hey, I have same issue and I used @nauman solution too but not answered. Anybody has reached to a solution?