Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot pass GET parameters to django admin custom action view
GET parameters seem to always return empty when attempting to retrieve them from the action view. For example when I add the parameter 'form1' to the form action url, it is missing when I access the request.GET object in the action view. Is it possible to access GET parameters in the action view method somehow? @admin.register(FormDefinition) class FormDefinitionAdmin(BaseAdmin): actions = ('export_forms') def export_forms(self, request, queryset): # returns empty here form_name = request.GET.get('form_name') exporter = FormExporter() file_path = exporter.export_form(form_name) with open(file_path, 'r') as file: response = HttpResponse(file, content_type='application/pdf') response["Content-Disposition"] = "attachment; filename=forms.json" return response -
Django not able to alter queryset in Class Based View with POST with get_queryset
Not really sure how I can't figure this out but I am trying to POST a form to alter the contents of get_queryset() but it isn't keeping the filtered items, it calls get_queeryset multiple times and loses the POST filtering. I must be doing something wrong, can someone help? class GeneralLedgerDatatableView(DatatableView): model = GeneralLedger datatable_class = GeneralLedgerDatatable template_name = 'accounting/general_ledger/general_ledger_list.html' def post(self, request, *args, **kwargs): self.object_list = self.get_queryset() context = self.get_context_data() return self.render_to_response(context) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) title = 'General Ledger: Transaction Detail' context['title'] = title properties = Property.objects.filter(active=True).order_by('name') accounts = GLAccount.objects.all().order_by('sortable_account_identifier') current_property = self.request.session.get('property') if current_property: current_property = current_property.pk form = SelectFilterOptionsForm(self.request.POST or None, properties=properties, accounts=accounts, initial={ 'from_date': timezone.now().replace(day=1, month=1).strftime('%m/%d%/%Y'), 'accounts': [x.pk for x in accounts], 'to_date': timezone.now().strftime('%m/%d%/%Y'), 'property': current_property }) context['form'] = form return context def get_queryset(self): queryset = super().get_queryset() if self.request.POST: # THIS IS CALLED BUT SO IS GET AND ALL ARE RETURNED? property = self.request.POST.get('property') accounts = [x for x in self.request.POST.getlist('accounts') if x] from_date = self.request.POST.get('from_date') to_date = self.request.POST.get('to_date') q_items = list() if property: # filter_dict['journal_line_item__property__pk__in'] = properties q_items.append(Q( property=property, )) q_items.append(Q( account__pk__in=accounts, )) q_items.append( Q( date_entered__date__gte=datetime.datetime.strptime(from_date, '%m/%d/%Y'), date_entered__date__lte=datetime.datetime.strptime(to_date, '%m/%d/%Y'), ) ) queryset = queryset.select_related( 'transaction_code', 'book', 'account', 'property' ).filter(*q_items) return queryset -
How do I use Django with phpMyAdmin? [closed]
So, bear with me as I am very new with this, I followed an guide to create an html site that can have a login system, it used WampServer, Phyton and Django to create it and it works fine, but now I want to do a ticket system on the site, and I am really confused on how do I get or save things that are in the database but are not declared on models.py, things that already got added by Django or tables that I created via phpMyAdmin. If any more context or code is needed I please just tell me, thanks in advance I tried looking for tutorials on the matter but I really suck at this and only get the reverse of what I want -
Django table - replace ID with two primary keys (or something similar)
I have a PostgreSQL table made with Django that looks sorta like this id | user_id | data ++++++++++++++++++++++++++++++++++++ 1119582010 | 1927472901 | foo 0318715789 | 2294819294 | bar 3927284920 | 3281847282 | baz 1610986385 | 3281847282 | qux 1948381983 | 2069385930 | foo 1610986485 | 3103827482 | corge Two different rows can have the same user_id OR the same data, but no two rows share both the same user_id and data. Therefore, since each row is already unique, is there any way I can nix the id row? It takes up a lot of space. Thank you. -
Parallel work of pygame and django. Transferring variables from pygame to the site
I organized a Django-based site following this tutorial tabnine.com/blog/how-to-create-django-projects-in-pycharm-community-edition . I also connected the pygame module and polled which button was pressed. Both programs work well when they are separate. But they do not work in one project. I suspect that the problem may be in the while True of the joystick (gamepad) polling program. I want the website to display the number of the joystick button that was pressed. thanks for the help I tried to integrate gamepad button polling into the pre-built django code, but Python ignores these lines. Commenting while True helps, but then polling the gamepad happens only once while True: for event in pygame.event.get(): if event.type == pygame.QUIT: break if event.type == pygame.JOYBUTTONDOWN: print(event.button) #number of key in console The part of the code where I send the value of the variable to the site. When this is a static number, the program works. But I need to transfer the number of the pressed key from the gamepad def index(request): vf = -8 #instead of vf, I want to transmit event.button print("this is requiest") return render(request, 'hello/index.html', {"name": 'ev386662entеdf', "desc": vf}) -
Subquery Sum returns duplicates
I need to annotate the sum of “reserved_quantity” based on some filters. With this code, I'm getting duplicates and, as a result, an inflated sum. I suspect it's due to filtering based on the reverse foreign key relationship listproduct__productionrequest__writingoffwarehouseproducts=None. def annotate_total_reserved_by_opened_production_lists_quantity(self): return self.annotate( total_reserved_by_opened_production_lists_quantity=Coalesce( Subquery( WarehouseProductReservationMapping.objects.filter( Q( warehouseproduct__current_technology_id=Case( When( warehouseproduct__nomenclature__type__in=( product_structure_api.models.NomenclatureType.ASSEMBLY, product_structure_api.models.NomenclatureType.MANUFACTURED, ), then=OuterRef("current_technology_id"), ), ) ) | Q( warehouseproduct__current_technology_id=None, warehouseproduct__nomenclature__type=product_structure_api.models.NomenclatureType.PURCHASED, ), listproduct__for_list__is_completed=False, warehouseproduct__nomenclature_id=OuterRef("nomenclature_id"), listproduct__productionrequest__writtenoffwarehouseproducts=None, warehouseproduct__quantity__gt=0, ) .order_by() .values("warehouseproduct__nomenclature_id") .annotate(total_reserved_quantity=Sum("reserved_quantity")) .values("total_reserved_quantity")[:1] ), 0, ) ) I've tried using Sum(field, Different=True) and also attempted to add .distinct() and .distinct("id") in different places in the subquery, but it didn't work. Currently, I've come up with the following code (which works correctly without duplicates), but it significantly impacts performance, running approximately 20 times slower. This is not acceptable, and I can't use it in production due to its speed. def annotate_total_reserved_by_opened_production_lists_quantity(self): # Get reservation ids to filter only unique entries. reservation_ids = WarehouseProductReservationMapping.objects.filter( Q( warehouseproduct__current_technology_id=Case( When( warehouseproduct__nomenclature__type__in=( product_structure_api.models.NomenclatureType.ASSEMBLY, product_structure_api.models.NomenclatureType.MANUFACTURED, ), then=OuterRef(OuterRef("current_technology_id")), ), ) ) | Q( warehouseproduct__current_technology_id=None, warehouseproduct__nomenclature__type=product_structure_api.models.NomenclatureType.PURCHASED, ), Q( listproduct__for_list__is_completed=False, listproduct__productionrequest__writtenoffwarehouseproducts=None, ) | Q(for_order_product__isnull=False), warehouseproduct__nomenclature_id=OuterRef(OuterRef("nomenclature_id")), warehouseproduct__quantity__gt=0, ).values("id") subquery = Subquery( WarehouseProductReservationMapping.objects.filter(id__in=reservation_ids) .order_by() .values("warehouseproduct__nomenclature_id") .annotate(total_reserved_quantity=Sum("reserved_quantity")) .values("total_reserved_quantity")[:1] ) return self.annotate( total_reserved_by_opened_production_lists_quantity=Coalesce( subquery, 0, ) ) I would appreciate any help, and thank you in … -
Get the list of a certain column wihout duplicate from model object
I have a model object such as class MyMenu(models.Model): key= m.CharField(max_length=255,unique=True) name = m.CharField(max_length=255) Now there is data like this, key,name a hiro b hiro c fusa d yoshi e yoshio f fusa Now I would like to get the name column without duplication. As a result I would like to get ["hiro","fusa","yoshi","yoshio"] It is possible to do this with for loop, however this way is awkward and slow. Is there any good method to use model object? -
Error while deploying (Not Found The requested resource was not found on this server)
I have deployed a Django-react APP using render.com now the server is live but going into the website https://calendar-app-2lin.onrender.com/only gets this message : in the deployer´s logs I have: here is the repo: https://github.com/SamLCris/calendar_app/blob/master/requirements.txt -
Saving HTML data into JSONField in Django
I have a checksheet with multiple item rows and checkboxes along it. {% for obj in checksheet_items %} <tr class="table-row"> <td class="cell-width"> <p class="cell-content"><span>{{ forloop.counter }}</span></p> </td> <td class="cell-width" colspan="14"> <p class="cell-content text-start"><span>{{ obj.item_name }} {% if obj.checksheet_number == 'E01A ELECTRICAL' and forloop.counter == 14 %} <input class="form-control form-control-sm bg-info" style="width: 50px; display: inline-block;" type="text" name="addition-14" value="{{ check_sheet_data.14.addition }}"><span style="display: inline-block;">M</span>{% endif %}</p> </td> <td class="cell-width text-center"> <input class="exclusive-checkbox-{{ forloop.counter }}" type="checkbox" name="checksheet_{{ checksheet.id }}_ok_{{ forloop.counter }}" id=""> </td> <td class="cell-width text-center"> <input class="exclusive-checkbox-{{ forloop.counter }}" type="checkbox" name="checksheet_{{ checksheet.id }}_na_{{ forloop.counter }}" id=""> </td> <td class="cell-width text-center"> <input class="exclusive-checkbox-{{ forloop.counter }}" type="checkbox" name="checksheet_{{ checksheet.id }}_pl_{{ forloop.counter }}" id=""> </td> </tr> {{ checksheet_data }} {% endfor %} {% block javascript %} <script> document.addEventListener("DOMContentLoaded", function() { {% for obj in checksheet_items %} var checkboxes{{ forloop.counter }} = document.querySelectorAll(".exclusive-checkbox-{{ forloop.counter }}"); checkboxes{{ forloop.counter }}.forEach(function(checkbox) { checkbox.addEventListener("change", function() { checkboxes{{ forloop.counter }}.forEach(function(otherCheckbox) { if (otherCheckbox !== checkbox) { otherCheckbox.checked = false; } }); }); }); {% endfor %} }); </script> {% endblock %} I am storing data in JSONField in my models.py. Everything works fine I am able to save the data by following views.py: if form.is_valid(): check_sheet_data = {} # Initialize a dictionary … -
Djang-admin is not recognized
I am creating a python project , and I am seeing an error saying : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again I have installed python is my system and as well as in VS code , I have also added path to enviroment variables , I am unable to find error -
Fields defined in ANNOTATE are not read by UPDATE
Can't Django use fields defined in annotations in updates? Here's the code. code = self.request.user.code product = Products.objects.filter(code=code) with transaction.atomic(): product_aggregated = product.annotate( pamt=Sum("related_name__product_amt"), psum=Sum("related_name__product_sum"), pmax_date=Max("related_name__product_date"), ).exclude(product_amt=F("amt")) This works fine when we try to print it out with print(). for record in product_aggregated: print(record.pamt) print(record.psum) print(record.pmax_date) 10 10000 2023-11-01 07:50:00.632888 However, if you try to update using it, it won't work. product_aggregated.update( product_amt=Subquery( Products.objects.filter(id=OuterRef("id")).values("pamt")[:1] ), product_sum=Subquery( Products.objects.filter(id=OuterRef("id")).values("psum")[:1] ), product_date=Subquery( Products.objects.filter(id=OuterRef("id")).values("pmax_date")[:1] ), ) I get an error like this Cannot resolve keyword 'pamt' into field. Choices are: product_amt, product_sum, product_date ... Can't Django use fields defined in annotations in updates? -
UWSGI Error with Nginx/Django deployment: ModuleNotFoundError: No module named 'web'
I have been trying to solve this for 3 days now. I can not get uwsgi to load my app correctly. I have tried using virtual environments, rebuilding a new EC2 Ubuntu instance, config changes, different versions of uwsgi, but nothing works. I have another working setup that is the exact same, sans versions, EC2, uwsgi, nginx, django. UWSGI should start with my wsgi.py file, but for some reason it seems like it is looking for a python module named "web" which is the name of my django project. Here are the uwsgi logs: Thu Nov 9 14:11:33 2023 - spawned uWSGI worker 1 (pid: 24452, cores: 1) Thu Nov 9 14:17:33 2023 - SIGINT/SIGTERM received...killing workers... Thu Nov 9 14:17:34 2023 - worker 1 buried after 1 seconds Thu Nov 9 14:17:34 2023 - goodbye to uWSGI. Thu Nov 9 14:17:34 2023 - *** Starting uWSGI 2.0.20-debian (64bit) on [Thu Nov 9 14:17:34 2023] *** Thu Nov 9 14:17:34 2023 - compiled with version: 11.2.0 on 21 March 2022 11:00:44 Thu Nov 9 14:17:34 2023 - os: Linux-6.2.0-1015-aws #15~22.04.1-Ubuntu SMP Fri Oct 6 21:37:24 UTC 2023 Thu Nov 9 14:17:34 2023 - nodename: ip-172-31-30-103 Thu Nov 9 14:17:34 2023 … -
Django filter by two fields rangement
I have a model with two fields: min_age, max_age. And I need to filter it with Django Filters by range of two fields. How can I do that? # models.py class AdvertisementModelMixin(models.Model): min_age = models.PositiveSmallIntegerField( blank=True, null=True, validators=[ MaxValueValidator(80) ] ) max_age = models.PositiveSmallIntegerField( blank=True, null=True, validators=[ MaxValueValidator(80) ] ) -
django commands gets stuck when I run makemigrations or createsuperuser etc
I have a Django application, and when I run python manage.py makemigrations The terminal gets stuck and it doesn't show any output and even ctrl + C doesn't work This isn't happening with all commands commands like createsuperuser, flush, makemigrations aren't working but commands like generateschema work I created another django project and tried running these commands and they work. This issue is happening with only this project and it happened suddenly. -
Error while deploying app (ModuleNotFoundError: No module named 'dj_database_url')
I am using render.com for the deployment of my app but I get the following error : (ModuleNotFoundError: No module named 'dj_database_url') why is that? -
Draw form buttons( using helper) after inline formset via crispy
I want my form to have a pair of "edit" and "return" buttons. These buttons should be at the end of the form, right after the formsets, and on the other hand, for some reason, I need the buttons to be created with crispy helper. If the form is drawn as follows, the formsets are placed under the buttons: {% crispy form %} {% for formset in inlines %} {{ formset.management_form }} {% for formss in formset %} {{ formss.management_form }} {% for fields in formss.visible_fields %} {{ fields|as_crispy_field }} {% endfor %} {% endfor %} {% endfor %} If it is drawn as follows, the buttons will not be drawn: {% for fields in form.visible_fields %} {{ fields|as_crispy_field }} {% endfor %} Is it possible to somehow access the helper inside the template and make it draw the pair of buttons? class UpdateStaffForm(forms.ModelForm): class Meta: fields = ['first_name', 'last_name', 'is_staff'] model = User helper = FormHelper() helper.add_input(Submit('submit', 'Edit Staff', css_class='btn-primary')) helper.add_input(Button('back', 'Back', css_class='btn-secondary', onClick="javascript:history.go(-1);")) helper.form_method = 'POST' class UpdateStaffView(NamedFormsetsMixin, UpdateWithInlinesView): template_name = "pages/staff/update.html" model = User form_class = UpdateStaffForm success_url = "/staff/" inlines = [StaffInline, ] -
Celery inspect remove 10 items limit
I need to get the worker queue size using python and Celery. The code works fine, but result is limited to 10 items. Is there any way to get entire list of queued tasks? I get 100+ items, but only 10 are being returned res = i.reserved() # Names of tasks reserved by the worker reserved_count = len(res[queue_name]) Entire code: app = Celery('myapp', broker='redis://redis:6379/0') # Tist of queue names to inspect queue_names = ['celery@worker.photos', 'celery@worker.videos'] queue_info = {} # Iterate through the queue names for queue_name in queue_names: i = app.control.inspect([queue_name]) a = i.active() # Names of tasks currently being executed by the worker active_count = len(a[queue_name]) res = i.reserved() # Names of tasks reserved by the worker reserved_count = len(res[queue_name]) pretty_queue_name = queue_name.replace('celery@worker.', '') queue_info[pretty_queue_name] = { 'active': active_count, 'reserved': reserved_count, 'total': active_count + reserved_count } return queue_info -
Django Routes intercepting api request and serving index page
I have a urls.py file with the following routes from django.contrib import admin from django.urls import path, include, re_path from rest_framework import routers from .core import views from django.shortcuts import render from .core.views import index as index_view def render_react(request): return render(request, "index.html") router = routers.DefaultRouter() router.register(r'site',views.SiteViewSet,'site') router.register(r'sitestatus',views.SiteStatusView,'sitestatus') router.register(r'lender',views.LenderView,'lender') router.register(r'job',views.JobView,'job') router.register(r'admin_view',views.AdminUploadView,'admin_view') router.register(r'site_geography',views.SiteGeographyView,'site_geography') urlpatterns = [ path('login/', views.ObtainAuthToken.as_view()), path('admin/', admin.site.urls), path('api/', include(router.urls)), re_path(r'^.*$', render_react), re_path(r"^(?:.*)/?$", render_react), # path('',render_react), ] Since serving the static react files via Django with the addition of re_path...xxx it is loading some pages (if supporting data is made with POST requests) but other pages that require api data from the /api route are being intercepted and served the render_react index.html file not the appropriate Api data I've tried changing the order but I expect that when a request is made to the /api route it correctly calls the api urls and is not served the html. -
Updating an auto_now DateTimeField in a parent model in Django Framework
I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code: def save(self): super(Attachment, self).save() self.message.updated = self.updated Will this work, and if you can explain it to me, why? If not, how would I accomplish this? -
ValueError: time data '2023-12-10' does not match format '%Y-%m-%d %H:%M:%S.%f'
While working with django, I am getting this error with expiry_date field declared as DateFeild in model. What should I do to resolve the error? I tried a lot but didn't get the solution. I imported datetime.datetime, etc. but still the error is not resolved. -
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
Why does it trying to connect to localhost when I directly specified "db" as HOST? docker-compose.yml services: web-app: build: . ports: - "8000:8000" volumes: - ./myapp:/myapp command: > sh -c "python manage.py runserver 0:8000" db: image: postgres:13-alpine volumes: - ./myapp_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=Test_overflow_db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Test_overflow_db', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Also once I had slightly different error django.db.utils.OperationalError: connection to server at db ("172.20.0.2"), port 5432 failed: Connection refused, but I tried some stuff after and this has never shown again -
Unnecessary filter code execution in custom filter class
Issue-1 Even if we don't pass any tag in the request query the function datasetfiletagsquery gets executed Issue-2 If I set dataset_id as required then it is enforced in retrieve and other action api functions as well. Context I need to make dataset_id as the required query only when tag query is passed in the request Code class DatasetFileViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet): class DatasetFileFilter(filters.FilterSet): def datasetfiletagsquery(request): try: dataset_id = request.query_params['dataset_id'] qs = Tag.objects.filter(object_id=dataset_id, content_type=ContentType.objects.get_for_model(Dataset), category=Tag.CategoryChoices.DATASET_FILE) except KeyError: raise serializers.ValidationError({'dataset_id': 'This query is required'}) return qs def datasetfiletagsfilter(queryset, name, value): tag_ids = [tag.pk for tag in value] qs = queryset.filter_by_tags(tag_ids) return qs dataset_id = filters.NumberFilter() tag = filters.ModelMultipleChoiceFilter(queryset=datasetfiletagsquery, to_field_name='name', method=datasetfiletagsfilter) class Meta: model = DatasetFile fields = ['dataset_id', 'tag'] queryset = DatasetFile.objects.prefetch_related('tags', 'related_child_dataset_files__child').select_related('datasetbatchfile').extend_order_by() serializer_class = DatasetFileSerializer filterset_class = DatasetFileFilter def get_queryset(self): if self.action == 'download': qs = DatasetFile.objects.all() else: qs = super().get_queryset() qs = qs.filter(dataset__organization_id=self.request.user.organization_id) return qs @action(methods=['POST'], detail=True, url_path='download', serializer_class=DatasetFileDownloadSerializer) def download(self, request, pk): """ api for downloading dataset file """ instance = self.get_object() instance = instance.dataset.get_datasetfiles_for_download(datasetfile_ids=[instance.pk])[0] serializer = self.get_serializer(instance) return Response(serializer.data, status=status.HTTP_200_OK) Expected execution for issue 1 The datasetfiletagsquery function should not be executed if no tag query is present in the request Expected execution for issue 2 The required … -
Add extra action flag to LogEntry in Django
I am registering a custom Log Entry model to django admin Panel. This is the code: class CustomLogEntryAdmin(admin.ModelAdmin): list_display = [ "action_time", "user", "content_type", "shortIds", "object_repr", "action_flag", "shortMessage", ] def shortIds(self, obj): return Truncator(obj.object_id).chars(30) shortIds.short_description = "Object ID" def shortMessage(self, obj): return Truncator(obj.change_message).chars(60) shortMessage.short_description = "Change Message" # list filter list_filter = ["action_time", "user", "content_type"] # search search_fields = ["user__username", "object_repr"] admin.site.register(LogEntry, CustomLogEntryAdmin) there are 3 default action flags of LogEntry ADDITION: int CHANGE: int DELETION: int I want to add a 4th action flag called 'VIEW'. How do I do it? Any help would be appreciated. -
DB architecture of instagram stories like service
Need to create instagram stories like service. I use django rest framework and postgresql as primary db. I stuck with db architecture for stories. I have an idea like: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Story(models.Model): created_at = models.DateTimeField(auto_now_add=True) expire_at = models.DateTimeField() preview = models.OneToOneField('StoryContent') class StoryContent(models.Model): media = models.FileField() duration = models.IntegerField() story = models.ForeignKey(Story) class StoryWatched(models.Model): storyfile = models.ForeignKey(StoryContent) user = models.ForeignKey(User) is_watched = models.BooleanField() watched_at = models.DateTimeField(auto_now_add=True) This is just basic implementation and in models will be extra fields. How to optimize user watched stories table. Let's suppose i have a 100.000 users and they watch 1 story with 4 files in it, it makes 400.000 rows in table story_watched. If there better db architectural solutions you can imagine pls help) -
How do I use TokenObtainPairView to don't return tokens for a class I created myself (inherited from AbstractUser)?
I've created a class that inherits from django's built-in user, which is successful when I want to create a new user by request. But when I access a token using the TokenObtainPairView view, it prompts "{ "detail": "Can't find a valid user for the specified credentials" }". I have configured JWT in the setting: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(days=7), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7) } In the meantime, my model is as follows: class User(AbstractUser): user_avatar = models.ImageField(null=False, blank=True, default='NONE', upload_to=user_avatar_path, validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])]) user_gender = models.CharField(null=True, blank=True, default='NONE', max_length=10, choices=GENDER_CHOICE) user_created_at = models.DateTimeField(auto_now_add=True) user_updated_at = models.DateTimeField(auto_now=True) class Meta: db_table = 'users' verbose_name = "user_table" ordering = ['user_created_at'] def __str__(self): return f"User({self.id}->{self.username})" def __repr__(self): return self.__str__() My url configuration is as follows: urlpatterns = [ path('login/', LoginView.as_view()), path('register/', RegisterView.as_view()), path('password/', PasswordView.as_view()), path('infomation/', UserView.as_view()), path('infomation/<int:pk>', UserDetailView.as_view()), path('token/', TokenObtainPairView.as_view()), path('token/refresh/', TokenRefreshView.as_view()), ] My Serializer is as follows: class LoginTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) data['username'] = self.user.username return data class UserSerializer(serializers.Serializer): username = serializers.CharField(min_length=3, max_length=150) password = serializers.CharField(min_length=6, max_length=20, write_only=True) email = serializers.EmailField(required=False) user_avatar = serializers.ImageField(required=False) user_gender = serializers.ChoiceField(required=False, choices=GENDER_CHOICE) first_name = serializers.CharField(required=False, label='姓') last_name = serializers.CharField(required=False, label='名') is_staff = …