Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got attribute error when trying creating model
I got this error message Got AttributeError when attempting to get a value for field id on serializer IngredientSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Ingredient instance. Original exception text was: 'Ingredient' object has no attribute 'ingredient'. when trying to save model in DRF. My serializers: from django.db import transaction from rest_framework import serializers from .models import Recipe, Ingredient, RecipeIngredient, Tag class IngredientSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField( queryset=Ingredient.objects.all(), source="ingredient" ) amount = serializers.IntegerField() class Meta: model = RecipeIngredient fields = ["id", "amount"] class CreateRecipeSerializer(serializers.ModelSerializer): ingredients = IngredientSerializer(many=True) tags = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), many=True) image = serializers.ImageField(required=False) name = serializers.CharField(source="recipe_name") class Meta: model = Recipe fields = ["name", "image", "text", "cooking_time", "ingredients", "tags"] def create(self, validated_data): ingredients_data = validated_data.pop("ingredients") tags_data = validated_data.pop("tags") with transaction.atomic(): recipe = Recipe.objects.create(**validated_data) recipe.tags.set(tags_data) recipe_ingredients = [ RecipeIngredient( recipe=recipe, ingredient=ingredient_data["ingredient"], amount=ingredient_data["amount"], ) for ingredient_data in ingredients_data ] RecipeIngredient.objects.bulk_create(recipe_ingredients) return recipe And my models here class Ingredient(models.Model): """Модель ингредиентов.""" ingredient_name = models.CharField( max_length=MAX_LENGTH_200 ) measurement_unit = models.CharField( max_length=MAX_LENGTH_200 ) class Recipe(models.Model): ingredients = models.ManyToManyField( Ingredient, through="RecipeIngredient", related_name="recipes", ) tags = models.ManyToManyField(Tag, related_name="recipes") author = models.ForeignKey( User, on_delete=models.CASCADE, related_name="recipes" ) recipe_name = models.CharField( max_length=MAX_LENGTH_200 ) image = models.ImageField( upload_to="recipes/images/" ) text = … -
Send an http request from django server inside docker container to another server that is located on localhost not inside docker
I have a django project inside docker container. I have several containers for backend, frontend, redis, celery and db thar are served by docker compose. I need to send an http request made by python lib requests to a server that is outside of docker but is started on the same computer (on localhost). This code worked perfectly when django server wasn't inside docker container. There is 500 status code from this function at the moment. How can i do this? Function that should send request: class ConnectLocalHost(APIView): response = requests.post('http://127.0.0.1:9001') return Httpresponse('Message sent', status=status.HTTP_200_OK) docker-compose.yml file: # docker-compose.yml version: "3" volumes: db-data: storage: services: backend: working_dir: /backend build: context: ./backend dockerfile: Dockerfile ports: - "8000:8000" command: bash -c " ./wait-for-postgres.sh database user user123 postgres && python manage.py makemigrations --settings=test_project.prod_settings && python manage.py makemigrations task_manager_app --settings=test_project.prod_settings && python manage.py migrate --settings=test_project.prod_settings && python manage.py migrate task_manager_app --settings=test_project.prod_settings && python manage.py collectstatic --noinput --settings=test_project.prod_settings && python manage.py auto_superuser --settings=test_project.prod_settings && gunicorn test_project.wsgi:application --bind 0.0.0.0:8000" volumes: - storage:/backend/storage/ depends_on: - database - redis environment: REDIS_HOST: redis POSTGRES_USER: user POSTGRES_PASSWORD: user123 POSTGRES_DB: postgres POSTGRES_PORT: 5432 restart: always frontend: working_dir: /frontend build: context: ./frontend dockerfile: Dockerfile command: yarn start ports: - "9000:9000" depends_on: - … -
Django Tastypie API Slow Response Time with Annotate Count and Pagination
I'm working with a Django Tastypie API that processes a large QuerySet. I need to perform an annotate with a Count on a related table, which is also very large. Afterward, I return the response using paginator to handle the pagination. However, the API is taking a significant amount of time to return the results. Here is a simplified version of the annotate that seems to be causing the most delay: .annotate( dynm_calc=Count('devices', filter=Q(devices__groups__id__in=ids_list), distinct=True) ) My main concerns are: QuerySet Evaluation: Is the entire QuerySet being evaluated despite using pagination? If so, could this be the reason for the slow response times? Performance Optimization: How can I optimize this query or improve the performance of the API response? Splitting the QuerySet: Would splitting the QuerySet into smaller parts before applying the annotate be beneficial? If yes, how can this be effectively implemented? Any insights or suggestions on how to tackle this issue would be greatly appreciated. Thank you! -
How to recover Django users password after migrating project to a different server
I migrated my Django project to a different server, so I figured that the database is the most important thing on the server since my code is on GitHub and my media files on S3 bucket. So I made a backup of the database as an SQL dump. I setup my project, restored the database, configure my domain etc. and everything seems like nothing changed (works well). Then I tried to login but it says incorrect password. I'm thinking the way Django hash the password has changed which makes it not match the hash on the database. Every data on the database is up to date. How can I recover the password of the users and what are best practice methods to midrate successfully? I don't have access to the old server anymore. -
Django Allauth: Keycloak Authentication Fails with "Connection Refused" Error
Django Allauth: Keycloak Authentication Fails with "Connection Refused" Error `I'm integrating Keycloak with my Django application using django-allauth for OpenID Connect authentication. I've set up the configuration, but when I click on the "Login with Keycloak" link, I encounter the following error: HTTPConnectionPool(host='localhost', port=8081): Max retries exceeded with url: /realms/customercloud/.well-known/openid-configuration (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f8d322fb100>: Failed to establish a new connection: [Errno 111] Connection refused')) /**login.html **/ <a href="{% provider_login_url 'openid_connect' %}">Login with Keycloak</a> `SOCIALACCOUNT_PROVIDERS = { "openid_connect": { "APP": { "provider_id": "keycloak", "name": "Keycloak", "client_id": "myclient", "secret": "********************", "settings": { 'server_url': 'http://localhost:/realms/customercloud/.well-known/openid-configuration', 'client_id': 'myclient', 'redirect_uri': 'http://localhost:***/', }, } } } ` ' -
Django Rest giving error Exception value: .accepted_renderer not defined in response
I am participating in a course and in it an activity was just to copy and paste the code provided and to use postman, but when I did this I got this error that is in the title, follow the code Minha views.py from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework import status from .models import Livro from .serializers import LivroSerializer @csrf_exempt def livro_list_create(request): if request.method == 'GET': livros = Livro.objects.all() serializer = LivroSerializer(livros, many=True) return Response(serializer.data) if request.method == 'POST': serializer = LivroSerializer(data=request.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) @csrf_exempt def livro_detail(request, pk): livro = Livro.objects.get(pk=pk) if request.method == 'GET': serializer = LivroSerializer(livro) return Response(serializer.data) if request.method == 'PUT': serializer = LivroSerializer(livro, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) if request.method == 'DELETE': livro.delete() return Response(status=status.HTTP_204_NO_CONTENT) urls.py from django.urls import path from .views import livro_list_create, livro_detail urlpatterns = [ path('livros/', livro_list_create, name='livros-list-create'), path('livros/<int:pk>/', livro_detail, name='livro-detail'), ] serializer.py from rest_framework import serializers from .models import Categoria, Autor, Livro class CategoriaSerializer(serializers.ModelSerializer): class Meta: model = Categoria fields = ['id', 'nome'] class AutorSerializer(serializers.ModelSerializer): class Meta: model = Autor fields = ['id', 'nome'] class LivroSerializer(serializers.ModelSerializer): class Meta: model = Livro fields = ['id', 'titulo', 'autor', 'categoria', … -
downloading large file from S3 is failed with django
I uploaded a large zip file (6.7GB) to S3 via Django code: @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True) @aws_exception_handler def upload_file(self, file_path, key, tags=None, extra_args={}): absolute_key = generate_key(key) transfer_config = TransferConfig( multipart_threshold=1024 * 1024 * 4, multipart_chunksize=1024 * 1024 * 16, max_io_queue=1000, max_concurrency=max_workers, use_threads=True ) with open(file_path, 'rb') as data: self.s3_client.upload_fileobj(data, self.bucket_name, absolute_key, Config=transfer_config, ExtraArgs=extra_args) if tags: try: put_object_tagging_kwargs = { 'Key': self._get_absolute_key(key), 'Bucket': self.bucket_name, 'Tagging': { 'TagSet': [ {'Key': tag_key, 'Value': tag_value} for tag_key, tag_value in tags.items() ] } } self.s3_client.put_object_tagging(**put_object_tagging_kwargs) except Exception as ex: raise ex Then I tried to download it through the UI with this code in the server (I tried each of those methods, and the result is the same as I describe below): def check_file_exists_retry_predicate(exception): return False if isinstance(exception, CloudStorageObjectDoesNotExists) else True @retry( retry=retry_if_exception(check_file_exists_retry_predicate), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True ) @aws_exception_handler def download(self, key, stream=False): obj = self.s3_client.get_object(Bucket=self.bucket_name, Key=self.generate_key(key)) if stream: return obj['Body'] return obj['Body'].read().decode(self._decode_format) @retry( retry=retry_if_exception(check_file_exists_retry_predicate), stop=stop_after_attempt(3), wait=wait_exponential(multiplier=3), reraise=True ) @aws_exception_handler def download_file(self, file_path, key): file_folder_path = os.path.dirname(file_path) if file_folder_path: mkdir_by_path(file_folder_path) with open(file_path, 'wb') as fh: transfer_config = TransferConfig( multipart_threshold=1024 * 1024 * 4, multipart_chunksize=1024 * 1024 * 16, max_io_queue=1000, max_concurrency=max_workers, use_threads=True ) absolute_key = self.generate_key(key) self.s3_client.download_fileobj(self.bucket_name, absolute_key, fh, Config=transfer_config) The download starts but stops suddenly after a … -
Django custom lookup, rhs receives %s only
I want to create a custom icontainsall lookup such that when a user searches for a phrase with a space in it, I want to convert it into a like on all words with AND (so that order of word does not matter). i.e. If user searches for 'egg milk', the predicate becomes name LIKE %egg% AND name LIKE %milk%. This is how my lookup looks: from django.db.models import CharField, Lookup, TextField class CaseInsensitiveContainsAllLookup(Lookup): lookup_name = 'icontainsall' def as_sql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) print(rhs) # shows %s and not 'egg milk' predicate, params = [], [] # escape \ and % rhs_list = rhs.replace('\\', '\\\\').replace('%', '\\%').split(' ') for rhs in rhs_list: params += lhs_params + rhs_params predicate.append(f"LOWER({lhs}) LIKE LOWER({rhs})") return ' AND '.join(predicate), params CharField.register_lookup(CaseInsensitiveContainsAllLookup) TextField.register_lookup(CaseInsensitiveContainsAllLookup) However, rhs receives only %s and not egg milk. How can I go about achieving what I want using a lookup? -
How do I check if a user is not in any group in Django?
I have created some groups in the Django Admin Panel, and users without a group are considered default users. If a user sends a request, how do I check to see if they don't have any groups assigned, similar to request.user.groups.filter(name="Group Name") but reversed? -
I would like to express that query through Django orm
My project have 4 models stock/models.py class StockIndex(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Stock(models.Model): code = models.CharField(max_length=24) name = models.CharField(max_length=128) price = models.DecimalField(max_digits=10, decimal_places=2) dividend_rate = models.DecimalField(decimal_places=2, max_digits=4) index = models.ForeignKey(StockIndex, related_name='stocks', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name class StockSet(models.Model): code = models.ForeignKey(Stock, related_name='stock_set', on_delete=models.CASCADE) quantity = models.IntegerField() owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='stock_set', to_field='wallet') def __str__(self): return f'{self.owner} - {self.code}' users/models.py class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() username = models.CharField( max_length=150, unique=True, ) email = models.EmailField(blank=True) is_staff = models.BooleanField( default=False, ) is_active = models.BooleanField( default=True, ) wallet = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) EMAIL_FIELD = "email" USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email"] def __str__(self): return self.username All I want is to get each user's assets. The way to evaluate users' assets is to multiply the StockSet object by the Stock Price and the quantity field and add it all. The database use is mariadb and I know how to get the value from the query. SELECT u.username, u.email, SUM(st.quantity * s.price) AS user_asset FROM stock_stockset st JOIN users_user u ON (st.owner_id = u.wallet) JOIN stock_stock s ON (st.code_id = s.id) GROUP BY u.username; But I don't know how to express the above query in Django ORM. class UserView(ListAPIView): queryset … -
Render Deployment could not install GUNICORN
When render deploys my Django App, it installs everything from the requirements.txt except for gunicorn. I've tried changing the version and also tried other wsgi servers but they are all not working. Can someone help me with this? -
I can't run manage.py server, anyone my fellow programmers? [closed]
It is giving me this error in both vs code and pycharm C:\Program Files\Python312\python.exe: can't open file 'C:\\Users\\HP\\Desktop\\Django\\manage.py': [Errno 2] No such file or directory I ran this command> python manage.py runserver but it issued an error -
'uv' is not recognized as an internal or external command in Windows when trying to create a virtual environment
I'm trying to create a virtual environment in Windows using the uv command, but I keep encountering the following error: 'uv' is not recognized as an internal or external command, operable program or batch file. 1] Installation: I installed uv using pip install uv within my Python environment. I verified the installation by running pip list, and uv appears in the list of installed packages. 2] Path Configuration: I checked my PATH environment variable and confirmed that the Python Scripts directory (where uv.exe should reside) is included. I tried using the full path to the uv executable, but the error persists. 3] Environment Setup: I ensured that my virtual environment was properly created and activated using: python -m venv myenv myenv\Scripts\activate 4] Other Commands: Other Python-related commands like pip, python, etc., work fine without issues. I also tried uninstalling and reinstalling uv but still face the same problem. Why is the uv command not being recognized despite being installed and listed by pip? How can I resolve this issue and successfully create a virtual environment using uv? -
Runtime.ImportModuleError: Unable to import module 'vc__handler__python' if the root folder is set one level above the server folder on vercel
I recently watched video “Deploy Django Project on Vercel with Supabase PostgreSQL: Step by Step Guide”. I followed this video step by step, and my project was really deployed. But it deployed if i picked my folder python_server/ as root directory. But I need to select the folder one level up as root directory. I have project structure like this: Project/ ├── python_server/ │ ├── __init__.py │ ├── mysite/ │ │ ├── __init__.py │ │ ├── settings.py │ │ ├── urls.py │ │ ├── wsgi.py │ ├── manage.py │ ├── gif_service/ │ │ ├── templates │ │ ├── views.py │ │ ├── urls.py │ ├── static │ ├── staticfiles ├── public ├── views ├── js_server I copied my static files from /public and views from /views to /python_server. And I picked /python_server as folder root. It’s works well for vercel. But it’s not good for me. Because I use views from /views and static files from /public for both server: Express server and Django. And so It’s not good practice to have copy of that static and html files. So I need to deploy vercel not with python_server/ as root folder, but with Project/ as root folder. I really tried … -
Not able to select database for database queries in django
I'm trying to direct my read queries to my read replica in a production setup. Django allows defining multiple databases, so I added two databases like: DATABASES = { "default": { "NAME": "ironbank", "ENGINE": "django_postgrespool2", "USER": "postgres", "PASSWORD": os.getenv("DATABASE_PASSWORD", "postgres"), "HOST": os.getenv("DATABASE_HOST", "localhost"), "PORT": os.getenv("DATABASE_PORT", "5432"), "CONN_MAX_AGE": 0, }, "replica": { "NAME": "ironbank_replica", "ENGINE": "django_postgrespool2", "USER": "postgres", "PASSWORD": os.getenv("DATABASE_PASSWORD", "postgres"), "HOST": os.getenv("REPLICA_DATABASE_HOST", "localhost"), "PORT": os.getenv("REPLICA_DATABASE_PORT", "5432"), "TEST": { "MIRROR": "default", }, "CONN_MAX_AGE": 0, }, } Here I'm using two different databases to test it setup locally. I also have a database router configured as file: settings.py DATABASE_ROUTERS = ["ironbank.router.PrimaryReplicaRouter"] --- file: ironbank/router/PrimaryReplicaRouter.py class PrimaryReplicaRouter: @staticmethod def db_for_read(model, **hints): """ Reads go to a randomly-chosen replica. """ # some model specific logic here, but removed for simplicity return "replica" @staticmethod def db_for_write(model, **hints): """ Writes always go to primary. """ return "default" @staticmethod def allow_relation(obj1, obj2, **hints): """ Relations between objects are allowed if both objects are in the primary/replica pool. """ return True @staticmethod def allow_migrate(db, app_label, model_name=None, **hints): """ Allow migrations on default database only. """ return db == "default" Findings I've been using shell_plus and manual data inspection to check the result being returned by the query is … -
How to Rank Students Based on Total Points in Django QuerySet When Filtering Results
I'm working on a Django application where I need to rank students based on their total points and then filter the results. I want to rank all students based on their total points but only show students who are children of a particular user (supervisor). class StudentQuerySet(SetFieldQuerySetMixin, models.QuerySet): """QuerySet for Student model""" def with_total_active_courses(self, alias: bool = False) -> Self: """Adds a field indicating total active courses of a student.""" return self.set_field( "total_active_courses", models.Count( "enrollments", filter=models.Q( enrollments__is_active=True, enrollments__start_date__lt=Now(), enrollments__expiration_date__gt=Now(), ), ), alias, ) def with_attendance_count(self, course_class_id: int) -> Self: """ Adds fields indicating attendance count of a student for given course class. """ return self.annotate( present=self._get_attendance_count( course_class_id, AttendanceStatus.PRESENT ), absent=self._get_attendance_count( course_class_id, AttendanceStatus.ABSENT ), excused=self._get_attendance_count( course_class_id, AttendanceStatus.EXCUSED ), ) def with_points(self) -> Self: """Adds a field indicating total points of a student.""" return self.annotate( total_points=Coalesce( models.Sum("attendances__feedback__overall"), Value(0) ) ) def with_rank(self) -> Self: """Adds a field indicating rank of a student.""" self = self.with_points() return self.annotate( rank=models.Window( expression=models.functions.Rank(), order_by=models.F("total_points").desc(), ) ) @staticmethod def _get_attendance_count( course_class_id: int, status: AttendanceStatus ) -> models.Count: return models.Count( "attendances", filter=models.Q( attendances__class_session__course_class_id=course_class_id, attendances__status=status, ), ) class StudentLeaderboardMeListView(generics.ListAPIView): serializer_class = StudentLeaderboardSerializer permission_classes = [IsSupervisor] filter_backends = (DjangoFilterBackend,) filterset_class = StudentFilter def get_queryset(self): all_students = Student.objects.all().with_rank() top_3_ids = all_students.order_by("rank")[:3].values_list( … -
Filter not appearing in django-import-export
I implemented django-import-export and tried to customer the export form with start_date and end_date filter, but it is not appearing on the export view. here is a snippets of my code. TIA forms.py from django import forms from import_export.forms import ExportForm class CustomExportForm(ExportForm): start_date = forms.DateTimeField(required=False, label="Start Date", help_text="Format: YYYY-MM-DD HH:MM:SS") end_date = forms.DateTimeField(required=False, label="End Date", help_text="Format: YYYY-MM-DD HH:MM:SS") here is my resource.py class SMSMessageResource(resources.ModelResource): sender = fields.Field( column_name='sender', attribute='session', widget=ForeignKeyWidget(Model2, 'sender') ) def __init__(self, **kwargs): super().__init__() self.start_date = kwargs.get("start_date") self.end_date = kwargs.get("end_date") def filter_export(self, queryset, **kwargs): if self.start_date and self.end_date: return queryset.filter(created__range=[self.start_date, self.end_date]) return queryset class Meta: model = Model1 fields = ('id', 'sender', 'created', 'sms', 'synced') export_order = ('id', 'sender', 'created', 'sms', 'synced') and this in my admin.py def get_export_resource_kwargs(self, request, **kwargs): export_form = kwargs.get("export_form") if export_form: kwargs.update( start_date=export_form.cleaned_data.get("start_date"), end_date=export_form.cleaned_data.get("end_date") ) return kwargs What I want to achieve is, apply a date range filter on my export. but the filters don't show on the export view. -
Django NoReverseMatch Error When Using Slug [duplicate]
I'm a newbie working on a Django project, and encountering a NoReverseMatch error when trying to generate a URL using a slug in my template. theres a problem with html file, i think but couldn't solve Error during template rendering In template C:\\Users\\user\\Documents\\coding_files\\python\\website\\main\\templates\\menu.html, error at line 6 NoReverseMatch at /menu/ Reverse for 'post_detail' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['post/(? P<slug>[-a-zA-Z0-9_]+)\\\'] **views.py** from django.shortcuts import render, get_object_or_404 from .models import Post def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) return render(request, 'menu.html', {'post': post}) **html file** <a href="{% url 'post_detail' slug=post.slug %}"> <div class='dontknow'> <img src="{% static 'img/image1.png' %}" class="logo"> </div> </a> **urls.py** from django.urls import path from . import views urlpatterns = [ path('post/<slug:slug>/', views.post_detail, name='post_detail'), ] the output should be if I click on the image in my HTML file, it should generate a URL with the slug and navigate to the post_detail view. -
Django Q (scheduler) is not working properly in python 3
Django Q (scheduler) is not working properly in python 3. it is alway terminated one time a week but it is working fine on python 2. no error log found in python 3. How to fix that issue ? is any configuration to change or fix? -
is it possible to use django-push-notifications[FCM] for both android/ios? (if both apps configured in firebase)
I want to use django-push-notifications library for push notifications. My mobile app part configured firebase for both android and ios. In library's documentations they separated logic and configuration of gcm and apns devices. Can I use just GCMDevice for both android and ios devices (to save them, send message) as it is already configured in firebase? Or should I configure apns in django also as it is mentioned in documentation from firebase_admin import auth # Initialize the default app (either use `GOOGLE_APPLICATION_CREDENTIALS` environment variable, or pass a firebase_admin.credentials.Certificate instance) default_app = firebase_admin.initialize_app() PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": "/path/to/your/certificate.pem", "APNS_TOPIC": "com.example.push_test", "WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']", "WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']", "WP_PRIVATE_KEY": "/path/to/your/private.pem", "WP_CLAIMS": {'sub': "mailto:development@example.com"} } If so, how to do it properly? -
VSCode Django Debugging: Breakpoints not working with 'debugpy', but work with 'python' type
When trying to debug a Django management command in VSCode, I encountered an issue where breakpoints were not being hit when using the 'debugpy' configuration type. However, when I switched to the 'python' configuration type, the breakpoints started working as expected. Steps to Reproduce Create a new Django project and app Create a simple management command Set up VSCode debug configuration Set breakpoints in the management command Try to debug the management command Django Management Command (myapp/management/commands/hello_world.py): from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Prints Hello, World!' def handle(self, *args, **options): message = "Hello, World!" # Set a breakpoint on this line self.stdout.write(message) VSCode Debug Configuration (.vscode/launch.json): { "version": "0.2.0", "configurations": [ { "name": "Django Command (debugpy)", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "hello_world" ], "django": true, "justMyCode": false }, { "name": "Django Command (python)", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "hello_world" ], "django": true, "justMyCode": false } ] } Expected Behavior The debugger should stop at the breakpoint set in the management command for both configuration types. Actual Behavior With "type": "debugpy", the breakpoint is not hit, and the command runs to completion without stopping. With "type": "python", the breakpoint is hit as expected, … -
Nested models aren't saving to database after being serialized
I'm sending an object like this to my Django backend to update the. { id: 1, firstName: 'Foo', lastName: 'Bar', items: [ { id:1, cost: 150, .... calculatedValue: 0 }, { id: 2, cost: 100, .... calculatedValue: 0 } ] } Here are the Models class Parent(models.Model): firstName = models.models.TextField() lastName = models.TextField() class Item(models.Model): parent = models.ForeignKey(Parent, related_name='items', on_delete=models.CASCADE) cost = models.FloatField(blank=True, default=0, null=True) calculatedValue = models.FloatField(blank=True, default=0, null=True) Here are the serializer class ParentSerializer(serializers.ModelSerializer): items = ItemSerializer(many=True, read_only=True) class Meta: model = Parent fields = ('id', 'firstName', 'lastName') class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'cost', 'calculatedValue') My intention is perform the operation for the calculatedValue on the server during the post or put calls. The issue I'm running into is the value I'm computing isn't saving to the database. def update(self, request, *args, **kwargs): # I set the values on the request.data object here setValues(request.data) partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): instance._prefetched_objects_cache = {} #save transaction items = request.data['items'] for item in items: itemInstance = Item.objects.get(id=item['id']) itemSerializer = ItemSerializer(itemInstance, data=transaction, partial=False) itemSerializer.is_valid(raise_exception=True) itemSerializer.save() #the correct value prints here print(f'instance after save {itemSerializer.data}') … -
Selenium wire hide redundant logging
I am using SeleniumWire, Django, Celery for parsing I have a lot of redundant logs from selenium-wire. I mean logs: Capturing request: sitename Capturing response: sitename 200 OK I want to hide these logs. How to configure logger/driver to hide selenium-wire logs? I am using regular logger: import logging logger = logging.getLogger(__name__) My Django logging settings: # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(name)s.%(funcName)s:%(lineno)s- %(message)s' }, }, # django uses some of its own loggers for internal operations. In case you want to disable them just replace the False above with true. # A handler for DEBUG. It is basically writing the DEBUG messages into a file called DJANGO_DEBUG.log 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, }, # A logger for DEBUG which has a handler called 'file'. A logger can have multiple handler 'loggers': { # notice the blank '', Usually you would put built in loggers like django or root here based on your needs '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, }, }, } -
is it possible to use django-push-notifications for both android/ios without apns? (if I have both apps in firebase)
I want to use django-push-notifications library for push notifications. My mobile app part configured firebase for both android and ios. In library's documentations they separated logic and configuration of gcm and apns devices. Can I use just GCMDevice for both android and ios devices (to save them, send message) as it is already configured in firebase? Or should I configure apns in django also as it is mentioned in documentation from firebase_admin import auth # Initialize the default app (either use `GOOGLE_APPLICATION_CREDENTIALS` environment variable, or pass a firebase_admin.credentials.Certificate instance) default_app = firebase_admin.initialize_app() PUSH_NOTIFICATIONS_SETTINGS = { "APNS_CERTIFICATE": "/path/to/your/certificate.pem", "APNS_TOPIC": "com.example.push_test", "WNS_PACKAGE_SECURITY_ID": "[your package security id, e.g: 'ms-app://e-3-4-6234...']", "WNS_SECRET_KEY": "[your app secret key, e.g.: 'KDiejnLKDUWodsjmewuSZkk']", "WP_PRIVATE_KEY": "/path/to/your/private.pem", "WP_CLAIMS": {'sub': "mailto:development@example.com"} } -
Static not loaded when django project deployed
I'm trying to deply my django site, and I did to my ip address, but when I load page online it doesn't load static files. I tried changing different settings on a server and on django files, but I'm out of ideas. I would appreciate a pair of fresh eyes. for sites-available I did this: sudo nano /etc/nginx/sites-available/django-site Output: server { listen 80; server_name xx.xx.xxx.xx; #my ip address location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/muser/django-site/staticfiles/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } this is settings.py STATIC_URL = 'static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] #media MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' It might be that this is all correct, but it might be that urls aren't set up properly. So please see urls.py urlpatterns = i18n_patterns( path(_('admin/'), admin.site.urls), path('rosetta/', include('rosetta.urls')), path('', include('my_app.urls', namespace='my_app')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL,document_root=settings.STATIC_ROOT) Any ideas what I did wrong? Thanks in advance!