Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Save sensor data in a Django database
Im doing a Django app that tries to show data taken from an ultrasonic sensor. What I want is to take the distance from the sensor and save it in its Django table. Normally this is done with a form, but i want it to be done in the backend for each sensor object. This is the code that i have for the moment: Ultrasonicsensor.py import time from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger def main(): # Grove - Ultrasonic Ranger connected to port D16 sensor = GroveUltrasonicRanger(16) counter = 10 while (counter < 10): distance = sensor.get_distance() #This is the distance i want to save for each sensor object distance = (float(distance) / 100) print('{:.4f} m'.format(distance)) if distance < 1: print('Cerca') elif 1 <= distance <= 1.9: print('Medio') else: print('Lejos') time.sleep(1) counter = counter + 1 Models.py class UltrasonicSensor(models.Model): name = models.CharField(max_length=50, default="HC-SR04") description = models.TextField() pin = models.IntegerField() distance = models.DecimalField(max_digits=20, decimal_places=4) date = models.DateTimeField(auto_now_add=True) Views.py class uSensorDetailView(DetailView): template_name = 'sensor_detail.html' context_object_name = 'sensor' def get_queryset(self): return UltrasonicSensor.objects.all() -
Getting wrong headers for Traefik ForwardAuth middleware
I've been trying to develop a custom auth thing for Traefik using Django and the ForwardAuth middleware. Unfortunately, I'm having troubles with the provided headers for my application: My auth app has three endpoints: /auth/, which checks whether the user is authenticated. If it is, returns a "OK" with status code 200. If it's not, tries to get the X-Forwarded-Host in order to build a redirect argument using f"?redirect={request.headers['X-Forwarded-Proto']}://{request.headers['X-Forwarded-Host']}" and then redirect to /auth/login/{redirect_url} /auth/login, which renders a form and then authenticates with Django (it uses the same logic as /auth/ for setting up a redirect URL /auth/logout It's exposed at https://auth.my-ip.nip.io, using the following: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: django-auth spec: entryPoints: - websecure routes: - match: Host(`auth.my-ip.nip.io`) kind: Rule services: - name: django-auth port: 80 tls: secretName: auth.my-ip.nip.io The middleware is configured as follows: apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: django-auth spec: forwardAuth: address: https://auth.my-ip.nip.io:443/auth/ trustForwardHeader: true Finally, I've got an example app exposed and using the django-auth middleware: apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: game-2048 spec: entryPoints: - web - websecure routes: - match: Host(`2048.my-ip.nip.io`) kind: Rule services: - name: game-2048 port: 80 middlewares: - name: django-auth tls: secretName: 2048.my-ip.nip.io But then, when I try to … -
Django deployment with docker - create superuser
I have 3 environments set up and cannot createsuperuser. The way I migrate and runserver now follows the container so I have an entrypoint.sh: #!/bin/sh 1 2 echo "${RTE} Runtime Environment - Running entrypoint." 3 4 if [ "$RTE" = "dev" ]; then 5 6 python manage.py makemigrations --merge 7 python manage.py migrate --noinput 8 python manage.py runserver 0:8000 9 10 python manage.py createsuperuser --username "admin" --email "admin@banl.com" --password "superuser" 11 echo "created superuser" 12 13 elif [ "$RTE" = "test" ]; then 14 15 echo "This is tets." 16 python manage.py makemigrations 17 python manage.py migrate 18 python manage.py runserver 19 20 elif [ "$RTE" = "prod" ]; then 21 22 python manage.py check --deploy 23 python manage.py collectstatic --noinput 24 gunicorn kea_bank.asgi:application -b 0.0.0.0:8080 -k uvicorn.workers.UvicornWorker 25 26 fi lines 10/11 is what I want to make work, I think I have a syntax issue. Originally I wanted the password and username to be variables stored in an env file: 1 RTE=dev 1 POSTGRES_USER=pguser 2 POSTGRES_PASSWORD=pgpassword 3 POSTGRES_DB=devdb 4 DJANGO_SUPERUSER_PASSWORD=superuser 5 DJANGO_SUPERUSER_EMAIL=admin@bank.com 6 DJANGO_SUPERUSER_USERNAME=admin But now I just want it to work, I need to create a superuser account in order to develop. Can anyone spot what's wrong? … -
react-django connectivity issues, 500 internal server errors
I’m working on a project using react as the frontend and Django rest api as backend. Unfortunately, I’m having some issues. Here are the issues I’m facing: From the Django setting.py file, I set the static directory folder to “build” (for css, images and JavaScript) and media folder (for user uploaded files) file to “media” as shown below. But I observed that only the “media” folder shows up in the directory structure and not the “build” folder. PLEASE WHAT COULD BE PREVENTING THE “BUILD” FOLDER FROM SHOWING? STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/medial/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I understand that normally when you run “npm build” and copy the build folder generated from the frontend to replace the one in the Django backend, then you can begin to use “localhost:8000” to access your pages rather than continue to use “localhost:3000”. I did the above, but I wasn’t able to load the pages using “localhost:8000” but instead getting 404 error. PLEASE WHAT COULD BE THE ISSUES? I created some routes (post and get), tested all the routes in postman as well as the browser, and they (routes) are all working perfectly. … -
Django - Translate variable before rendering to template
I am currently using Django Translation in order to switch between en/es and viceversa. And I know that I can use {%blocktrans%} in order to translate a variable inside a template. The problem is that I have no access to the template of this particular feature where I need to translate several words. How do I translate a variable before rendering it into a template? -
Problems to display the Form in the Template using CreateView
What happens is that I am using CreateView and I find it curious that the code works when I put {{form}}, it displays all the fields and saves in the database (everything works very well) but when I break down the values one by one for example: {{form.plates}}, {{form.type}}, it does not send anything to the database and it stays on the same page. Why is that? I just need it broken down clientes-add.html <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row mb-3"> <div class="col-md-3"> <div class="mb-3"> <label>Customer type</label> <br> <div class="form-check form-check-inline"> {{ form.tipo }} </div> </div> </div> </div> <div class="row mb-3 only-corp hide-item"> <div class="col-md-12"> <div class="mb-3"> <label>Corporation name</label> {{ form.corporacion }} </div> </div> </div> <button class="btn btn-primary mb-3" type="submit" value="Post">Save</button> </form> -
Django pasar parametros por url
a través de una etiqueta y href paso parametros por url. Las etiquetas son del navbar y funcionan como filtro el problema esta en que al seleccionar una segunda opción la url no se maxaca y vuelve a insertar la ruta a la view. Esto como se puede solucionar? views.py: def pueblo(request, pueblo): activo = establecimientos.objects.filter(pueblo=pueblo) context = {'establecimientos_objects':activo} return render(request, 'orders/establecimientos.html', context) urls.py: path('pueblo/<str:pueblo>',views.pueblo, name='pueblo'), template: <ul class="nav nav-pills flex-column mb-auto"> <li class="nav-item"> <a href="pueblo/opcion1" class="nav-link link-dark" aria-current="page"> opcion1 </a> </li> <li> <a href="pueblo/opcion2" class="nav-link link-dark"> opcion2 </a> </li> <li> <a href="pueblo/opcion3" class="nav-link link-dark"> opcion3 </a> </li> </ul> -
Django background_task results in BrokenPipeError
I'm using django 3.1.4, django-background-tasks 1.2.5. I have a task registered which runs to completion successfully when I perform updateProducts.now() from the shell, but for some reason when it's automatically ran, it results in BrokenPipeError at different parts of the code. Often it refers to a collection not being undefined in a dictionary which is in the constructor of the GClient class. All collections are defined in the GClient class constructor. @background(schedule=timezone.now()) def updateProducts() -> None: client = GClient() db_client = DBClient() total_products = 0 collections = ["collection1", "collection2", "collection3", "collection4"] for collection in collections: products = client.getProductOfCollection(collection) if products is None: continue total_products += len(products) for product in products: db_client.addProduct(product) if "inventoryQuantity" in product and product["inventoryQuantity"] > 0: notify_restock(product["id"], db_client) print(db_client.updateErrors) db_client.updateErrors = {} print(f"Done Updating {total_products} Products") if not Task.objects.filter(verbose_name="Update Products").exists(): updateProducts(verbose_name="Update Products", repeat=7200, repeat_until=None) getProductOfCollection - Performs a GraphQL request for an array of products which can take anywhere between 3secs to 1min to fulfill, it checks periodically whether it's been fulfilled. Once fulfilled, it receives a link with a json to download, it downloads the json, parses it, stores all the products in an array and returns it. -
ERROR code 1452 mysql in windows and but not in linux
I have a django project that creates tables after manage.py migrate. I use some LOAD DATA LOCAL INFILE MySQL queries for both. I have 7 tables. All the first 6 tables are populated the same way in both Linux and Windows. Except for the last table that has some foreign keys in previous ones. Linux MySQL Output Windows MySQL Output Both Windows and Linux tables are in InnoDB and the parent table has exactly the same data. Table information in Linux Table information in Windows Section Table keys in Linux Section Table keys in Windows INSERT INTO `seas_database`.`section_t` (`eSession`,`eDays`,`dYear`,`nSectionNumber`,`nSectionCapacity`,`nEnrolled`,`bIsBlocked`,`tStartTime`,`tEndTime`,`cCoffCode_ID`,`cFaculty_ID`,`cRoom_ID`) VALUES ("Spring","F",2009,1,250,43,0,"14:00","15:30","AAT101","T001","C10210-S"); Proof that AAT101 exists in Windows Yet i get this error in Windows ONLY. Not in Linux. Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`seas_database`.`section_t`, CONSTRAINT `section_t_cCoffCode_ID_ade53504_fk_cooffered` FOREIGN KEY (`cCoffCode_ID`) REFERENCES `coofferedcourse_t` (`cCoffCode_ID`)) Linux MySQL version : mysql Ver 8.0.27 for Linux on x86_64 (MySQL Community Server - GPL) Windows MySQL version: C:\Program Files\MySQL\MySQL Server 8.0\bin\mysql.exe Ver 8.0.27 for Win64 on x86_64 (MySQL Community Server - GPL) If it helps, the csv for which the LOAD DATA INFILE was ran, it was modified and created by Pandas from an xlsx file. -
how to search table by QR code scanning in django admin
Lookup Records with Qr code scanning in Django how we can add search option by QR scanning in django on the table.i wanna create the table .every item has unique QR code and i wanna search by scanning QR code (using mobile ) and show the matching data can i do in Django admin ??? -
How to Share single App to Django Developer?
I am developing a big application. How to share only single app to a developer. For Example there are 5 developers working on a Project. I want each developer to see only single app. Not complete code. Problem i am facing is with Django ORM. Since we import Django models inside the views. So other apps should be present in Django project to work. Approach which i found → Instead of Django ORM use Sqlalchemy. Here i can give access to specific app to developer. If he require some other table then i give him permission from Postgres to that corresponding table. I am confused in this method. Do big companies like Instagram provide code to every developer? Any blog or any answer is appreciated. -
Is it possible to create related objects on parent creation automatically in Django?
I have a Profile model and NotificationSettings model with OneToOne relation. There is more than one way to create Profile, but NotificationSettings must be created with all of them. I don't want to write same code for every view that creates Profile. So i was hoping that there is some event that i can track so NotificationSettings would be created automatically. Something similar to RubyOnRails' after_create callback -
Django NGINX uswsgi custom admin site permission
Just found out this tutorial for gunicorn https://codyparker.com/protect-django-admin-nginx-gunicorn/ Is there a way to add the same filterin case of proxying uwsgi? server { listen 80; server_name myserver; charset utf-8; location / { uwsgi_pass localhost:9876; include /opt/uwsgi_params } location /admin/ { allow 192.168.1.0/24; allow 10.1.1.0/16; deny all; proxy_pass http://myserver; } result in: 502 Bad Gateway -
Why won't my icons load in a django environment(or what ever its called)?
Good evening everyone. I had been coding outside a virtual environment for quite some time, so i decided it was finally time to put my project on a django app/environment/server/whatever lol. However, my fontawesome icons did not load when i did so. I tried everything i could possibly do -- I tried using both internal and external links to fontawesome. My icons are still loading perfectly outside the virtual environment, so I'm not sure what the problem is. -
ImportError: Could not import 'rest_framework.pagination.LimitOffsetPagination'
I am going to use latest django 4.0 with djangorestframework. After command: python manage.py runserver ImportError: Could not import 'rest_framework.pagination.LimitOffsetPagination' for API setting 'DEFAULT_PAGINATION_CLASS'. ModuleNotFoundError: No module named 'pytz'. -
How to fetch axios GET response to FullCalendar Vue.Js
Hello I'm traying to fetch my GET response axios to FullCalender events to make the events display dynamically -
ProgrammingError at /sign-up/ relation "auth_user" does not exist LINE 1: SELECT (1) AS "a" FROM "auth_user" WHERE "auth_user"."userna
so i just hosted my django app on Heroku and everytime i try to create an account i keep getting this error my views.py register function def register(request): if request.user.is_authenticated: return redirect('home') form = registerform() if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'User does not exist') return render(request, 'register.html', {'form' : form}) help, thanks -
Django AWS Elastic Beanstalk .ebextensions cronjob
I have successfully set up a cron in AWS extensions to run a Django command at a certain time. Although, I have unsuccessfully been able to run/add multiple commands at different times. Question: if I wanted to run multiple Django commands as cron jobs, would I add new duplicate config files (like below) within in my .ebextensions folder OR is it possible to add a new Django command (w/ different time) to the one below? .ebextensions -cron_job.config files: /usr/local/bin/cron_activity_use.sh: mode: "000755" owner: root group: root content: | #!/bin/bash source /opt/python/run/venv/bin/activate source /opt/python/current/env cd /opt/python/current/app docker exec `docker ps --no-trunc -q | head -n 1` python manage.py cron_activity_use /etc/cron.d/m_cron: mode: "000644" owner: root group: root content: | */10 * * * * root /usr/local/bin/cron_activity_use.sh commands: rm_old_cron: command: "rm -fr /etc/cron.d/*.bak" ignoreErrors: true -
How we use Recommendation System in Django?
I am working on a project (Recommendation for Clothes of E-commerce Site for Online Shopping) in which we almost done module 1 and in module 2 I use recommendation system. Requirements are : The system should be able to recommend the products to the user based on his/her buying history. For implementing the recommendation functionality in your Project you have to use AI (Machine Learning) based Approach. So how I'll perform this task ? -
DJANGO - Add/update/delete row in table with backup in sqlite database
Hi everyone :) (sry for my bad english you will have a french accent x) ) I'm stuck in my project because i need to update data already display by model (database objects). So, i need to add a row, delete a row with confirmation of user, and modify data ( i can already modify data but only into the table (with contenteditable="true" into the td ), it don't save it into the database). I really need you help to solve this problems, thanks in advance everyone :) Here my models (i use tableau): from django.db import models class Intervenants(models.Model): name = models.CharField(max_length=3, null=True) def __str__(self): return self.name class tableau(models.Model): Statut = models.CharField(max_length=1, null=True) Facturation = models.CharField(max_length=1, null=True) Commande = models.CharField(max_length=1, null=True) Num_d_affaire = models.CharField(max_length=100, null=True) Projet = models.CharField(max_length=120, null=True) Localisation = models.CharField(max_length=120, null=True) Descriptif = models.CharField(max_length=120, null=True) Archi = models.CharField(max_length=120, null=True) Date_Marqueur = models.CharField(max_length=10, null=True) BBIO_RT = models.CharField(max_length=10, null=True) DIAG_FAISA = models.CharField(max_length=10, null=True) APS = models.CharField(max_length=10, null=True) APD = models.CharField(max_length=10, null=True) PRO = models.CharField(max_length=10, null=True) DCE = models.CharField(max_length=10, null=True) ACT = models.CharField(max_length=10, null=True) VISA = models.CharField(max_length=10, null=True) DET = models.CharField(max_length=10, null=True) AOR = models.CharField(max_length=10, null=True) Charge_d_affaire = models.CharField(max_length=3, null=True) Second = models.CharField(max_length=3, null=True) Intervenant3 = models.CharField(max_length=3, null=True) Intervenant4 = … -
DRF: Share data between multiple SerializerMethodFields in ListSerializer
I have a DRF project with the following view: class AssetViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = Asset.objects.all() serializer_class = AssetSerializer def get_serializer_class(self): if self.action == "list": return AssetListSerializer if self.action == "retrieve": return AssetSerializer return AssetSerializer # For create/update/destroy My problem is within the AssetListSerializer: class AssetListSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() name = serializers.ReadOnlyField() block_count = serializers.SerializerMethodField("get_block_count") requirement_count = serializers.SerializerMethodField("get_requirement_count") open_requirements = serializers.SerializerMethodField("get_open_requirements") in_progress = serializers.SerializerMethodField("get_in_progress") measure_count = serializers.SerializerMethodField("get_measure_count") All these methods call the same internal (expensive) method and then work with the result: def _get_asset_requirements(self, asset_id): req = do_some_expensive_method(asset_id) return req def get_requirement_count(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla def get_open_requirements(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla def get_in_progress(self, instance): requirements = self._get_asset_requirements(instance.id) blablabla So what I would like to do is to only to the expensive method once per object and then access the result from the SerializerMethodField-methods. I have found this part in the documentation: https://www.django-rest-framework.org/api-guide/serializers/#customizing-listserializer-behavior However I am clueless on how to implement it. My idea was something like: @classmethod def many_init(cls, *args, **kwargs): cls.req = cls._get_asset_requirements(cls.instance.id) return super().many_init(*args, **kwargs) but this does not work as I can't access the instance this way and the documentation is really incomplete here. Does anyone have an idea how to solve … -
python subprocess command (javac "Main.java") is not working on production
i am trying to compile java file from python(django). when i run my code on local sever then my java file compiled sucessfully but when i upload the files on heroku,Javac not found error showing def method1(request): code=request.data.get('code') len1=request.data.get('len') if os.path.isfile("Main.java"): os.remove("Main.java") f = open("Main.java", "x") f.write(code) f.close() file = 'Main.java' # codes[compile(file,len1)] std="" try: output = subprocess.check_output( "javac "+file, stderr=subprocess.STDOUT, shell=True, timeout=3, universal_newlines=True) except subprocess.CalledProcessError as exc: std="Status : FAIL", exc.returncode, exc.output else: # std="Output: \n{}\n".format(output) std="compiled sucess" context={ 'msg':'we got data', 'code':code, 'len':len1, 'std':std } return Response(context) This is my view.py file. response on local server "msg": "we got data", "code": "public class Main{\n public static void main(String[]args){\n \n System.out.println(\"HELLO Sid\");\n \n }\n}", "len": "java", "std": "compiled sucess" } response on heroku server "msg": "we got data", "code": "public class Main{\n public static void main(String[]args){\n \n System.out.println(\"HELLO Sid\");\n }\n}", "len": "java", "std": [ "Status : FAIL", 127, "/bin/sh: 1: javac: not found\n" ] }``` -
Chatting platform with django
I built a real-time chatting platform with Django framework using channels, but I don't understand why it's not saving the chat history to the database. So I added a few lines of codes, but now it showing undefined. Can anybody show me how to fix the code on my consumers.py? from django.contrib.auth import get_user_model from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync from .models import Message import json User = get_user_model class ChatConsumer(WebsocketConsumer): def fetch_messages(self, data): messages = Message.last_10_messages() content = { 'messages': self.messages_to_json(messages) } self.send_messages(content) def new_message(self, data): author = data['from'] author_user = User.objects.filter(username=author)[0] message = Message.objects.create( author=author_user, content=data['message']) content = { 'command': 'new_message', 'message': self.message_to_json(message) } return self.send_chat_message(content) def messages_to_json(self, messages): result = [] for message in messages: result.append(self.message_to_json(message)) return result def message_to_json(self, message): return { 'author': message.author.username, 'content': message.content, 'timestamp': str(message.timestamp) } commands = { 'fetch_messages': fetch_messages, 'new_message': new_message } def connect(self): self.room = self.scope['url_route']['kwargs']['room'] self.room_group_name = 'chat_%s' % self.room async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): data = json.loads(text_data) self.commands[data['command']](self, data) def send_chat_message(self, message): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'message': message } ) def send_messages(self, message): self.send(text_data=json.dumps(message)) def chat_message(self, event): message = event['message'] … -
DetailView in Django, keyword 'slug'
I recently started learning Django. I want to display one news item, but when I open on the link I get an error message: Cannot resolve keyword 'slug' into field. Choices are: NewsTitles, NewsContent, NewsSlug Request Method: GET Request URL: http://127.0.0.1:8000/news/nam-gravida-purus-non/ Django Version: 4.0 Exception Type: FieldError views.py from django.views.generic import DetailView from .models import News class GetNews(DetailView): model = News slug_url_kwarg = 'NewsSlug' template_name = 'news/single_news.html' context_object_name = 'single_news' allow_empty = False urls.py from django.urls import path from .views import GetNews urlpatterns = [ path('news/<str:NewsSlug>/', GetNews.as_view(), name='news'), ] models.py from django.db import models from django.urls import reverse_lazy class News(models.Model): NewsTitles = models.CharField(max_length=120) NewsContent = models.TextField(max_length=255) NewsSlug = models.SlugField(max_length=255) def __str__(self): return self.NewsTitles def get_absolute_url(self): return reverse_lazy('news', kwargs={'NewsSlug': self.NewsSlug}) What am I doing wrong? -
populate an excel with data from a django model
I populated a Django model with a pandas dataframe. In order to do this is had I used the to_dict() function in order for JSONField() Django model to accept the data. Is fine and works well. No what I am trying to do is to populate an excel file with this data. So I am accessing the data in the Django model and trying to use openpyxl to populate an excel with this data. However I am running into problems as I am getting the error saying that it cannot convert to excel. Anyway around this? My model: class myvalues(models.Model): items_list = models.JSONField() function that’s trying to populate excel: values_to_go_into_excel_obtained_from_model = myvalues.objects.values_list(“items_list”, flat=True) path = file_for_download.my_file.path wb = load_workbook(path) ws = wb["Sheet1"] pd.read_excel(path, engine='openpyxl', sheet_name="Sheet1") for row, v in enumerate(values_to_go_into_excel_obtained_from_model, 2): ws.cell(row, 4, v) wb.save(path) Any ideas why I am getting the error. Basically what Im trying to do is: Step 1: pandas df -> Django model of type Json Step 2: Access Django model values Step 3: put values from Django model into excel file I have step 1 and 2 but for cant get step 3.