Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extending Django's nav-sidebar with additional options
I am working with Django and currently trying to add options to default nav-sidebar which will not be anyhow connected with models, but will open other additional pages. The best idea i got is to extend the default base_site.html with my new option for a sidebar. Therefore i resulted in the following code: {% extends "admin/base_site.html" %} {% block sidebar %} <div class="app-dashboard module current-app"> <h2>Custom Options</h2> <ul> {% include "admin/custom_sidebar.html" %} </ul> </div> {{ block.super }} {% endblock %} custom_sidebar.html: <th class="model-group"><a href="{% url 'email' %}">Send message</a></th> This indeed extends the page, but adds my option to the bottom of the content block, whereas I want it to appear in my sidebar. Here is how it looks: I understand I practically didnot affected the default nav_sidebar anyhow, but I am out of ideas how to make it. Is there a way i can modify a nav_sidebar in django? And if so how shall i do it? -
Django - How to show Full name of the Month in Admin Panel
I want to show Full month (like April or September) in Django Admin Panel. But it keeps show me first 3 letter of the month or a number. Is there any way to do make it show full month on Admin Panel? Thanks! -
Celery task stays running forever, but completes successfully
My Task: @app.task(ignore_result=True) def leaks_scan(target: str, remove_type: str = "old", **kwargs): url = settings.API_URL + "leaks" skip = 0 limit = 1000 max_limit = 5000 if remove_type == "all": remove_all_data(Leak, target) scan_id = None target_id = None while True: data = get_data(url, target, skip=skip, limit=limit) count = data.get("count") data = data.get("data", []) if not data: if not count: remove_all_data(Leak, target) break break scan_id, target_id = load_leak_data(data) skip += limit if skip > max_limit: break if remove_type == "old" and scan_id and target_id: remove_old_data(Leak, scan_id, target_id) print("Leak scan completed") Notice that this task has a print statement that prints Leak scan completed in the last line Logs: Task received: Task finished (debug print line): The task works as expected and completes successfully. However, when I check the Celery worker logs, the task stays in the running state indefinitely, even though it has been completed: Can anyone suggest a solution or provide any guidance on how to troubleshoot this issue? Thanks in advance for your help. Environment & Settings Celery version: celery report Output: software -> celery:5.2.7 (dawn-chorus) kombu:5.2.4 py:3.11.2 billiard:3.6.4.0 py-amqp:5.1.1 platform -> system:Linux arch:64bit, ELF kernel version:5.15.90.1-microsoft-standard-WSL2 imp:CPython loader -> celery.loaders.default.Loader settings -> transport:amqp results:disabled deprecated_settings: None Broker & Result … -
Django: Starting a celery worker when a button is clicked
I have a button which puts a PCAP file into a parsing function. When my button is clicked "Upload File" it calls my form_upload view and I want my celery task to start running so it displays a progress bar while the file is being parsed. However, when clicking "Upload File", the page loads and then the celery starts. So the progress bar does not display until after the page loads and the function finishes parsing. Here is my index.html <form action="{% url 'upload' %}" class="row gy-1 gx-2 align-items-center" id='startIDS' method="post" enctype="multipart/form-data" style="margin-bottom: 10px;"> <div class='col-auto'> <input class="form-control" type="file" name="file"> </div> <div class='col-auto'> {% csrf_token %} <button type="submit" class="btn btn-primary btn-sm" style="float: right;" onclick="wait()">Upload File</button> <script> function wait() { //go_to_sleep.delay(5); alert("Click Ok and then please wait for upload to finish"); } </script> </div> <div class='progress-wrapper'> <div id='progress-bar' class='progress-bar' style="background-color: #68a9ef; width: 0%;">&nbsp;</div> </div> <div id="progress-bar-message">Waiting for progress to start...</div> <div id="celery-result"></div> <script src="{% static 'celery_progress/celery_progress.js' %}"></script> <!--CELERY--> {% if task_id %} <!-- avoid any errors by just checking if the task_id exists --> <script> // JQuery document.addEventListener("DOMContentLoaded", function() { var progressUrl = "{% url 'celery_progress:task_status' task_id %}"; CeleryProgressBar.initProgressBar(progressUrl); }); </script> {% endif %} </form> Here is my views.py `# Render … -
Django returns a tuple instead of returning data
I have a simple model that is supposed to store some basic nutritional information about food, but whenever I create or edit the model it returns a tuple instead of the data. The app is simple and these are the only models I have in them. Here is the model: class User(AbstractUser): test_field = models.CharField(max_length=100) def __str__(self): return self.username class Food(models.Model): name = models.CharField(max_length=100, null=False, blank=False), calories = models.IntegerField(default=0, null=False), protein = models.IntegerField(default=0), fat = models.IntegerField(default=0), rel_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) At first I thought it was an issue with how I was saving the model, so I tried creating one through the shell with the following commands: from api.models import User, Food f = Food() f.name = "Test" f.calories = 1 f.rel_user = User.objects.get(id=1) f.save() If I call f.rel_user, it returns myemail@gmail.com, but if I call f.name, it returns (<django.db.models.fields.CharField>,). In order to try to fix this, I've looked through the getting started project on https://docs.djangoproject.com/en/4.2/intro/tutorial01/, and have made sure that my settings.py, and my models are written like the ones on the site. I've tried using both the shell and a form to create test Food objects. How can I fix this so when I try to get … -
HDF5-DIAG: Error detected in HDF5 on django project
Im working on my django project and when I made a copy of the project on a new pc I got this error (repeated multiple times) each time I load the server: HDF5-DIAG: Error detected in HDF5 (1.10.7) thread 1: #000: H5T.c line 1915 in H5Tcopy(): not a datatype or dataset major: Invalid arguments to routine minor: Inappropriate type and when I stop the server I get another one HDF5: infinite loop closing library L,T_top,P,P,FD,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E,E I have no idea where this come from, any light to where to find the issue?, deprecated model datatypes? postgres/postgis problem? thanks -
Django: How to loop through query set and change the boolean field to True in django?
I am trying to loop through a queryset in django and turn all the boolean fields in the queryset to true. I want to turn this booleans to True on the success_page, so i tried doing it like this @login_required def PaymentSuccessView(request): ... order = get_object_or_404(CartOrder, stripe_payment_intent=session.id) cart_order_items = CartOrderItem.objects.filter(order=order) for c in cart_order_items: c.paid = True c.save() return render(request, "payment/payment_success.html", {"order": order}) The problem is that, this still does not work even after i get redirected to the success page on successful transaction. I also tried doing this in the model, i am not sure if it's the right way to do this, but i tried it and it still did not work class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) paid = models.BooleanField(default=False) .... def save(self, *args, **kwargs): if self.order.payment_status == "paid": self.paid = True return super(CartOrderItem, self).save(*args, **kwargs) These are my model fields class CartOrderItem(models.Model): order = models.ForeignKey(CartOrder, on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, on_delete=models.SET_NULL, null=True) paid = models.BooleanField(default=False) ... class CartOrder(models.Model): vendor = models.ManyToManyField(Vendor) buyer = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name="buyer") stripe_payment_intent = models.CharField(max_length=200,null=True, blank=True) -
When should I use to_representation?
I'm looking for guidance on if my usage of to_representation is a decent approach or if there is a better way to solve my specific problem. I have this code in my serializers.py: from rest_framework import serializers from .models import Project, Task, TaskStatus class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ["name", "description", "start_date", "end_date", "pkid"] def create(self, validated_data): organization = validated_data.pop('organization', None) project = Project.objects.create(**validated_data) if organization: project.organization = organization project.save() return project class TaskStatusSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ["name", "description", "pkid"] def create(self, validated_data): task_status = TaskStatus.objects.create(**validated_data) return task_status class TaskSerializer(serializers.ModelSerializer): project = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all()) status = serializers.PrimaryKeyRelatedField(queryset=TaskStatus.objects.all()) class Meta: model = Task fields = ["name", "description", "project","status","pkid"] def create(self, validated_data): project = validated_data.pop('project') status = validated_data.pop('status') task = Task.objects.create(project=project, status=status, **validated_data) task.save() return task def to_representation(self, instance): representation = super().to_representation(instance) representation['project'] = ProjectSerializer(instance.project).data representation['status'] = TaskStatusSerializer(instance.status).data return representation What I'm trying to do is have my TaskSerializer respond to an API request and provide me task, taskstatus, and project objects that I use to populate a Vue list. Within the view list, I have a create modal that loads where the user can select the project via drop down and specify the status. These … -
django-storages FTP doesn't work on production
I've frontend (made with Angular) on a cloud hosting and backend (made with DRF) on pythoneverywhere. I configured django-storages so that it sends the files that the user uploads to the server where the frontend is located via FTP. While I use it in development, on localhost, it works perfectly, however when I use it in production I get a Server Error (500). This is the error that shows the console: 2023-04-04 19:32:00,158: Internal Server Error: /admin/portfolio/developer/add/ Traceback (most recent call last): File "/home/ferreromanuel/.virtualenvs/portfolio-virtualenv/lib/python3.10/site-packages/storages/backends/ftp.py", line 91, in _start_connection ftp.connect(self._config['host'], self._config['port']) File "/usr/local/lib/python3.10/ftplib.py", line 158, in connect self.sock = socket.create_connection((self.host, self.port), self.timeout, File "/usr/local/lib/python3.10/socket.py", line 845, in create_connection raise err File "/usr/local/lib/python3.10/socket.py", line 833, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused **NO MATCH** During handling of the above exception, another exception occurred: **NO MATCH** Traceback (most recent call last): ... raise FTPStorageException( storages.backends.ftp.FTPStorageException: Connection or login error using data {'active': False, 'path': '/htdocs/assets/media/', 'host': 'ftp.manuelferrero.com.ar', 'user': 'webmaster.manuelferrero.com.ar', 'passwd': '*********', 'port': 21} and this is my settings.py: import os import environ from pathlib import Path env = environ.Env() environ.Env.read_env() SITE_NAME = 'Manuel Ferrero' BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get("SECRET_KEY") DEBUG = os.environ.get("DEBUG") == "True" ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", … -
How to create a constraint on a field and the date value of created_at in django?
I want to create a constraint that allows an instance of a value for a field to exist only once per day. Meaning if I have a column custom_id and a created_at field, an example value '1' of custom_id can only exist once on 2023-01-01, so adding another field will fail. I am using postgres as a database and from what I have gathered, a query similar to EXCLUDE USING gist (custom_id WITH =, date_trunc('day', created_at) WITH =) However I am failing to replicate this in a django model according to the available -
imported a populated table on to postgresql but I need the model in Django . What to do?
I have a set of populated tables (country,region town etc) that I have imported onto Pgadmin (postgresql) but I need the models in Django now so that I can work on those tables. However, like I said, these were tables with data, so if I write the model definition in Django, it will either destroy my tables by overwriting them (leaving them empty) or it will give an error. I prefer to work now with models, but can't create them because the tables already exist. What can I do? I know you could say, well, you should have first defined the models. Well, no, because the three tables are linked by multiple composite primary keys and actually I got the code for the model once the tables have been imported to the pgadmin, and the model definition was quite complex. If you are curious to see how a model definition looks here it goes: ` class Localidades(models.Model): id_localidad = models.AutoField(primary_key=True) id_region = models.SmallIntegerField() id_pais = models.SmallIntegerField() id_idioma = models.SmallIntegerField() nombre_localidad = models.CharField(max_length=150) x = models.FloatField() y = models.FloatField() exacto = models.SmallIntegerField() class Meta: managed = False db_table = 'localidades' unique_together = (('id_localidad', 'id_region', 'id_pais', 'id_idioma'),) ` I did not even … -
Django primary key field not showing up in postgres database
I have a model class import uuid import datetime, pytz from django.db import models from django.conf import settings class Topic(models.Model): key = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=168) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField() updated = models.DateTimeField(default=datetime.datetime(2000, 1, 1, 0, 0, 0, 0, pytz.UTC)) keyword_json = models.TextField() model_bin = models.BinaryField() article_ttl = models.FloatField(default=48.0) timeliness = models.FloatField(defautl=4.0) It results in a migrations file containing the block name='Topic', fields=[ ('key', models.UUIDField(...)), ('name', models.CharField(...)), ('created', models.DateTimeField()), ('updated', models.DateTimeField(...)), ('keywords_json', models.TextField()), ('model_bin', models.BinaryField()), ('article_ttl', models.FloatField(...)), ('timeliness', models.FloatField(...)), ('owner', models.ForeignKey(...)) ] However the key field is not present in the PostgreSQL database. This results in errors in any code that tries to access the Topic model objects from the database. -
Problem with the construct of LoginView.as_view formula
I know that command django.contrib.auth.views import login has changed. That's why I used a new formula. I don't know why my webiste is not working althouh I think that I used a new formula correctly. Everything is fine: the paths to the files are used correctly although my website is not rendered. enter image description here1[2[3enter image description here](https://i.stack.imgur.com/GzWSH.png)](https://i.stack.imgur.com/wBbFV.png) I will be grateful for any help :) -
python Django - redirect to specific page after login required
I have audio-server in python -Django. I have scenario that I am send a link to admin via E-mail to approve login credentials. link will contain tokan genre-ted by tokan generator something like http://domain/approve/MzA/69s-7a603f32c695968a5345/ I want view function to give list of all users who is on waiting list. but when admin comes on this link I want to check @login that user is logined in with admin credentials if yes redirect to http://domain/approve/MzA/69s-7a603f32c695968a5345/ page else "sorry-page". I have @user_passes_test(is_mbcadmin,login_url="/login/") before my view def but it is redirect to dashboard after right credentials login. can anyone help? PB -
nginx and gunicorn 502 bad gateway
I'm trying to publish the project I created with Django using gunicorn and nginx. But when I visit my server's ip address it returns 502 Bad Gateway. I've been dealing with this error for 4 days. Can you help me please ? /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/DjangoLearning ExecStart=/home/ubuntu/.local/share/virtualenvs/DjangoLearning-_DwN_DVL/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/DjangoLearning/myproject.sock --env DJANGO_SETTINGS_MODULE=config.settings.production config.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/myproject server { listen 80; server_name 52.205.77.21; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/DjangoLearning/myproject.sock; } } /home/ubuntu/DjangoLearning/config/settings/production.py from .base import * import sentry_sdk from sentry_sdk.integrations.django import DjangoIntegration ALLOWED_HOSTS = ['www.osmanefekurt.com', "127.0.0.1", "52.205.77.21"] # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': config("DB_NAME"), 'USER': config("DB_USER"), 'PASSWORD': config("DB_PASSWORD"), 'HOST': 'localhost', 'PORT': '5432', } } sentry_sdk.init( dsn=config("dsn"), integrations=[ DjangoIntegration(), ], traces_sample_rate=1.0, send_default_pii=True ) AWS_ACCESS_KEY_ID = config("ACCES_KEY_ID") AWS_SECRET_ACCESS_KEY = config("SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = 'osmanefes3' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age= 86400', } AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = … -
authorize user using JWT and axios
settings.py from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-siq5r5k3*sg#858b4w8$i*6c-ubf*zkpjj1wb&chn4v$%t!ve+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dlt.urls' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=10), 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True } CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dlt.wsgi.application' # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' … -
Filtering object if it is referenced in another object with many to many relation in Serializer
I am trying to pull a list of all Rooms here where Tenant is equal to the Tenant that is pulled from context data and where the Roomss is a part of the Unit. This is a manytomanyrelationship. Then it should serialize and output the fields for all. This then goes down to Bed as well. The filter for tenant is working but the other filter is not. MODELS.PY class Bed(models.Model): bed_id = models.AutoField(primary_key=True) bed_name = models.CharField(max_length=200) description = models.CharField(max_length=200) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='bedtenant',blank=False) def __str__(self): return self.bed_name class Room(models.Model): room_id = models.AutoField(primary_key=True) room_name = models.CharField(max_length=200) description = models.CharField(max_length=200) beds = models.ManyToManyField(Bed,blank=True,null=True) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='roomtenant',blank=False) def __str__(self): return self.room_name class Unit(models.Model): unit_id = models.AutoField(primary_key=True) unit_name = models.CharField(max_length=200) description = models.CharField(max_length=200) rooms = models.ManyToManyField(Room,blank = True,null=True) tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE,null=True,related_name='unittenant',blank=False) def __str__(self): return self.unit_name Serializers.py class RoomSerializer(serializers.ModelSerializer): beds = serializers.SerializerMethodField('get_beds') def get_beds(self, obj): serializer_context = {'request': self.context.get('request') } user_tenant = self.context.get('request').user.tenant bed_instances = Bed.objects.filter(room__isnull=False,tenant=user_tenant) serializer = BedSerializer(bed_instances, many=True,context=serializer_context) return serializer.data class Meta: model = Room fields = ['room_id','room_name','description','beds'] class BedSerializer(serializers.ModelSerializer): class Meta: model = Bed fields = ['bed_id','bed_name','description'] class UnitSerializer(serializers.ModelSerializer): rooms = serializers.SerializerMethodField('get_rooms') def get_rooms(self, obj): serializer_context = {'request': self.context.get('request') } user_tenant = self.context.get('request').user.tenant room_instances = Room.objects.filter(unit__isnull=False,tenant=user_tenant) serializer = RoomSerializer(room_instances, … -
cannot access my Django application from /api
I have deployed my django Api on kubernetes on my localmachine, windows laptop. I did setup kubernetes deployment, LoadBalancer service and ingress file also. But When i try to access the api using path http://localhost/api/my-api-endpoint it does not work and throws an error server not found. While i can successfully connect using just https://locahost/my-api-endpoint Below is my Service file and Docker file: # START Service apiVersion: v1 kind: Service metadata: name: peopledb-api-service labels: app: peopledb-api-service spec: type: LoadBalancer ports: - port: 80 #port that the service exposes targetPort: 8000 #port that the app is receiving requests from via the pod selector: name: peopledb-api-deployment # END SERVICE --- apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: django-api-ingress annotations: nginx.ingress.kubernetes.io/rewrite-target: / spec: ingressClassName: nginx rules: - host: localhost - http: paths: - path: /api pathType: Prefix backend: service: name: peopledb-api-service port: number: 80 Docker File: FROM python:3.9.7-slim ENV PYTHONUNBUFFERED=1 WORKDIR /api COPY requirements.txt /api/ RUN pip install -r requirements.txt COPY . /api/ EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] please note that I have not included any custom nginx config files or I also did not specify any base URL in my Django app settings. what am I doing wrong? do I need to … -
Arduino + Django REST API + Cloud Run = HTTP 302 + No response
I am exploring the wonderful world of IOT, just started. I wanted to start simple: Arduino Rev2 Wifi, combined with couple of sensors (humidity, temp etc) Django REST API, to push mentioned data, deployed on Cloud Run (MySQL is somewhere else) Some kinda of BI e.g. Looker on gcp etc. I assume that this may not be the go-to architecture but i tried nevertheless :) Django works fine This is the view.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from server.models import Reading, Sensor @csrf_exempt def index(request): if request.method == 'GET': return HttpResponse(False) elif request.method == 'POST': print(request) temperature = request.POST.get("temperature") humidity = request.POST.get("humidity") heatIndex = request.POST.get("heatIndex") sensorId = request.POST.get("sensorId") print(sensorId, temperature, humidity, heatIndex) currentSensor = Sensor.objects.get(pk=sensorId) new_reading = Reading.objects.create( temperature=temperature, humidity=humidity, heatIndex=heatIndex, sensor=currentSensor ) return HttpResponse(True) else: return HttpResponse(False) I can easly push data via Postman and check either via admin panel or MySql workbench that those data were correctly saved. With Arduino is not that simple. #include "DHT.h" #include "WiFiNINA.h" #include "arduino_secrets.h" #include "SPI.h" #define DHTTYPE DHT11 #define DHTPIN 12 DHT dht(DHTPIN, DHTTYPE); float val; int redPin = 2; int greenPin = 7; char ssid[] = SECRET_WIFINAME; char pass[] = SECRET_WIFIPASS; char serv[] = SECRET_SERVER; int status … -
Django filtered queryset doesn't update
Following this tutorial, I'm trying to implement a facet filter based navigation: (starting at 7'05). The facet shows up with the expected materiau__nom and count, but the queryset doesn't update when I click on the filter categories. Is there any visible error in the code? models.py class ObjetArchi(models.Model): id = models.AutoField( primary_key=True, ) materiau = models.ForeignKey( 'Materiau', on_delete=models.SET_NULL, related_name='objets_archi', blank=True, null=True ) class Materiau(models.Model); id = models.AutoField( primary_key=True ) nom = models.CharField( max_length=125, blank=True, null=True ) views.py class NoticesListView(ListView): model = ObjetArchi template_name = 'notices/index.html' context_object_name = 'liste_notices' paginate_by = 20 def get_queryset(self): qs = super().get_queryset() materiau = self.request.GET.get('materiau__nom') if materiau: qs = qs.filter(type=materiau) return qs def get_context_data(self, **kws): context = super().get_context_data(**kws) context['materiaux'] = ( self.get_queryset() .values('materiau__nom') .annotate(count=Count('id')) ) return context urls.py urlpatterns = [ path('', views.NoticesListView.as_view(), name='notices_list'), ] notices/index.html {% for materiau in materiaux %} <ul> <a href="?materiau={{ materiau.materiau__nom }}"> {{ materiau.materiau__nom }} ({{ materiau.count }}) </ul> {% endfor %} {% if liste_notices %} <ul> {% for notice in liste_notices %} <li><a href="{% url 'notices:detail' notice.id %}">{{ notice.titre }}</a></li> {% endfor %} </ul> {% else %} <p>Aucune notice n'est accessible.</p> {% endif %} -
django formset with initial data is not showing the Files
So im using a django formset to show multiple instances of a model and i have a file field in this model. the problem is when i add a file and save it, it's not being shown in frontend part. this is the form: class ProductForm(forms.ModelForm): class Meta: model = Product fields = ( "name", "description", "related_file" ) widgets = { 'description': forms.Textarea(attrs={'rows':4, 'cols':10}), } the formset: ProductFormSet = formset_factory(ProductForm) and view: class ProductView(LoginRequiredMixin, TemplateView): template_name = 'pages/account/products.html' success_url = reverse_lazy('account:products') page_name = 'products' page_title = _('Products') crumb = _('Products') def render_to_response(self, context: Dict[str, Any], **response_kwargs: Any): formset = ProductFormSet( initial=self.request.user.company.products.all().values()) context['formset'] = formset return super().render_to_response(context, **response_kwargs) to test i used these tags in my html file: {{formset.0.initial}} {{formset}} and this is the result: as you can see the initial data is there, and also filled other inputs correctly, but it did not fill the filefield data. -
How to move items between lists in Django
Beginner and fairly new to Django here, I have two Django models and I would like to move an item(s) from one to the other. I am using lists to store the items, but for some reason I can't quite figure out why when I try to remove the item from one and move it into the other it is remaining in the previous list. Here is my code: views.py def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 print(playinglist_items) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: game = Game.objects.get(id=item.game_id) playedlist_items.append(game) present_in_playedlist = True finished += 1 playing -= 1 playinglist_items.remove(game) except: present_in_playedlist = False models.py class Game(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True, max_length=500) image = models.URLField(blank=True, null=True, max_length=500) genre = models.CharField(blank=True, null=True, max_length=200) platform = models.CharField(blank=True, null=True, max_length=200) developer = models.CharField(blank=True, null=True, max_length=200) publisher = models.CharField(blank=True, null=True, max_length=200) added_by = models.CharField(max_length=64) def __str__(self): return f"ID# { self.id }: { self.title }" class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) … -
Slug Error / No Reverse URL for manually uploaded data
I have a slug defined in my model as follows: slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if self.slug is None: self.slug = slugify(self.name + "-" + self.city + "-" + self.state) super().save(*args, **kwargs)``` The issue I'm having is when I bulk upload to the database via CSV I have to manually go in and re-save each business for the slug to save/populate. I would like to be able to simply upload the csv with the slug pre-populated (slug field with formatting is already in the csv). Can I format the slug manually or does this need to be done via the save method in the models.py file? -
Wagtall - template class for blocks StreamField
I have a Strucktblock: # blocks.py class GameBlock(StructBlock): logo = ImageChooserBlock(required=True) image = ImageChooserBlock(required=True) heading = CharBlock(required=True, max_length=50) description = CharBlock(required=True, max_length=100) url_button = URLBlock(required=True) class Meta: icon = "form" template = "blocks/game_card.html" How can I wrap one or more blocks in a template into its own class? For example: <div class="row-grid"> <div class="card">Card1</div> <div class="card">Card2</div> </div> I tried a template: {% for block in page.body %} {% if block.block_type == 'game' %} <div class="row-grid">{% include_block block %}</div> {% else %} {% include_block block %} {% endfor %} And I did: <div class="row-grid"><div class="card">Card1</div></div> <div class="row-grid"><div class="card">Card2</div></div> -
How can I solve django.db.utils.OperationalError when I try to migrate data when I run my docker compose up command?
I am currently working on a project to deploy a django app using docker compose but I keep getting a django.db.utils.OperationalError when I try to migrate data when I run the docker compose up command. This is the full error I am getting; => ERROR [6/7] RUN python3 manage.py makemigrate --settings=core.settings.production 4.5s ------ > [6/7] RUN python3 manage.py makemigrate --settings=core.settings.production: #0 3.964 /usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py:158: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': could not translate host name "postgres" to address: Name or service not known #0 3.964 #0 3.964 warnings.warn( #0 3.985 No changes detected in app 'tags' #0 4.016 No changes detected in app 'users' #0 4.050 No changes detected in app 'content' #0 4.081 No changes detected in app 'actions' #0 4.102 Traceback (most recent call last): #0 4.102 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection #0 4.104 self.connect() #0 4.104 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner #0 4.105 return func(*args, **kwargs) #0 4.105 File "/usr/local/lib/python3.10/site-packages/django/db/backends/base/base.py", line 270, in connect #0 4.106 self.connection = self.get_new_connection(conn_params) #0 4.106 File "/usr/local/lib/python3.10/site-packages/django/utils/asyncio.py", line 26, in inner #0 4.107 return func(*args, **kwargs) #0 4.107 File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 269, in get_new_connection #0 4.108 connection = self.Database.connect(**conn_params) #0 4.108 File …