Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Correct way to store JSON into SQL database in React/Python(Django) app
So, I have, in my React application, a method that will generate a json with some settings and data, like this: const generateJSON = async () => { const json = generateManualJSON(caseId); const data = { cdata: customData, settings: json, }; try { const response = await Axios.post(`/manual/${caseId}/generate`, { manual_settings: JSON.stringify(data) }); console.log('response.data', response.data); } catch (error) { setError(arch, true, [error.message]); console.error(error); } }; and this will end up in this View in my Django application: class Manual(APIView): def transaction(self, case_id, action, request): user = request.user manual_settings = request.data['manual_settings'] if (action == 'generate'): CaseAutomationStatusModel.objects.create( current_ind=True, case_id=case_id, created_by=user, modified_by=user, status_comment=manual_wire_settings ) def post(self, request, case_id, action): try: self.transaction(case_id, action, request) return JsonResponse({ 'status': 200, 'message': 'Success' }) except Exception as err: print('*** API error', err) We are using PostgreSQL as database. The purpose of this is that we have a few jobs that run with nextflow and python running in paralel, and it this nextflow job will get this json in the database, and use it. But the problem is, the way it is currently stored, probably due to lack of escape characters, the database string input (which is the one we saved in the react/python project) is breaking up into … -
Chatbot with Knowledge base using GPT 3.5 turbo - Prompt optmizing [closed]
For context, I've been developing a chatbot with Chatgpt in pythom, more precisely, with Django. I am developing a prompt for my chatbot that uses chatgpt and it is giving some problems when I enter a lot of information in it. My goal for this prompt: What I want for my chatbot are short and objective answers, so that they can be as close as possible to a human, without leaving out some information. Problems encountered at the prompt: With my prompt, which I can provide, there are times when the chatbot is able to capture the menu data and there are times when it is not. Also, the chatbot generates some very large responses, passing unnecessary information to customers at that time of the response. The access link for my prompt is: "https://docs.google.com/document/d/1OGAlRGWQbhFbJWKKn5CBXobj3danvVskPsQuZa_CbTk/edit?usp=sharing" What has already been done: What I've been working on for a long time is a prompt for a chatbot that serves customers at a pizzeria. I'm trying to configure the prompt in countless ways but I'm not getting the ideal answers for my business. My prompt already has the menu separated in another context and is called, from the main prompt, through a function. With … -
'django-admin' is not recognized however i installed django
'django-admin' is not recognized as an internal or external command, operable program or batch file. i wrote pip install django and it installed. but when I try this: django-admin --version in cmd it wrote this: 'django-admin' is not recognized as an internal or external command, operable program or batch file. What's the problem?? -
Unable to run Django project with Azure
I have made a website where everything ran on Django. I recently went over to storing data on Azure, but now I am not able to run the server to continue developing. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1128, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mssql' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\osnys\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\osnys\OneDrive\Skrivebord\nordicusv\myenv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File … -
Default value from related model
I have a zipcode table and a persontable. When entering the persons zip I'll need the persons cityfield to be filled with the city from the related ziptable. models.py: from django.db import models class Zip(models.Model): zipcode = models.IntegerField() city = models.CharField(max_length=200) def __str__(self): return str(self.zipcode) class Person(models.Model): name = models.CharField(max_length=200) zipcode = models.ForeignKey('Zip',on_delete=models.CASCADE,related_name="zip_of_this_person") personcity = models.CharField(max_length=200) def __str__(self): return self.name forms.py from django import forms from .models import Zip, Person class ZipForm(forms.ModelForm): class Meta: model = Zip fields = ('zipcode', 'city',) class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'zipcode', 'personcity' ) views.py from django.shortcuts import render, redirect, get_object_or_404 from .forms import PersonForm, ZipForm from .models import Zip, Person # Create your views here. def index(request): return render(request, 'theapp/index.html' ) def person_new(request): if request.method == "POST": form = PersonForm(request.POST) # author_name = '2222'.Zip.city if form.is_valid(): post = form.save(commit=False) post.save() return redirect('person_detail', pk=post.pk) else: form = PersonForm() return render(request, 'theapp/person.html', {'form': form}) def zip_new(request): if request.method == "POST": form = ZipForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('zip_detail', pk=post.pk) else: form = ZipForm() return render(request, 'theapp/zip.html', {'form': form}) def person_detail(request, pk): post = get_object_or_404(Person, pk=pk) weather= "testing purposes" context= { 'post': post, 'weather': weather, } return render(request, 'theapp/person_detail.html', … -
Django signals returns Notification.user must be a "CustomUser" instance
I'm trying to use this method to add a Notifications system to my Django app. I want to notify our users when the Invitation model is created. However, the problem is that the Invitation model does not have a user field, and we don't want to add the user field to the model, because we don't want to make the person who is going to create the Invitation model a user, How can I make the first_name as the one who created the Invitation model, the method I'm using down below return an error: Cannot assign "<Invitation: Adamu>": "Notification.user" must be a "CustomUser" instance. the signals: from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from .models import Level, Notification, Invitation from django.urls import reverse User = settings.AUTH_USER_MODEL @receiver(post_save, sender=Invitation) def comment_post_save(sender, instance, **kwargs): message = f'{instance.first_name} has booked our"{instance.select_type.level} room"' link = reverse('Open-Room', args=[str(instance.select_type.slug)]) notification = Notification(user=instance, message=message, link=link) notification.save() models: class Invitation(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) id_card = models.CharField(max_length=50, choices=ID_CARD) id_number = models.CharField(max_length=100) nationality = models.CharField(max_length=50, choices=LIST_OF_COUNTRY) state = models.CharField(max_length=50) town = models.CharField(max_length=50) address = models.CharField(max_length=90) phone_number = models.IntegerField() guardian_phone_number = models.IntegerField() number_of_day = models.IntegerField() visited_for = models.CharField(max_length=40, choices=VISITED_FOR_THIS) date_created = models.DateTimeField(auto_now_add=True) select_type … -
I wrote a middleware that handles refreshing the access token if expired but it is not properly working, (I use DRF combined with simple jwt )
from datetime import datetime, timezone from rest_framework_simplejwt.tokens import RefreshToken from django.http import HttpResponse from django.utils.deprecation import MiddlewareMixin class TokenRefreshMiddleware(MiddlewareMixin): def process_response(self, request, response): if response.status_code == 200: refresh_token = request.COOKIES.get('refresh_token') if refresh_token: try: decoded = RefreshToken(refresh_token, verify=False) if decoded: if decoded.access_token['exp'] < datetime.datetime.now(timezone.utc).timestamp(): refresh = RefreshToken(refresh_token) response.set_cookie('access_token', refresh.access_token) response.set_cookie('refresh_token', refresh) except: pass if response.status_code == 401: refresh_token = request.COOKIES.get('refresh_token') if refresh_token: print ("refresh_token = = = = = ", refresh_token) try: decoded = RefreshToken(refresh_token, verify=False) if decoded: refresh = RefreshToken(refresh_token) response.set_cookie('access_token', refresh.access_token) response.set_cookie('refresh_token', refresh) response.status_code = 200 except: pass return response hello I m working on the authentication using django (dj-rest-auth), I use httpOnly cookie to store the access token and refresh token so I don't have access to them in the front end, which means I must handle that in the backend, I wrote this middleware to keep refreshing the access token but whenever it is expired I get the response below: { "detail": "Given token not valid for any token type", "code": "token_not_valid", "messages": [ { "token_class": "AccessToken", "token_type": "access", "message": "Token is invalid or expired" } ] } until I reload the page for the second time then the authenticated user shows up -
I'm getting value error while redirecting checkout page in django
error enter image description here my checkout.html enter image description here my payment_done view enter image description here checkout.html is supposed to redirect on orders page after successful payment, but when the payment gets done it gets redirected to this error instead of orders page, i've tried everything from changing the type of cust_id to int, please help me solve this asap this is the github repo link of the code -
Django custom lookup, error on using modulus operation in as_sql()
from django.db.models import Lookup class NotEqual(Lookup): lookup_name = 'div' def as_sql(self, compiler, connection): lhs, lhs_param = self.process_lhs(compiler, connection) rhs, rhs_param = self.process_rhs(compiler, connection) params = lhs_param + rhs_param return "%s %% %s == 0" % (lhs, rhs), params i am using Book.objects.filter(rating__div=5) Error . . . File "D:\PROJECTS\Projects_Personal\django_challenges_venv_\Lib\site-packages\MySQLdb\cursors.py", line 200, in _mogrify query = query % args ~~~~~~^~~~~~ ValueError: unsupported format character '%' (0x25) at index 272 this only happening with modulus operation with % operator, i can use MOD etc. but i wanted to know why with this operator this error happening. i tried to change this operator to other, they work fine but i didn't get anything for this not even in docs -
Django integrity error on parallel requests
I have: IntegrityError duplicate key value violates unique constraint "user_pkey" DETAIL: Key (id)=(3220037) already exists. This happens in this part of the code user = User() user.save() Model is pretty simple, 3 fields. So it happens when there are lot's of parallel requests to my endpoint. I thought Django deals with race condition under the hood in such an easy operation. Database is Postgres, default transaction isolation is read commited. Maybe smth changed with newer Django versions? Do I have to handle race condition by myself in code? -
Problem for import cloudgenix lib in views file on Django
Good morning, As said in the title, I am facing a problem when want to import cloudgenix library into view file using Django framework. from django.shortcuts import render import cloudgenix My error : "Unable to resolve 'cloudgenix' importPylance reportMissingImports" I hope someone can help me I uninstall/install the library and i try to import on other files like models file -
Sync local postgres database with server postgres database?
Currently, I have a PostgreSQL database running on my local server, and everything is functioning well. Now, I want to synchronize this local database with another database on a remote server but only in a specific schema. There are two scenarios to consider: Case I: When an internet connection is available, I need the synchronization to occur immediately between the local and remote databases. Case II: In the absence of an internet connection, I want to store all changes in the local server. Once the internet connection becomes available, the system should automatically transfer all the unsynchronized data from the local server to the remote server. I need guidance on the best approach to achieve this synchronization considering both cases. -
Updating "success_url" adds the content twice after POST method is executed
I am trying to add function which will add entries in the database, its adding the data with out any issues however, when I update the sucess_url with the page I want it to re-direct, Django duplicates the url text in the variable: `class NotesCreateView(CreateView): success_url = 'smart/notes' model = Notes # fields = ['title', 'text'] form_class = NotesForm` It fails with Page Not found error as success_url is sent back with 'smart/notes/smart/notes' instead of 'smart/notes'. I tried updating blank value, debugging edit.py, however, couldn't reach to the root cause of the issue. Is there any parent class that would cause this issue? -
Problem in using Django model's related_query_name
I have two Django projects which share the same model files. I do all the DB migrations on project A, and use the data in project B. Everything works but one thing. I have a User model and Post model class User(models.Model): ... class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,related_name="posts", related_query_name='post') ... Using related_name user.posts.all() works for both projects, but not the related_query_name User.objects.filter(post=[whatever]) works in project A but not B. It reports Django.core.exceptions.FieldError: Cannot resolve keyword 'post' into field. I also have a third project also using the same DB and also works. The difference is project B is not using it as the default DB, but does it matter? I just don't know why related_query_name only works for A project but B. -
Like button in Django + AJAX (dubl)
I want to implement a like button in my project. I want to do this without page reloading, so I googled and decided to use JS's AJAX, but there is one problem, I have absolutely zero knowledge in Javascript and I don't know how this s*** works. So, take a look at my code, I hope someone could help me Or there is a dead end for me Thanks in advance :) Here's views.py def like_place(request, pk): print(request.method) if request.method == "POST": place = Place.objects.get(id=pk) user = request.user if user in place.place_likes.all(): place.place_likes.remove(user) else: place.place_likes.add(user) place_likes_count = place.place_likes.count() return JsonResponse({'likes_count': place_likes_count}) else: return JsonResponse({'error': 'Invalid request.'}, status=400) Here's my html page <div class="search-and-filters"> <form action="" method="GET"> <input type="text" name="search_query" placeholder="Search by cafe name"> <select name="country_filter" style="text-align: center;"> <option value="">Search by country</option> </select> <select name="city_filter"> <option value="">Search by city</option> </select> <button type="submit">Find Place</button> </form> </div> <div class="feed-container"> <div class="comments-section"> <div class="comment"> <div class="comment-nickname">Никнейм</div> <div class="comment-details">commented at (название заведения)</div> <div class="comment-text">Комментарий</div> <div class="comment-date">3 дня назад</div> </div> </div> <div class="posts-section"> <div class="post"> {% for place in places %} <div class="post-title"><a href="{% url 'place_page' place.id %}" style="color: black;">{{ place.place_name }}</a></div> <form method="post"> {% csrf_token %} <button class="button button-like like-button" data-place-id="{{ place.id }}" style="border: none; … -
adding a user in django admin is impossible
I created a customuseradmin model and add a field (age) to it . now when i want to add a user despite using legal characters for username, it gives me error in django admin panel and want me to correct username here is the code of my model from django.db import models from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) and the view from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' and form as well from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields+('age',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields any answer would be appreciated Thanks i did not find any answer after a couple of hours searching the internet -
Original exception text was: 'AnonymousUser' object has no attribute 'email'
This is the error i am getting:AttributeError: Got AttributeError when attempting to get a value for field email on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the AnonymousUser instance. Original exception text was: 'AnonymousUser' object has no attribute 'email'. view.py def get(self, request, *args, **kwargs): user = UserSerializer(request.user) return Response(user.data, status= 200 ) Serializer.py class UserSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) username = serializers.CharField(required=True, validators=[UniqueValidator(queryset=User.objects.all())]) first_name = serializers.CharField(required=True, max_length=32, ) last_name = serializers.CharField(required=True, max_length=32, ) password = serializers.CharField(required=True, min_length=8, write_only=True ) def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token class Meta: model=User fields = ['token', 'email', 'username', 'first_name', 'last_name', 'password', 'id'] I am trying to use the GET method in rest_framework django My email fields is okay in both places -
django.template.exceptions.TemplateSyntaxError: 'i18n' is not a registered tag library
i work on Django==4.2.3. when i try to open admin panel i get error - TemplateSyntaxError at /admin/. here is screenshot of error - second screenshot. my views.py from django.shortcuts import render from .forms import BookedCarForm def book_car(request): if request.method == 'POST': form = BookedCarForm(request.POST) if form.is_valid(): booked_car = form.save(commit=False) booked_car.availability = True booked_car.save() return redirect('success-url') # Redirect to a success page or another view else: form = BookedCarForm() return render(request, 'booking_car.html', {'form': form}) i have other apps too i tried to change code of inner files -
In view testing,client put and delete method is not working as expected
#views.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Order,Pizza,Box,Topping from .serializers import OrderSummarySerializer ,ToppingSerializer,BoxSerializer,PizzaSerializer class OrderListAndDetailApiView(APIView): # 1. List all def get(self, request, *args, **kwargs): order = Order.objects.filter(user = request.user.id) print(order) serializer = OrderSummarySerializer(order, many=True) return Response(serializer.data, status=status.HTTP_200_OK) # 2. Create def post(self, request, *args, **kwargs): print("request body is your request.data",request.data) print("request id:",request.user.id) data = { 'customer': request.data.get('customer'), 'address': request.data.get('address'), 'user': request.user.id } serializer = OrderSummarySerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get_object(self, order_id, user_id): try: return Order.objects.get(id=order_id,user = user_id) except Order.DoesNotExist: return None # 3. update def put(self, request, order_id, *args, **kwargs): order_instance = self.get_object(order_id,request.user.id) return Response( {"res": "Object with order id does not exists"}, status=status.HTTP_400_BAD_REQUEST ) data = { 'customer': request.data.get('customer'), 'address': request.data.get('address'), 'user': request.user.id } serializer = OrderSummarySerializer(instance = order_instance, data=data, partial = True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # 4. Delete def delete(self, request,order_id,*args, **kwargs): order_instance = self.get_object(order_id,request.user.id) if not order_instance: return Response( {"res": "Object with order id does not exists"}, status=status.HTTP_400_BAD_REQUEST ) order_instance.delete() return Response( {"res": "Object deleted!"}, status=status.HTTP_200_OK ) #urls.py from django.urls import path from .views import ( OrderListAndDetailApiView ) urlpatterns = [ path('order', OrderListAndDetailApiView.as_view(),name="order"), path('order/<int:order_id>/',OrderListAndDetailApiView.as_view(),name="details") ] #test.py … -
Django-admin custom logentry for model inlines
I have been struggling to resolve this issue for 2 days now without success... Here is my working admin.py that has custom logentries that are coming straight from the model (imnCode) class imnCodeAdmin(admin.ModelAdmin): list_display = ('imn_code', 'description', 'killlife', 'addcheck') @admin.display(description='IMN Code') def imn_code(self, obj): return obj.code @admin.display(description='Description') def description(self, obj): return obj.text_value @admin.display(description='Kill Life') def killlife(self, obj): return obj.kill_life @admin.display(description='Exclude') def addcheck(self, obj): return obj.add_check fieldsets = ( ('Change Information', { 'fields': ('code', 'text_value', 'kill_life', 'add_check'), }), # Add other fieldsets here if needed ) def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'code': db_field.verbose_name = 'IMN Code' elif db_field.name == 'text_value': db_field.verbose_name = 'Description' elif db_field.name == 'kill_life': db_field.verbose_name = 'Kill Life' elif db_field.name == 'add_check': db_field.verbose_name = 'Exclude' return super().formfield_for_dbfield(db_field, **kwargs) field_custom_names = { 'code': 'IMN Code', 'text_value': 'Description', 'kill_life': 'Kill Life', 'add_check': 'Exclude', } def save_model(self, request, obj, form, change): if change: obj_before = self.model.objects.get(pk=obj.pk) changes = [] for field in obj._meta.fields: field_name = field.attname old_value = getattr(obj_before, field_name) new_value = getattr(obj, field_name) if old_value != new_value: field_verbose_name = self.field_custom_names.get(field_name, field.verbose_name.capitalize()) change_url = reverse('admin:OCR_imncode_change', args=[obj.pk]) changes.append(f"Changed {field_verbose_name}: <strong>FROM:</strong>{old_value} <strong>TO:</strong> {new_value} <strong>FOR: <a href='{change_url}'>{obj.code}</a></strong>") if changes: content_type = ContentType.objects.get_for_model(obj) LogEntry.objects.create( user_id=request.user.pk, content_type_id=content_type.pk, object_id=obj.pk, object_repr=str(obj), action_flag=CHANGE, change_message=", ".join(changes), ) super().save_model(request, … -
Django prefetch related used inside a serializer method making too many queries. How to use prefetch related to reduce queries in following case?
By investigating why some apis are taking too much time to respond I encountered that it's because of the db queries increases as the queryset increases. In Django select related and prefetch related will helps to reduce this problem. Here I am trying to solve such a problem where I used prefetch related in a serializer and still making too much db queries. models.py class Order(models.Model): orderid = models.AutoField(primary_key=True) order_number = models.CharField(max_length=20, unique=True) #.... class SubOrder(models.Model): suborderid = models.AutoField(primary_key=True) orderid = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="orderitems", db_column="orderid" ) order_number = models.CharField(max_length=50) product_quantity = models.PositiveIntegerField() #.... views.py class GetOrderDetailsByStore(mixins.ListModelMixin, generics.GenericAPIView): def get(self, request, order_number=None, *args, **kwargs): start = time.time() logger.info("started %s", start) store_id = self.kwargs["storeid"] status_list = [SubOrder.Suborder_Status.PAYMENT_INITIATED, SubOrder.Suborder_Status.PAYMENT_FAILED, SubOrder.Suborder_Status.PAYMENT_PENDING, SubOrder.Suborder_Status.ORDER_INITIATED] order_items = Order.objects.filter(Q(storeid=store_id) &~Q(order_status__in=status_list)).order_by( "-created_date" ) order_items_eager_loading = AllOrderSellerSerializer.setup_eager_loading( order_items) serializer = AllOrderSellerSerializer(order_items_eager_loading, many=True).data end = time.time() diff = end - start logger.info("ended %s", end) logger.info("time taken %s", diff) return Response({"message": "success", "data": serializer}, status=status.HTTP_200_OK) serializer.py class AllOrderSellerSerializer(serializers.ModelSerializer): orderitems = AllOrderItemsSellerSerializer(many=True) store_reference = serializers.CharField(source="store_reference.store_reference") user_reference = serializers.CharField(source="user_reference.user_reference") number_of_items = serializers.SerializerMethodField("get_number_of_items") class Meta: model = Order fields = ["order_number", "order_request_number", "store_reference", "user_reference","number_of_items", "total_amount", "orderitems"] @staticmethod def get_number_of_items(obj): list_of_pdt_quantity_of_order = [order_item.product_quantity for order_item in obj.orderitems.filter(orderid=obj.orderid)] total_ordered_products_quantity = sum(list_of_pdt_quantity_of_order) return total_ordered_products_quantity # return obj.orderitems.count() … -
python-django: How to debug "OPTIONS /api-token-auth/ HTTP/1.1" 200 0
when a POST request for token authentification is made in a browser, the request is changed to an OPTIONS request due to CORS preflights. I followed this tutorial to adapt for those requests. I now get the django-rest-framework's response "OPTIONS /api-token-auth/ HTTP/1.1" 200 0 which is considered to be an XMLHttpRequest error from the front-end. How do I debug this error? What is the problem here? -
Why does Django's annotate seemingly modify the QuerySet?
I have a model, that (extremely simplified for the example) looks like this: class Car(models.Model): driver = models.ForeignKey(Person, on_delete=models.PROTECT) # details of Person don't really matter here class Meta: managed = False # the project has a shared db with another project, included because I don't know if it's relevant db_table = "cars" I wish to have field called driver_name present on the Car model. My approach to that was to create a custom manager that annotates the queryset: class CarManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( driver_name = models.ExpressionWrapper( models.F("driver__surname") + ", " + models.F("driver__name"), output_field=models.TextField() ) ) and then I set it as Car's manager, objects = CarManager(). Now, by my understanding of annotate, this should just add a new field called driver_name that's a combination of each driver's name and surname, on each of the objects in the default queryset. I must be mistaken though, because there are 10 Car objects in the database, and running Car.objects.all() returns a queryset with a single object. That object happens to be the last Car in the database, but I don't know if that's relevant, since I don't have any way to check. If I remove the annotation from the custom manager, … -
Unable to connect to Postgres from a Docker container
I have two containers on a server, one running a Postgres instance from a docker container. However, I can't seem to be able to connect to PG from inside either of the containers, it just times out. I've tried docker exec -it backend bash followed by: psql --host <server_ip> --port 8080 -U root -d main, which locally prompts for password, but times out here. python then which prints connection info locally and on the server shell, but not from inside the container (exception raised after around a minute). More info: docker logs postgres doesn't show anything helpful. mtu is 1500 for docker0, eth0, and eth1. The server is a basic droplet on Digital Ocean. -
How can i add custom field to admin panel for User Model
How can I add a custom field for the User Model to the admin page? I have defined a Char field to abstract User. Although I can see this field in the database, I can't see it in the Django admin panel. I created a Meta class and wrote my field, but it's still invisible on the admin panel. This issue is not happening with my custom models, only with Django's User model. Can anybody tell me why this is happening and what I should do?