Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django ORM calculate all Members of Group
I am trying to annotate all my groups by the number of Users, that apply to a certain condition. In this case I want to get a number of users, that have related Offer model to the Task in the Group. Users can create Offers to the Task. One Task can be related to one Group. So as the result of annotating Groups I want something like this | id | name | runners_num | | -- | ------ | ----------- | | 1 | name1 | 3 | | 2 | name2 | 5 | With a query below I can get this count as a dictionary runners = User.objects.filter( offer__tack__group_id=1 ).distinct( ).values( 'id' ).aggregate( count=Count('id') ) output: {'count': 5} But I can't figure out how to do this with OuterRef clause runners = User.objects.filter( offer__task__group_id=OuterRef('id') ).distinct().values('id') groups = Group.objects.annotate( runners_num=Count(Subquery(runners)) ) It ended up with this wrong query SELECT "groups"."id", "groups"."name", COUNT( ( SELECT DISTINCT U0."id" FROM "users" U0 INNER JOIN "offers" U1 ON (U0."id" = U1."runner_id") INNER JOIN "tasks" U2 ON (U1."task_id" = U2."id") WHERE U2."group_id" = ("groups"."id") ) ) AS "runners_num" FROM "groups" GROUP BY "groups"."id" LIMIT 21 My models class Task(models.Model): tasker = models.ForeignKey( "user.User", … -
Django: In templates using an if statement inside a for loop of _set.all doesn't work. why?
If you have a better way to reformulate my question please let me know. My template is as follows: {% for x in group.groupmember_set.all %} {% if x.user != user.username %} {{ x.user }} {% endif %} {% endfor %} This statement prints all users in the Group, as though the if statement doesn't exist. If I remove the if statement, eventually prints the same and makes sense... I want to filter out user.username with an if statement but doesn't work. What is wrong? Group has a ManytoMany relation with User through GroupMember. My models.py file reads: class Group(models.Model): name = models.CharField(max_length=255, unique=True) members = models.ManyToManyField(User,through="GroupMember") class GroupMember(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) group = models.ForeignKey(Group,on_delete=models.CASCADE,) is_valid = models.BooleanField(default=False) and in views.py I use DetailView, e.g., class SingleGroup(DetailView): model = Group -
How to implement last visited functionality for articles in django rest framework
I have this model of Articles where users can post articles. add comments etc. I want to add a filter where it can filter articles according to user which have visited the last article or commented the last article Please guide me how can i achieve this functionality in django/drf this is my models class Article(models.Model): id=models.AutoField(primary_key=True, auto_created=True, verbose_name="ARTICLE_ID") headline=models.CharField(max_length=250) abstract=models.TextField(max_length=1500, blank=True) content=models.TextField(max_length=10000, blank=True) files=models.ManyToManyField('DocumentModel', related_name='file_documents',related_query_name='select_files', blank=True) published=models.DateField(auto_now_add=True, null=True) tags=models.ManyToManyField('Tags', related_name='tags', blank=True) isDraft=models.BooleanField(blank=True, default=False) isFavourite=models.ManyToManyField(User, related_name="favourite", blank=True) created_by=models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name="articles") def get_id(self): return self.headline + ' belongs to ' + 'id ' + str(self.id) class Meta: verbose_name_plural= "Articles" ordering=("id" , "headline", "abstract", "content", "published", "isDraft", "created_by") def __str__(self): return f'{self.headline}' -
How to rename standart django-registration templates' names
I am using django-registration standard urlpatterns, but i want to rename its template name. By default it is "registration/login.html". In source code there is a parameter "template_name" that i want to change: class LoginView(RedirectURLMixin, FormView): """ Display the login form and handle the login action. """ form_class = AuthenticationForm authentication_form = None template_name = "registration/login.html" redirect_authenticated_user = False extra_context = None How and where i can do it? (p.s. django.contrib.auth.views.LoginView.template_name = name is not working, or i just write it in incorrect place) -
Creating PeriodicTask in celery django
I need to send notifications with certain interval when Ticket model instance has been created. For that I decided to use celery-beat. I created signals.py where I create PeriodicTask intance. When I create new Ticket instance the PeriodicTask instance is created in DB but the task is not running. What do I do wrong? signals.py from datetime import datetime from django.db.models.signals import post_save from django.dispatch import receiver from .models import Ticket from django_celery_beat.models import PeriodicTask, IntervalSchedule import json @receiver(post_save,sender=Ticket) def notification_handler(sender, instance, created, **kwargs): if created: interval, created = IntervalSchedule.objects.get_or_create(every=10, period='seconds') task = PeriodicTask.objects.create(interval=interval,enabled=True, name='notification_' + str(instance.id), task="create", args=json.dumps((instance.id, ))) tasks.py from celery import shared_task @shared_task(name="create") def create(data): print("Some logic here") celery.py import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'helpdesk.settings') app = Celery('helpdesk') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() setting.py CELERY_BROKER_URL = 'redis://redis:6379/0' The commands I use for launching celery and celery-beat: beat: celery -A helpdesk beat celery: celery -A … -
How to create many to many relationships using three tables Django
I have three tables Client, Company, Account and want to create a relation between then so that they can satisfy following conditions. One client can have many accounts. One Account can be associated with many users. One company can have many accounts. One account can be in many companies. One client can have many companies. One Company can be associated with many companies. Tables are as follows: class Company(models.Model): name = models.CharField(max_length=255) website_url = models.CharField(max_length=255, null=True, blank=True, default='') class Account(models.Model): customer_id = models.CharField(max_length=20, null=True, blank=True) name = models.CharField(max_length=255) class Client(models.Model): name = models.CharField(max_length=255) age = models.CharField(max_length=10, null=True, blank=True) I don't know how to define many to many relationships for these tables. -
adding fields from models to function in django
I'm trying to add all parameters from class Room(number, beds, capacity) to show it on room list page. In result I want to to see all other information under the category which is linked with booking form. I've tried in various ways but I can't solve it. def RoomListView(request): room = Room.objects.all()[0] room_categories = dict(room.ROOM_CATEGORIES) room_values = room_categories.values() room_list = [] for room_category in room_categories: room = room_categories.get(room_category) room_url = reverse('hotelbooking:RoomDetailView', kwargs={'category': room_category}) room_list.append((room, room_url)) context = { 'room_list': room_list, } return render(request, 'room_list.html', context) -
django-cors-headers allow any request and i didn't put any origin why?
Here the code i make post request from frontend to this api that didn't raise any problem, look at this code i didn't allow any origin so why accept requests ? CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOWED_ORIGINS = [ ] CORS_ORIGIN_WHITELIST = [ ] CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "PUT", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] -
Is there a way to upload video file with timestamp in Django Rest Framework?
Is there any way in DRF or just python to post mp4 video with set up timestamp? For example i want to post a video that will start at 10 second if user will display it on frontend. -
Add cluster information to table after KMeans
I am building a django application that uses Kmeans to cluster a particular table in the database. I'd like to add the clusters to the table in the database after the clustering process is done. Here is a sample of the code. This code runs every time someone registers This prints the data frame adding an extra column to show which cluster they belong to. How would I go about it if I want to add those clusters to the original data frame, the table in the database. -
I get AnonymusUser in Ajax GET request DJANGO
I am working in a Django application and I need to get some data with a GET request from a template. I have set up a AJAX get request as follows: $.ajax({ type: 'GET', dataType: "json", url: "https://www.url.com/enpd/var1/var2/var3", xhrFields: { withCredentials: true }, success: function(obj) { ... }, error: function(data) { ... } }); And in the views.py I have the following: @login_required(login_url='/login') def getReq(request, var1, var2, var3): user = request.user if user.is_authenticated: ... else: return HttpResponse({user}) And I always get the request user as "AnonymusUser". It's like the AJAX get request is not sending the user details in the request. Why is that happening? I have read through many posts and nothing helped... PD: I created a custom user, don't know if that may cause any issue? -
Django django-filters ipaddress mysql
filter for ip not working properly model.py class Network(models.Model): start_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) end_ip_address = models.GenericIPAddressField(protocol='both', blank=True, null=True) filters.py class NetworkFilter(django_filters.FilterSet): f_by_address = django_filters.CharFilter(method='filter_by_address', label="BY ADDRESS") def filter_by_address(self, queryset, name, value): return queryset.filter(start_ip_address__lt=value, end_ip_address__gt=value) class Meta: model = Network fields = ['id', 'start_ip_address',] filter by address result to SELECT `network_network`.`id`, start_ip_address, `network_network`.`end_ip_address` FROM `network_network` WHERE (`network_network`.`end_ip_address` > 10.172.148.12 AND `network_network`.`start_ip_address` < 10.172.148.12) ORDER BY `network_network`.`id` ASC my table doesn contains so much records, but even now I got into the troubles. mysql> SELECT start_ip_address, end_ip_address from network_network where (end_ip_address > '10.172.148.12' AND start_ip_address < '10.172.148.12'); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.14.1 | 10.172.15.254 | | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 2 rows in set (0.01 sec) mysql> SELECT start_ip_address, end_ip_address FROM network_network WHERE (INET_ATON("10.172.148.12") BETWEEN INET_ATON(start_ip_address) AND INET_ATON(end_ip_address)); +------------------+----------------+ | start_ip_address | end_ip_address | +------------------+----------------+ | 10.172.148.1 | 10.172.149.254 | +------------------+----------------+ 1 row in set (0.01 sec) Not sure what to do in order to make this filter working accurate over django ORM. Can't use raw SQL as example is simplified. -
Large JSON data over POST request
I have a system working as a swarm, with a lot of independent devices running Django and a main Queen (running Django as well) gathering data from the swam. Each device from the swarm is sending the new data to the queen using a POST request with the data in a json. Each data recorded in the device is then updated to mark it as sent to the queen and doesn't need to be resent later. the problem is that each dataset is about 10 MB and I am getting a timeout error while processing the post request. The solution I got at the moment is far from optimal: I split the upload in batches of 500 records and send several post requests. After each successful upload, I update each record 1 by 1. This solution has some performance issues. Things I would need to improve: manage to send all data in 1 single request Reduce the data volume to be sent Update the data faster on each device after so the questions are: Is there a way to keep the post request alive for longer? I am thinking of using gzip to send the data. Is it something to … -
how to view the extension file mention below?
I would like to view (.tiff .ecw) extension files, orthoimage [large files] through online with map integration using python JavaScript ...any one can help or suggest some to create the Web Apps