Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
slug related Feilds are not parsed in json parsing
I am trying to import with codenames it takes as a string while doing json parsing with slug feilds class ImportFinanceSaleSerializerField(serializers.JSONField): def to_representation(self, obj): user_serializer = ImportFinanceSaleSerializer(obj, many=False, ) return user_serializer.data def to_internal_value(self, data): return data' class ImportFinanceSaleSerializer(serializers.ModelSerializer): interestpercentage = serializers.SlugRelatedField( required=False, allow_null = True, slug_field="code", queryset=PercentageInterest.objects.filter(status=1,)) guarantor = serializers.SlugRelatedField( required=False, allow_null = True, slug_field='code', queryset=Person.objects.filter(status=1,)) emi_date = serializers.IntegerField(required=False, min_value=1, max_value=30) -
Doing polymorphic model, what's the best approach?
I'm trying to upscale a project that originally was used by an area to assign reports to their respective departments. Those reports I want them to be tasks, to broaden the spectrum of use to all of the organization. Originally, I was using separate models for reports, updates, report files, update files. (Those tables, had almost the same fields) Now, I'm trying to have a polymorphic model, as shown below: #### TASK TYPE (TASK, UPDATE) class TipoTarea(models.Model): nombre = models.CharField(max_length=50, unique=True) def __str__(self): return self.nombre ###### TASK CATEGORY (TOPIC AND THE AREA WHO IS BEING DIRECTED TO) class CategoriaTarea(models.Model): nombre = models.CharField(max_length=50, unique=True) area = models.ForeignKey(Area, on_delete=models.CASCADE) tiempo_atencion = models.IntegerField(default=2) def __str__(self): return self.nombre ##### TASK STATE (CREATED, IN PROCESS, COMPLETED, REASIGNED) ##### REASIGNED STATE, CREATES A NEW TASK WITH A DIFFERENT CATEGORY class EstadoTarea(models.Model): nombre = models.CharField(max_length=50) def __str__(self): return self.nombre ###### TASK ###### TASK PARENT WOULD BE USED FOR UPDATES, BUT HOW CAN REASIGNMENTS BE CLASSIFIED class Tarea(models.Model): tipo = models.ForeignKey(TipoTarea, on_delete=models.CASCADE, related_name = 'tarea') categoria = models.ForeignKey(CategoriaTarea, on_delete=models.CASCADE, related_name = 'tarea') descripcion = models.CharField(max_length=500) fecha = models.DateField(default=datetime.date.today) estado = models.ForeignKey(EstadoTarea, default= 1, on_delete=models.CASCADE) creado_por = models.ForeignKey(User, on_delete=models.CASCADE, related_name='creador') creado = models.DateTimeField(auto_now_add=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, related_name="actualizaciones", null=True, … -
how to run tasks in parallel with django async
i'm using daphne as a asgi server, with django. turning my view from sync to async was relatively simple, since i could use @sync_to_async at the ORM part. the problem is, some service of mine is like this: async def service_of_mine(p1, p2, p3): r1 = await foo1(p1) r2 = await foo2(p2) r3 = await foo3(p3) return r1, r2, r3 i wanted to run all three calls in parallel, using return await asyncio.gather(foo1(p1), foo2(p2), foo3(p3)) but my api hangs with Application instance <Task pending name='Task-1' coro=<ASGIStaticFilesHandler.__call__() running at /mypath/python3.10/site-packages/django/contrib/staticfiles/handlers.py:101> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at /home/rado/.pyenv/versions/3.10.6/lib/python3.10/asyncio/futures.py:385, Task.task_wakeup()]>> for connection <WebRequest at 0x7f8274b98340 method=GET uri=/myApiPath clientproto=HTTP/1.1> took too long to shut down and was killed. how can i achieve this? -
How to fetch a boolean value from models for a specific user in Django?
I have an extended user model and I want to check it to see if the logged-in user has completed_application as per the model: Models.py: class Completed(models.Model): class Meta: verbose_name_plural = 'Completed Application' user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) completed_application = models.BooleanField(default=False) def __str__(self): return f'{self.completed_application}' Views.py: @login_required def dashboard(request): if Completed.objects.get(completed_application = True): completed = True else: completed = False return render(request, 'dashboard.html', {'section': 'dashboard', 'completed' : completed}) HTML: {% if completed %} <!-- You already completed an application! --> <h1> Already completed </h1> {% else %} <!-- Show the application form --> <h1> Render model form here </h1> {% endif %} The code above is not working for me as it returns True every time. I read quite a few posts on here but they don't seem to be user specific such as: How to show data from django models whose boolean field is true? -
How do I make sure a model field is and incremental number for my model?
I have the following model in django: class Page(models.Model): page_number = models.IntegerField() ... and I would like to make sure that this page number keeps being a sequence of integers without gaps, even if I delete some pages in the middle of the existing pages in the data base. For example, I have pages 1, 2 and 3, delete page 2, and ensure page 3 becomes page 2. At the moment, I am not updating the page_number, but rather reconstructing an increasing sequence without gaps in my front end by: querying the pages sorting them according to page_number assigning a new page_order which is incremental and without gaps But this does not seem to the be best way to go... -
MultipleObjectsReturned: get() returned more than one items -- it returned 3
I am getting the following error in my traceback, I am currently running tests for my new website and when I try to create more than one blog post I get returned a MultipleObjectsReturned error, how would I fix this? I am guessing the issue lies with get_object_or_404 as other questions on Stack Overflow have suggested that I use primary keys but I don't want just one object to filter, I need to show all the objects in my Post model traceback: https://dpaste.com/6J3C7MLSU views.py ```python3 class PostDetail(LoginRequiredMixin, DetailView): model = Post form_class = CommentForm template_name = "cubs/post_detail.html" def get_form(self): form = self.form_class(instance=self.object) return form def post(self, request, slug): new_comment = None post = get_object_or_404(Post) form = CommentForm(request.POST) if form.is_valid(): # Create new_comment object but don't save to the database yet new_comment = form.save(commit=False) # Assign the current post to the comment new_comment.post = post # Save the comment to the database new_comment.save() messages.warning(request, "Your comment is awaiting moderation, once moderated it will be published") return redirect('cubs_blog_post_detail', slug=slug) else: return render(request, self.template_name, {'form': form}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post = get_object_or_404(Post) comments = post.cubs_blog_comments.filter(active=True).order_by('-date_posted') articles = Article.objects.filter(status=1).order_by('-date_posted')[:2] post_likes = get_object_or_404(Post, slug=self.kwargs['slug']) total_likes = post_likes.total_likes() if post_likes.likes.filter(id=self.request.user.id).exists(): liked = True … -
django query to count boolean values using annotate and values
So, what I am trying to do is count how many absents, tardy, and left early's an employee has. What I am using right now is results = Attendance.objects.values('emp_name__username').annotate(abs_count=Count('absent'),tardy_count=Count('tardy'), early_count=Count('left_early')) What this query is doing here is for every field i have specified to count, it's just giving me the count of every time an emp_name object has been made. -
How can I return a hex value of a dominant color from an image?
I'm making a backend django photo viewing app, and I'm tasked with extracting the hex value of the most dominant color from an image, and push it into a local database. I can't wrap my head around it, and I've been stuck at this for a whole day, looked everywhere and just couldn't find a proper solution. Anyone mind helping? -
systemctl enable gunicorn fails with error "/etc/systemd/system/gunicorn.service:8: Missing '='."
I am deploying Django application working on web server using gunicorn locally on WSL. I need to enable needed systemd files. When I run command systemctl enable gunicorn I get error "/etc/systemd/system/gunicorn.service:8: Missing '='. Failed to enable unit, file gunicorn.service: Invalid argument. gunicorn.service looking like that: [Service] User=root Group=www-data WorkingDirectory=<base_app_path> Environment="PATH=<base_app_path>/env/bin" EnvironmentFile=<base_app_path>/.env ExecStart=<base_app_path>/env/bin/gunicorn \ --workers 4 \ --bind 0.0.0.0:8080 \ meeting.wsgi:application RestartSec=10 Restart=always [Install] WantedBy=multi-user.target What can be the problem here? -
Get sum of nested JSON
I have this JSON data where "logs" is called as another serializer. { "id": 1, "logs": [ { "work_hours": 7, "user": "admin" }, { "work_hours": 8, "user": "admin" }, { "work_hours": 6, "user": "admin" }, { "work_hours": 4, "user": "admin" }, { "work_hours": 5, "user": "admin" } ] } Is it possible to get the total work_hours from logs? Tried the annotate(Sum) but I can only get the Sum of logs.id as default Here is my serializer.py class UserLogsSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() class Meta: model=UserLogs fields=['work_hours','user'] class UserSerializer(serializers.ModelSerializer): logs = UserLogsSerializer(read_only=True,many=True) class Meta: model=User fields='__all__' -
What is the simplest way to store a list of numbers in Django model without using third party databases
I want to store a list of numbers in Django model without using third party databases like MySQL, PostgreSQL etc. I want a simple approach. I don't think that there is any built-in field like PositiveSmallIntegerField, CharField etc but please do correct me if I am wrong. Is there a way I can use the built-in fields in order to achieve the result or is there a different approach? Please note that I need to add / remove / extract those numbers also. Can someone help me with it? -
Returning two arrays from a python script in Django and utilizing in Ajax simultaneously
I have a python script running in views.py within Django which returns two very large arrays, x and y. It currently is able to run off a button press within my index.html. def python_file(request): final() return HttpResponse("ran") The ajax code I have running to do the button press. <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <script> function gotoPython(){ $.ajax({ url: "/python_file", context: document.body }).done(function() { alert('finished python script'); }); } </script> It's also attached to the URLS.py. I know there's no array being returned right now, because I am unsure how to run the script, get the data simultaneously, then add it to the page without refreshing the page. So, I am asking what would be the best practice to do what I described. Any help would be appreciated. -
Django dump data got module not found error from Allauth and other package
After run python manage.py dumpdata > data.json I get this ModuleNotFoundError: No module named 'allauth' and if i comment the allauth in the installed apps i still get another error on another package that might have a data -
Django - mix two annotated values into one with a Case/When make the performance getting slow on many elements
In get_queryset function inside a viewset I buid a queryset that needs to list a big amount of "Course" but with annotating some counts of a children model "CoursePerson". It could have like 10000 "Course" objects with in total ~5 millions of "CoursePerson" objects. I would like to annotate "interact_count" by taking another annotated value depending of the Course type. If I remove then "interact_count" annotation django + postgresql taking ~20-50ms to answer. But when I put back that annotation, it takes like 600-800ms. I am pretty sure the Case/When is the cause of this latency. But I don't know how to do other way cause I need only one count. (And not 2) I don't wanna do that with python because I would lose the ordering or pagination. This part is the problem: How can I do the same but more performantly ? interact_count=Case( When( Q(type=models.Course.TypeChoices.PHISHING) | Q(type=models.Course.TypeChoices.SMS), then=course_person_open_subquery, ), default=course_person_extra_subquery, ) full queryset: course_person_open_subquery = Subquery( CoursePerson.objects.filter( course_id=OuterRef('uid'), status__gte=models.CoursePerson.StatusChoices.OPEN, is_in_analytics=True ) .annotate(count=Func(F('uid'), function="Count")) .values('count'), output_field=IntegerField() ) course_person_extra_subquery = Subquery( CoursePerson.objects.filter( course_id=OuterRef('uid'), status__gt=models.CoursePerson.StatusChoices.OPEN, is_in_analytics=True ) .annotate(count=Func(F('uid'), function="Count")) .values('count'), output_field=IntegerField() ) return models.Course.objects.annotate( account_count=Count("accounts", distinct=True), groups_count=Count("groups", distinct=True), domain_name=F("domain__name"), interact_count=Case( When( Q(type=models.Course.TypeChoices.PHISHING) | Q(type=models.Course.TypeChoices.SMS), then=course_person_open_subquery, ), default=course_person_extra_subquery, ), ).all() -
django.core.exceptions.AppRegistryNotReady: When I run docker
I have a chat application so I need to use both gunicorn and uvicorn in order to have websockets working. When I build the image only for the wsgi with gunicorn it's working and when I add the uvicorn for handling asgi I run into this error asgi.py from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from chat import urls import os import django os.environ.setdefault("DJANGO_CONFIGURATION", "Local") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "friendly_enigma.settings") django.setup() application = get_asgi_application() application = ProtocolTypeRouter( { "http": application, "websocket": URLRouter(websocket_urls.websocket_urlpatterns) } ) dockerfile command CMD gunicorn friendly_enigma.wsgi:application --bind 0.0.0.0:8000 & gunicorn friendly_enigma.routing:application -k uvicorn.workers.UvicornWorker --bind=0.0.0.0:8001 logs [2022-10-20 14:10:31 +0000] [7] [INFO] Starting gunicorn 20.1.0 [2022-10-20 14:10:31 +0000] [7] [INFO] Listening at: http://0.0.0.0:8000 (7) [2022-10-20 14:10:31 +0000] [7] [INFO] Using worker: sync [2022-10-20 14:10:31 +0000] [10] [INFO] Booting worker with pid: 10 [2022-10-20 14:10:31 +0000] [8] [INFO] Starting gunicorn 20.1.0 [2022-10-20 14:10:31 +0000] [8] [INFO] Listening at: http://0.0.0.0:8001 (8) [2022-10-20 14:10:31 +0000] [8] [INFO] Using worker: uvicorn.workers.UvicornWorker [2022-10-20 14:10:31 +0000] [12] [INFO] Booting worker with pid: 12 [2022-10-20 14:10:32 +0000] [12] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/local/lib/python3.8/dist-packages/uvicorn/workers.py", line 66, in init_process super(UvicornWorker, self).init_process() File "/usr/local/lib/python3.8/dist-packages/gunicorn/workers/base.py", line 134, … -
psql -U postgres not working & not installed using brew
Every time I try to run psql -U postgres in my terminal, I get this response. psql: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? I did not install this through brew instead though postgres.app When I enter the command postgres -V I get the response postgres -V postgres (PostgreSQL) 14.5 -
TypeError: fromisoformat: argument must be str
I have accidentally made '1' the default value for the models.DateField(). Now Django throws an error everytime I try to migrate, even if I delete the CharacterField / change the default value using (default=datetime.now()). Is there a way to fix this? Applying mainApp.0006_test_date...Traceback (most recent call last): File "/Users/di/Code/Schule/GymnasiumApp/manage.py", line 22, in <module> main() File "/Users/di/Code/Schule/GymnasiumApp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 252, in apply_migration state = migration.apply(state, schema_editor) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/migrations/migration.py", line 130, in apply operation.database_forwards( File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/migrations/operations/fields.py", line 108, in database_forwards schema_editor.add_field( File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 394, in add_field self._remake_table(model, create_field=field) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 237, in _remake_table self.effective_default(create_field), File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/backends/base/schema.py", line 423, in effective_default return field.get_db_prep_save(self._effective_default(field), self.connection) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 925, in get_db_prep_save return self.get_db_prep_value(value, connection=connection, prepared=False) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 1438, in get_db_prep_value value = self.get_prep_value(value) File "/Users/di/Code/Schule/GymnasiumApp/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line … -
Django return new property in json response
I have a view in Django that fetches some objects, adds new attribute to them and returns them as JSON response. The code looks like this: def stats(request): items = MyItem.objects.all().order_by('-id') for item in items: item.new_attribute = 10 items_json = serializers.serialize('json', items) return HttpResponse(items_json, content_type='application/json') The new_attribute is not visible in JSON response. How can I make it visible in JSON response? It can be accessed in templates normally with {{ item.new_attribute }}. -
Django - Problem with DB query using foreign key
I'm using Django for a Web app and I have the following data model: class classi(models.Model): nome = models.TextField(null=True) class Meta: db_table = 'classi' class users(models.Model): name = models.TextField(null=True) email = models.TextField(null=True) password = models.TextField(null=True) classe = models.ForeignKey(classi, db_column='classe', on_delete=models.CASCADE, null=True) class Meta: db_table = 'users' class smartphone(models.Model): marca = models.TextField(null=True) modello = models.TextField(null=True) possessore = models.ForeignKey(users, db_column='possessore', on_delete=models.CASCADE, null=True) class Meta: db_table = 'smartphone' My goal is to show, on an HTML page, all classi, and for each classi all users and for each user all smartphone. How can I do this? I tried to user filter in view.py and a for loop in the html, but there are some errors. How can I implement my view.py and my html file? -
Uniting two virtual environments/servers/apps into one (Nginx/Django)
My project has two virtual environments, "main" and "test". I want to unite them on one server. I've been advised to use nginx proxy to do this, but I'm not sure how, especially since each environment already has its own network: backend of one project (the backend of the "test" project is similar): version: "3.8" services: postgres: image: postgres:13.3 container_name: postgres_stage restart: always volumes: - postgres_data_stage:/var/lib/postgresql/data ports: - 5432:5432 env_file: - .env-stage networks: - stage_db_network backend: <...> depends_on: - postgres env_file: - .env-stage networks: - main_db_network - main_swag_network migrations: <...> networks: main_db_network: name: main_db_network external: true main_swag_network: name: main_swag_network external: true volumes: postgres_data_main: name: postgres_data_main static_value_main: name: static_value_main How do I set up a nginx_proxy to unite the two on one server? -
Nginx 413 Request Entity Too Large, Docker, Django
I get hit with the error 413 Request Entity Too Large when I try to upload any file larger than 1.5MB. I have seen various answers out there regarding this issue but nothing seems to work with my situation: my nginx default.conf: upstream django { server store:27038; } server { listen 27036; location /static { alias /vol/static; } location / { proxy_pass http://django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } my nginx Dockerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf /etc/nginx/conf.d/default.conf USER root RUN mkdir -p /vol/static RUN chmod 777 /vol/static USER nginx I keep on seeing responses saying that just adding something like server { client_max_body_size 100M; ... } somewhere in Nginx should solve the issue but I keep getting an error when I try to put it on my conf file so am not entirely sure where this code is supposed to go. If anyone has an answer for this it would be much appreciated -
Swagger..Unable to render this definition The provided definition does not specify a valid version field. Django Server
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0). It works locally but it shows above given error on server. For reference screenshot is attached.dj -
How to use Django template filters?
I have Variable : unit = 'BARS' i pass this value into frontend using Django template I want to get 'bar' I use {{ unit|slice":4"|lower }} but it doesn't work . -
Django - How can I make an if statement using step_number and another Javascript function?
I'm trying to use the step_number function (this function is being used to go to the next page) and at the same time validate the fields if they are blank using Javascript. I would like to know what can be done in order to get both working without using a form. Is there a way to include the step_number in the Javascript function? So far I got this: HTML <div class="mt-3"> <button class="button btn-navigate-form-step" type="button" step_number="2" onclick="validatefields1()">Next</button> </div> Javascript let x = document.forms["checklistForm"]["user_name"].value; if (x == "") { alert("Name must be filled out"); return false; } } -
NetSuite: How can I add a record to a Advanced PDF/HMTL Template?
So I know that I can use the N/render to generate a template and I can use the addRecord to add record objects to the print template to make them available in the FTL. My question is if I can do something similar when the native print button is clicked and prints a Advanced PDF/HTML Template. I know that I can catch the PRINT event in the User Event script but beyond that I am stuck. I know the question is a little general I will add context on request. I just don't know which way to go. EDIT: I am familiar with the option of adding a custpage field to the form and then extracting the JSON in the FTL. In this specific situation it would be much more convenient if I could simply add a full record. Meaning I am on a Item Fulfillment print and want to add the FULL parent Sales Order record to the print so that I can access it in the FTL by salesorder.memo etc. Something similar to: require(['N/render'], function(render) { var renderer = render.create(); renderer.addRecord('customer', record.load({ type: record.Type.CUSTOMER, id: customer })); }) The issue is that I only know how to do …