Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I solve this local variable referenced before assignment in below code?
def Robot_History(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) fm = list(jenkinsHistory.objects.values('id','robotName','jenkinsBuildNumber','jenkinsBuildStatus','errorMsg','Param').filter(robotName=pi)) # print("hello",fm) rob = Robot.objects.all() return render(Request, 'hello/robotHistory.html',{'jenkinsHistory': fm,'robot': rob}) That is my code, whenever i try to sun the code i got the error local variable 'fm' referenced before assignment How to solve that ? -
I wanted to create api for my django project but i alos need to connect Machine Learning project which has a docker file. Now how should i create api?
I have a Machine learning file with Dockerfile. Now i need to create the api and access the ML model in django. How should I do that. Thank you -
How do I use the response from ModelSet view inside my view in Django?
I have a class defined as : class ObjectView(viewsets.ModelViewSet): serializer_class = serializers.ObjectSerialzer queryset = ObjectModel.objects.all() The serializer is defined as: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email', 'username') This creates all the necessary endpoints with various methods like get, post, put etc.. I want to use the data returned from this View with the method get inside of a view. Is there a way to do it or a better way to achieve this function? -
Strange connection error while notifications by celery on heroku
Does anyone know why I'm getting this and how to debug it? WSCONNECTING /ws/notifications/TOKEN" - - DEBUG Upgraded connection ['xxxxxxxx', 23494] to WebSocket DEBUG Creating tcp connection to ('xxxxx.compute.amazonaws.com', 15049) INFO failing WebSocket opening handshake ('Access denied') WARNING dropping connection to peer tcp4:10.1.27.42:23494 with abort=False: Access denied DEBUG WebSocket ['xxxxxx', 23494] rejected by application WSREJECT /ws/notifications/TOKEN -
Option to see/edit objects details in ManyToMany field in Django admin
if we select a foreign key object we get a option to edit that object as shown in image below. But there is no edit option or a way to see the objects in many to many field as you can see below. Is there any option to open the object in a different object and see it's values? -
I want to reflect the images with wagtail
Current state *When I uploaded image files on wagtail, although it is going well to read image title but images itself was destroyed. so the titles is only showed on the display of both admin and user side. I browsed through some blogs and websites on media and static, but this problem has not been resolved for many days. In addition, after using s3, the CSS of admin side might or might not be reflected depending on the browser. development environment python==3.7.3 Django==3.2.6 gunicorn==20.1.0 psycopg2==2.9.1 wagtail==2.14 whitenoise==5.3.0 DB == postgres server == Heroku stack-18 aws s3 ==== the CSS was kept by whitenoise before adapting s3 but I don't know whether to need adding two STATICFILES_STORAGE, therefore remove the one. I could not use collectstatic command, though essensial code comment out for previous code #base.py PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) BASE_DIR = os.path.dirname(PROJECT_DIR) # aws settings """ AWS_ACCESS_KEY_ID = 'AKIAXXXXXXXXXXXXXXX' AWS_SECRET_ACCESS_KEY = 'XXXXXXXXXXXXXXXXXXXX' AWS_STORAGE_BUCKET_NAME = 'XXXXXXXXXXXXXXX' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = None """ AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = f'XXXXXXXXXXXXX.com.s3.amazonaws.com' AWS_URL = os.environ.get('AWS_URL') AWS_DEFAULT_ACL = 'public-read' # static settings """ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_LOCATIONS = 'static' STATICFILES_STORAGE = … -
Webpack ERROR in multi frontend/src/index.js
I get an error when I try to run in dev mode, there is an error in the main file, tell me how I can fix this, thanks in advance "scripts": { "start": "react-scripts start", "test": "react-scripts test", "eject": "react-scripts eject", "dev": "webpack --mode development frontend/src/index.js --output-path frontend/static/frontend/", "build": "webpack --mode production frontend/src/index.js --output-path frontend/static/frontend/" }, Ошибка ERROR in multi frontend/src/index.js Module not found: Error: Can't resolve 'frontend/src/index.js' in 'E:\Work\Folder\src' @ multi frontend/src/index.js main[0] -
Can not user login() function of Django ? Encounter __init__() takes 1 positional argument but 3 were given [closed]
From this link: https://docs.djangoproject.com/en/3.2/topics/auth/default/ I tried to do the login,however, I encounter the __init__() takes 1 positional argument but 3 were given error. Here is the views.py file in my app: class login(generics.GenericAPIView): def post(self, request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return HttpResponse("Login success") else: return HttpResponse("Login fail") When call, I got this error: login(request, user) TypeError: __init__() takes 1 positional argument but 3 were given I thought it is something relating to Session so I here is my middleware in settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware' # I added this row ] Here is my app/urls.py from django.urls import path from . import views urlpatterns = [ path('add', views.add_new_user.as_view(), name='Add new user'), path('login', views.login.as_view(), name='Login to user') ] -
Application error on Deploying Djngo (Python) app
I had deployed my website built with Django via Github. It displays an "Application error". How do I get access to the app via the command line? I want to know the "heroku logs --tail". kindly help me with the code to run. -
How to Containerize sqlite3 and Django app in separate containers for local dev
My project is a web application which is using two technologies wiz: Django + Sqlite3 + Neo4J. I am working on writing docker-compose file so that I can create complete env in just one cmd. The thing which is not clear to me is how I can create three separate container, 1 for Djano, 1 for sqlite3, 1 for neo4j so that app can easily work together. Here the catch point is when Django app run migrate cmd, it create some config.db file in its file system and it should also be shared with sqllite3 db. So how does people handle sqlite3 and Django container issue where table skeleton is created by Django before starting the server and at the same time they want to run sqlite3 in a separate container. my docker-compose.yml: version: '3' volumes: local_neo4j_data: {} local_sqllite_data: {} networks: ecosystem_network: driver: bridge services: neo4j: image: neo4j:latest #4.3.3-community latest container_name: neo4j ports: - "7474:7474" - "7687:7687" networks: - ecosystem_network environment: - NEO4J_AUTH=neo4j/eco_system - NEO4J_dbms_memory_pagecache_size=512M volumes: - ${HOME}/neo4j/data:/data - ${HOME}/neo4j/logs:/logs - ${HOME}/neo4j/import:/var/lib/neo4j/import - ${HOME}/neo4j/plugins:/plugins sqllite3: image: nouchka/sqlite3:latest container_name: sqllite3 stdin_open: true tty: true volumes: - local_sqllite_data:./root/db networks: - ecosystem_network myapp_python: container_name: myapp_python build: context: . dockerfile: compose/Dockerfile volumes: - local_sqllite_data:./myapp_dashboard/config.db … -
Django: Creating unique collection of form elements for every product in e-commerce app
I'm trying to develop a new app in django I'm going to create an easy e-commerce app. This app contains model that include all possible products in the shop. class Product (models.Model): name=models.CharField(max_length=20) and another one that contains all possible form elements for products. class Product (models.Model): id=models.ForeignKey(products, on_delete=models.CASCADE) amount=DecimalField(max_digits=6, decimal_places=2) weigth=DecimalField(max_digits=6, decimal_places=2) color=models.CharField(max_length=20) country=models.CharField(max_length=20) batterycapacity=amount=DecimalField(max_digits=6, decimal_places=2) size=DecimalField(max_digits=2, decimal_places=1) My goal is to create uniqe form collection for every product because for example shoes has different collection of chareacteristic from for example battery. My question is. Is there any way to match chosen form elements for every product? May be instead creating model to connect proper form elements to particular product i should use forms.py in some way. Any suggestions? -
Django aggregate sum on child model field
Consider the following models: from django.db import models from django.db.models import Sum from decimal import * class Supply(models.Model): """Addition of new batches to stock""" bottles_number = models.PositiveSmallIntegerField( bottles_remaining = models.DecimalField(max_digits=4, decimal_places=1, default=0.0) def remain(self, *args, **kwargs): used = Pick.objects.filter(supply=self).aggregate( total=Sum(Pick.n_bottles))[bottles_used__sum] left = self.bottles_number - used return left def save(self, *args, **kwargs): self.bottles_remaining = self.remain() super(Supply, self).save(*args, **kwargs) class Pick(models.Model): """ Removals from specific stock batch """ supply = models.ForeignKey(Supply, on_delete = models.CASCADE) n_bottles = models.DecimalField(max_digits=4, decimal_places=1) Every time an item (bottles in this case) is used, I need to update the "bottles_remaining" field to show the current number in stock. I do know that best practice is normally to avoid storing in the database values that can be calculated on the fly, but I need to do so in order to have the data available for use outside of Django. This is part of a stock management system originally built in PHP through Xataface. Not being a trained programmer, I managed to get most of it done by googling, but now I am totally stuck on this key feature. The remain() function is probably a total mess. Any pointers as to how to perform that calculation and extract the value … -
Stripe 'card-element' is not displaying. Why?
Completely losing my mind with this... I am creating a ecommerce website with django. I use Stripe as Payment Gateway Provider. I don't understand ...Stripe 'card-element' is not displaying. Why ? For information, the card-element used to be displayed correclty in the previous days. I could simulate payments which were recorded in my Stripe account... The thing is, I have checked with older versions of my code which used to work (in case I did a mistake since). But none of them is working... It's driving me crazy. Anything wrong with my code ? Any idea ? checkout.html {% extends 'main.html' %} {% load static %} {% block content %} <script src="https://js.stripe.com/v3/"></script> <div class="container"> <div class="row"> <div class="col d-flex justify-content-center align-items-center"> <h3 class="text-primary fw-bold">PAIEMENT PAR CARTE</h3> </div> </div> <div class="row "> <div class="col d-flex justify-content-center align-items-center"> <form id="payment-form" method='POST' class="col"> {% csrf_token %} <div class="form-control" id="card-element"></div> <div class="sr-field-error" id="card-errors" role="alert"></div> <button id="payer-submit" class="btn btn-primary"> <div class="spinner-border spinner-border-sm text-light d-none" id="spinner" role="status"></div> <span class="text-white" id="button-text">Pay</span> <span class="text-white" id="order-amount"></span> </button> </form> </div> </div> <div class="row "> <div class="col d-flex justify-content-center align-items-center"> <form id="payload" method='POST' class="col" action="/payment/payment-bycard-complete"> {% csrf_token %} <input id ="data-payload" type="hidden" name="payload"/> </form> </div> </div> </div> <script type="text/javascript" src="{% static … -
How do i relate model X to an instance of model X?
Suppose i have class modelX(models.Model): value = models.CharField(max_length=200) now var1 = modelX(value='some_value') var2 = modelX(value='another_value') How do i connect var1 and var2 ? I know about .objects.all method but thats not what i want. I want something like a linked list. -
How to handle a post request in json format to own laptop in python via django or flask
I have configured an http webhook on thethingsstack webpage cloud.thethings.network that performs a post request to a configured endpoint (my laptop) as follows: http://xxx.ngrok.io -> http://localhost:80 For uplink message: http://localhost:80/uplink-message For join ack: http://localhost:80/join-accept Using ngrok.exe http 80 I can also see that I receive the post requests in my command line: POST /uplink-enabled 502 Bad Gateway POST /uplink-enabled 502 Bad Gateway POST /uplink-enabled 502 Bad Gateway However, I'm not able to receive the data in json format following the online tutorials: enter link description here enter link description here Is there a code example that listens continuously to the http port and handles post requests? -
Django db block for migration with no schema change
When updating the helptext of field of a Django model, it produces a migration to track this change. This operation doesn't perform any sql query (checked with manage.py sqlmigrate myapp). However, does it still lock the table like normal schema change migration? -
How to Issue and Return a book in Library Managament System
1st Problem - What I want is that when a user issue a book the quantity must be decreased by 1 and once there is no book user should not be able to issue the book and this should be handled by bookIssueView(first view) 2nd Problem - I want to return(remove from issued book list) issued books by clicking return and once the book returned the quantity must be increased by 1(I could not handle this also) now when button clicked it is showing - ConnectionDoesNotExist at /book-return/1/ The connection 'Django For Pro' doesn't exist - Here is the code written Related Views def bookIssueView(request, id): book = get_object_or_404(Book, id=id) issue_date = timezone.now() quantity = 0 book_issue = BookIssue.objects.create( issue_date=issue_date, book=book, reader=request.user.reader, quantity=quantity ) book = book_issue messages.info(request, "Book has been issued.") return redirect("book_issue_list" def bookIssueView(request, id): book = get_object_or_404(Book, id=id) issue_date = timezone.now() quantity = 0 book_issue = BookIssue.objects.create( issue_date=issue_date, book=book, reader=request.user.reader, quantity=quantity ) book = book_issue messages.info(request, "Book has been issued.") return redirect("book_issue_list") Related Models class Book(models.Model): book_name = models.CharField(max_length=50) author_name = models.CharField(max_length=50) isbn = models.CharField(max_length=50, unique=True) category = models.CharField(choices=CATEGORY, max_length=30) description = models.TextField() cover = models.ImageField(upload_to="book_cover/") status = models.CharField(choices=BOOK_STATUS, default="Available", max_length=50) quantity = models.IntegerField(default=0) class BookIssue(models.Model): reader … -
Login not working in django when using rewrites from firebase hosting to cloud run
Current Setup: I've got a Django application behind gunicorn running on Cloud Run. Since the region it is deployed in does not support Custom Domains, I have a firebase hosting setup with the following code: { "hosting": { "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [{ "source": "/**", "run": { "serviceId": "website", "region": "ap-south1" } }] } } The relevant settings in settings.py: CSRF_TRUSTED_ORIGINS = ['.<domain>.com'] CSRF_COOKIE_SECURE = True SESSION_COOKIE_SECURE = True The problem: However, the login form on /admin does not work if I access the site using my domain name https://doman.com/admin even though it works fine if I use the Cloud Run endpoint https://endpoint-uw.a.run.app. Faulty behaviour: When accessing it from my domain, the login page shows up, I enter my credentials and log in, it adds the relevant cookies to my browser but then it redirects me back to the login page. Could it be that since the URL is being rewritten by firebase django is expecting a cookie from uw.a.run.app? I tried adding the setting SESSION_COOKIE_DOMAIN = '.<domain>.com' but that did not fix it either, it just made the Cloud Run endpoint stop working as well. Any advice on how to fix this or how to diagnose … -
How to display python variable to Django UI
I'm trying to subscribe to a MQTT topic called Wind. After that I want to show the value in my Django chart. But whenever I return the result of my MQTT value with test it showed me name 'test' is not defined. My Idea: Globalize the msg.topic with test and then use test in showdata class. But unfortunately it don't work, Does anyone have any idea on this issue? Thanks My code (views.py): from django.shortcuts import render from paho.mqtt import client as mqtt_client import random broker = 'localhost' port = 1883 topic = "Wind" # generate client ID with pub prefix randomly client_id = f'python-mqtt-{random.randint(0, 100)}' # username = 'emqx' # password = 'public' def showdata(request): context = test return render(request, 'index.html', {'data': context}) def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg, request): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") global test test = msg.topic client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ == '__main__': run() -
How to save one table value to another table in django?
I have two models mentioned in below Robot - class Robot(models.Model): robot = models.CharField(max_length=100) short_Description = models.CharField(max_length=200) status = models.CharField(max_length=20) parameter = models.CharField(max_length=200) jenkins_job = models.CharField(max_length=100, default='JenkinsJobName') jenkins_token = models.CharField(max_length=100, default='JenkinsToken') jenkins_build = models.CharField(max_length=10, default=0) jenkins_build_status = models.CharField(max_length=20, default="Never Run") def __str__(self): return self.robot jenkinsHistory - class jenkinsHistory(models.Model): robotName = models.ForeignKey(Robot, on_delete=models.CASCADE, blank=True, null=True) jenkinsBuildNumber = models.CharField(max_length=100) jenkinsBuildStatus = models.CharField(max_length=200) errorMsg = models.CharField(max_length=500) Param = models.CharField(max_length=500,blank=True, null=True) my robot table has some data . now i want to assign some Robot table data in my jenkinsHistory table. so that i have written view like this def Run_data(Request,id): if Request.method == 'POST': pi = Robot.objects.get(pk=id) name = pi.robot print("name", name) hist = jenkinsHistory(robotName= name,jenkinsBuildStatus='Jenkins-Running') hist.save() but when i try to run that . it is giving me error like this How to solve that issue and assign data in jenkinsHistory table from Robot table? -
Django unable to persisted cached array
Django cannot persist my cached data even if I set timeout to none. My settings.py contains this: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'django_cache', #'/var/tmp/django_cache', 'TIMEOUT': None, } } I save data with this line of code: cache.set('array', array, timeout=None) I fetch data like this: array = cache.get('array') try: iterator = iter(array) except TypeError: # Array not iterable: my app gets here when cache data is lost else: # I go through the array and get needed info I don't think it's a MAX_ENTRIES issue because I only have one array with 39 elements. When the data is lost, the array becomes not iterable (because empty). I also tried using file cache cause I suspected that restarting the Django app may clear the RAM cache but had the same issue. I've tried file caching with the following configuration in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': os.path.join(BASE_DIR, 'filecache'), 'TIMEOUT': None, } } The "filecache" directory is created and contains a non-empty cache file but I still loose my cached array somehow. -
How to send MQTT topic value to Django UI
I'm trying to subscribe to a MQTT topic called Wind. After that I want to show the value in my Django chart. But whenever I return the result of my MQTT value with test it showed me name 'test' is not defined. My Idea: Globalize the msg.topic and then use in my showdata class. But unfortunately it don't work, Does anyone have any idea on this issue? Thanks My code (views.py): from django.shortcuts import render from paho.mqtt import client as mqtt_client import random broker = 'localhost' port = 1883 topic = "Wind" # generate client ID with pub prefix randomly client_id = f'python-mqtt-{random.randint(0, 100)}' # username = 'emqx' # password = 'public' def showdata(request): context = test return render(request, 'index.html', {'data': context}) def connect_mqtt() -> mqtt_client: def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client: mqtt_client): def on_message(client, userdata, msg, request): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") global test test = msg.topic client.subscribe(topic) client.on_message = on_message def run(): client = connect_mqtt() subscribe(client) client.loop_forever() if __name__ == '__main__': run() -
Use context variable to compare with forloop.revcounter in Django
I can not use context variable to compare with forloop.counter or forloop.revcounter. No error returning. But, every time if statement become false. here is my view func- def view_single_server(request, pk): server = PhysicalServer.objects.get(pk=pk) context = { 'server' : server, 'n':range(42) } return render(request,'server/view_single_server.html', context ) And Here is my templete- {% for i in n %} {% if forloop.revcounter == server.loc_in_rack %} <li>{{server.loc_in_rack}}</li> {% else %} <li>No Server</li> {% endif %} {% endfor %} What wrong am I doing? -
How can i get to filter talent , talent2 both using django filter
views.py def get_ajax(self, request, *args, **kwargs): talent= request.GET.get('talent', None) users = User.objects.all().order_by('last_name') if talent: user = users.filter(user_talent=talent) and users.filter(user_talent2=talent) models.py def get_talent(self): talent = f'' if self.user_talent: talent = f'{self.user_talent}' if self.user_talent2: talent = f'{self.user_talent}, {self.user_talent2}' return talent -
Not able to connect to websocket using Nginx and Uvicorn
I built a docker container with Django, Uvicorn, Nginx and Redis, and am using django-channels but when I run this it says it cannot connect to the websocket and this is seen in the browser console: WebSocket connection to 'ws://127.0.0.1:8080/ws/notifications/' failed It is working fine when I use Django's runserver command for development but when I include Nginx and Uvicorn it breaks. Entrypoint.sh: gunicorn roomway.asgi:application --forwarded-allow-ips='*' --bind 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker Nginx config: upstream django { server app:8000; } map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 8080; location /static { alias /vol/static; } location /ws/ { proxy_pass http://0.0.0.0:8000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } location / { proxy_pass http://django; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_redirect off; proxy_buffering off; } } settings.py: CHANNEL_LAYERS={ 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [('redis', 6379)], #Redis port } } } The JS file which handles the socket: var wsStart = "ws://" var webSocketEndpoint = wsStart + window.location.host + '/ws/notifications/' const notificationSocket = new WebSocket(webSocketEndpoint) asgi.py: application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AuthMiddlewareStack( URLRouter([ url(r'^ws/notifications/', NotificationConsumer.as_asgi()), path("ws/<str:room_name>/", ChatConsumer.as_asgi()) ]) ) })