Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django connection with Sybase SQL Anywhere 17 with pyodbc on Digital Ocean App Platform
I need help with connecting to the Sybase SQL Anywhere database via the pyodbc library. When I am running a local development server or local python desktop script connection is established easily and successfully. I found out that the problem is in the SQL Anywhere 17 driver. In the scripts below you can see that when I run pyodbc.drivers() in a local environment I get a list with a few drivers, and when I repeat the same in the App platform application console I get an empty list. My question is how can I install or transfer SQL Anywhere 17 driver to the App platform or ubuntu droplet? Thank you! views.py code connection_string = "Driver=SQL Anywhere 17;" \ "Server=xxx;" \ "Host=host;" \ "UID=user;" \ "PWD=pass;" \ "DBN=db_test;" \ "Port=xxxx;" \ "DSN=xxxx;" \ "dobroadcast=all;" \ "APPINFO=xxx;" def my_view(request): rows = [] with pyodbc.connect(connection_string) as conn: cur = conn.cursor() cur.execute('SELECT NAZIV1 FROM ARTIKEL') rows = list(cur.fetchall()) return render(request, 'app/my_template.html', {'rows': rows}) -
Razorpay Signature Verification faild
I am trying to integrate Razorpay into my django-rest-framework application. I am following this article. I am able to create Orders successfully. But not able to do the payment. You can directly see the whole code in github repository. views.py from django.shortcuts import render from django.conf import settings from django.views.decorators.csrf import csrf_exempt from .constants import PaymentStatus import json import razorpay from .models import Order client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET)) def home(request): return render(request, "index.html") def order_payment(request): if request.method == "POST": name = request.POST.get("name") amount = request.POST.get("amount") razorpay_order = client.order.create( {"amount": int(amount) * 100, "currency": "INR", "payment_capture": "1"} ) order = Order.objects.create( name=name, amount=amount , provider_order_id=razorpay_order["id"] ) order.save() return render( request, "payment.html", { "callback_url": "http://" + "127.0.0.1:8000" + "/razorpay/callback/", "razorpay_key": settings.RAZORPAY_KEY_ID, "order": order, }, ) return render(request, "payment.html") @csrf_exempt def callback(request): def verify_signature(response_data): return client.utility.verify_payment_signature(response_data) print(f'first request.POST: {request.POST}') print(f'input {request.body}') if "razorpay_signature" in request.POST: payment_id = request.POST.get("razorpay_payment_id", "") provider_order_id = request.POST.get("razorpay_order_id", "") signature_id = request.POST.get("razorpay_signature", "") order = Order.objects.get(provider_order_id=provider_order_id) order.payment_id = payment_id order.signature_id = signature_id order.save() print(f'signature verification: {verify_signature(request.POST)}') if not verify_signature(request.POST): order.status = PaymentStatus.SUCCESS order.save() return render(request, "callback.html", context={"status": order.status}) else: order.status = PaymentStatus.FAILURE order.save() return render(request, "callback.html", context={"status": order.status}) else: payment_id = json.loads(request.POST.get("error[metadata]")).get("payment_id") provider_order_id = json.loads(request.POST.get("error[metadata]")).get( "order_id" ) order = … -
Django AJAX Get Request from Client Side
I am very new to Django and trying to learn sending an ajax request with id to Django server HTML <input class="search-input" type="search" placeholder="Search..." onkeyup="filterCars(this.value)"/> JS <script> function filterCars(str) { let xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", "/?id="+str, true); xmlhttp.send(); } </script> Django url: urlpatterns = [ path('',views.index), path('<str:id>', views.getCar) ] Django views: def getCar(request): fileJs = serializers.serialize("python", CarModel.objects.all()) id = request.query_params["id"] print(id) return render(request, 'index.html', {'fileJs': fileJs}) For now my issue is that the id is not printing and seems I am not accessing it properly. This is the response I get in terminal: "GET /?id=h HTTP/1.1" 200 425559 Thanks a lot in advance! -
How to display name of city instead of id?
I have 2 models: class City(models.Model): name = models.CharField(max_length=50, default='') def __str__(self): return self.name class Street(models.Model): name = models.CharField(max_length=50) city = models.ForeignKey(City, on_delete=models.CASCADE) def __str__(self): return f"{self.city}: {self.name}" And i want to display all streets of city by url: path('city/<int:pk>/street/', views.CityDetail.as_view()) The following View: class CityDetail(APIView): def get(self,request, pk, format=None): city = City.objects.get(id = pk) # try except for DoesNotExist streets = Street.objects.filter(city=city) serializer = StreetSerializer(streets, many=True) # Name instead of id! return Response(serializer.data) How to display name of cit instead of id? [{"id":1,"name":"Почтовая","city":1},{"id":2,"name":"Ленина","city":1},{"id":3,"name":"Быстрецкая","city":1}] -
Python Django +WhatsApp bot + Twilio ,use regex to match URL of different papers .I
I am building a WhatsApp bot that when grade 12 students type subject year and paper 1 or 2 ,the bot goes to saexams.co.za find a matching URL and then download paper and memo .All the URLs to the papers are like this https://saexampapers.co.za/wp-content/uploads/2021/09/Mathematics-NSC-P1-QP-Sep-2021-Eng.pdf but have different IDs after the year like '/09/' which range from 1 to 10 . how can i use regex to search for url with matching ID .code smaple is below. def bot(request): #message =request. POST["body"] if request.POST: message = request.POST["Body"] sender_name = request.POST["ProfileName"] number = request.POST['From'][9:] print(number) print(sender_name) print(request.POST) if message =="hi" or message =='Hi' or message =='Hello' or message=='Hie': message = client.messages.create( from_='whatsapp:+14155238886', body='Hello there {} , I am Nkosi Ncube BOT . I only assist you to download math papers .This is how you type the paper you want - Mathematics P2 Sep 2021'.format(sender_name), to='whatsapp:{}'.format(number) ) elif 'Mathematics' in message : message = request.POST["Body"].replace(" ","") sender_name = request.POST["ProfileName"] url1 =f'https://saexampapers.co.za/wp-content/uploads/{message[16:]}/09/{message[:11]}-NSC-{message[11:13]}-QP-{message[13:16]}-{message[16:]}-Eng.pdf' url2=f'https://saexampapers.co.za/wp-content/uploads/{message[16:]}/09/{message[:11]}-NSC-{message[11:13]}-Memo-{message[13:16]}-{message[16:]}-Eng.pdf' print(url1) print(url2) download = wget.download(url1) download2 = wget.download(url2) print(message) url_list =[url1,url2] for i in range(0,2): message = client.messages.create( from_='whatsapp:+14155238886', media_url = url_list[i], to='whatsapp:{}'.format(number) ) else: message = client.messages.create( from_='whatsapp:+14155238886', body='Sorry {} i dont understand try to rephrase'.format(sender_name), to='whatsapp:{}'.format(number) ) return HttpResponse("hello") … -
QuerySet Django, need to get multiple result on one
I got this model : class BfMatchingNafRome(models.Model): code_naf = models.CharField(null=False,max_length=255) libelle_naf = models.CharField(null=True,max_length=255) code_rome = models.CharField(null=True,max_length=255) I want to put some data in a table. {% for match in matching %} <tr> <th scope="row">{{match.code_naf}}</th> <td>{{match.libelle_naf}}</td> <td> {% for i in match.code_rome %} {{i}} {% endfor %} </td> {% endfor %} I use : matching = BfMatchingNafRome.objects.filter(code_naf__lte=activity.code_activity).order_by('code_naf') I've tried absolutely all I can find on stack overflow, google, youtube, but I cant link my datas. I just get, on my view, one line with code_naf - code_rome. I want one line per code_naf with all code_rome for this code_naf. I create multiple entries (for an other view I need one data by entry). But, for this view, I need to receive datas linked. Thanks for help -
How to make work javascript in template in django
I'm trying to use js to save values in selected options. It works if js put it in my HTML template. Like this: {% load static %} {% include "header.html" %} {% block content %} <script src="{% static 'ReportingTool/js/sort_text.js' %}"></script> <script src="{% static 'ReportingTool/js/sort_number.js' %}"></script> ... <form method="GET" action="."> <div class="row"> <div class="border border-2 p-2 g-2"> <label for="periodMin">Start date</label> <input type="date" class="myselect form-select form-select-sm" id="periodMin" name="period_min"> <label for="periodMax">End date</label> <input type="date" class="myselect form-select form-select-sm" id="periodMax" name="period_max"> </div> <div class="border border-2 p-2 g-2"> <label for="structDivisions">Structural divisions</label> <select id="structDivisions" class="myselect form-select form-select-sm" name="struct_division"> <option selected>Choose...</option> {% for SD in struct_divisions %} <option id="{{ SD.id }}" value="{{ SD }}"> {{ SD }}</option> {% endfor %} </select> <label for="workers">Worker</label> <select id="workers" class="myselect form-select form-select-sm" name="worker"> <option selected>Choose...</option> {% for worker in workers %} <option value="{{ worker }}">{{ worker }}</option> {% endfor %} </select> </div> <div class="border border-2 p-2 g-2"> <label for="workDone">Work done</label> <select class="myselect form-select form-select-sm" id="workDone" name="work_done"> <option selected>Choose...</option> {% for work in workstype %} <option value="{{ work }}">{{ work }}</option> {% endfor %} </select> <label for="scope_min">Scope min</label> <input type="number" min=0 class="myselect form-control form-control-sm" id="scope_min" name="work_scope_min"> <label for="scope_max">Scope max</label> <input type="number" min=0 class="myselect form-control form-control-sm" id="scope_max" name="work_scope_max"> <label for="notes">Notes contains</label> <input type="text" class="myselect … -
Websocket connection issue on django production server
I am facing an issue with the WebSocket protocol. I am using Django channels/daphne. Everything is working normally on the development local server. I think the issue is with NGINX settings. The error code is 1006 Here is the reverse proxy that I am using: location ~* \.(js|css|jpg|png|jpeg|html)$ { try_files $uri $uri/ /; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; #Persistent connection related configuration add_header X-Cache $upstream_cache_status; #Set Nginx Cache proxy_ignore_headers Set-Cookie Cache-Control expires; add_header Cache-Control no-cache; expires 12h; } location /ws/ { proxy_pass http://127.0.0.1:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } #PROXY-END/ -
How to get() the non-numeric primary key field's value during model save
I am trying to catch the primary key field's value during model save using: def save(self, *args, **kwargs): if self.pk: # For some post processing, I am trying to catch the instance "ID", and make changes to fields cls = self.__class__ old = cls.objects.get(pk=self.pk) # Getting current model state. << Error occurs here new = self # Newly instantiated model object with new values. # ... # ... This works fine if I have the following model definition (primary key as Integer): class myModel(models.Model): some_fld_id = models.AutoField(primary_key=True, verbose_name='... However, if I use a charField as the primary key like so: class myModel(models.Model): some_fld_id = models.CharField(primary_key=True, max_length=6, ... It fails with error: myModel matching query does not exist. And points to the line with: old = cls.objects.get(pk=self.pk) Now due to some constraints, I am to define the primary_key as a charField (and still be able to catch the pk value). How can I achieve this. -
Docker Django Is the server running on that host and accepting TCP/IP connections?
I'm running Django app on Docker container, the problem is it can't see the database connection is already up. Dockerfile FROM ubuntu RUN apt-get update # Avoid tzdata infinite waiting bug ARG DEBIAN_FRONTEND=noninteractive ENV TZ=Africa/Cairo RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN apt -y install certbot python3-certbot-apache RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN apt -y install software-properties-common RUN add-apt-repository universe RUN apt update RUN ln -sf /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd RUN apt install wait-for-it RUN a2enmod headers RUN service apache2 restart COPY www/demo_app/water_maps/requirements.txt requirements.txt RUN pip install -r requirements.txt ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 5432 WORKDIR /var/www/html/demo_app docker-compose.yaml version: "2" services: db: image: postgres restart: always volumes: - ./data/db:/var/lib/postgresql/data ports: - '5332:5432' environment: - POSTGRES_DB=(db name here) - POSTGRES_USER=(db user here) - POSTGRES_PASSWORD=(db password here) django-apache2: build: . container_name: test_water_maps restart: always environment: - POSTGRES_DB=(db name here) - POSTGRES_USER=(db user here) - POSTGRES_PASSWORD=(db password here) ports: - 5000:80 - 5001:443 volumes: - ./www/:/var/www/html - ./www/demo_app/kml_files:/var/www/html/demo_app/kml_files - ./www/demo_app/temp_kml_file:/var/www/html/demo_app/temp_kml_file - ./www/demo_app/upload:/var/www/html/demo_app/upload command: sh -c 'wait-for-it db:5432 -- python manage.py migrate && apache2ctl -D FOREGROUND' # command: sh -c 'wait-for-it db:5432 -- … -
def send_confirmation_email coming up with error of nonetype
As I'm not using webhooks in my latest project, I need to setup function for sending confirmation emails when user places an order. However it always comes up with an error of Attribute Error : 'NoneType' object has no attribute 'user' What am I doing wrong here? def send_confirmation_email(order): """ Send email to customer with order confirmation """ cust_email = order.user_profile.user.email subject = render_to_string( 'checkout/confirmation_emails/confirmation_email_subject.txt', {'order': order}) body = render_to_string( 'checkout/confirmation_emails/confirmation_email_body.txt', {'order': order, 'contact_email': settings.DEFAULT_FROM_EMAIL}) send_mail( subject, body, settings.DEFAULT_FROM_EMAIL, [cust_email] ) -
Extra fields on many-to-many relationships: How to automatically create the "through" fields?
I'm trying to use a many to many field in order to add a set of facilities to a lead. The trouble is that i need an extra field for the date and time of the tour scheduled for each of the facilities i add to the lead. So when i create a lead and add facilities to the lead i have that extra field where i can enter date and time and access it afterwards as a list of facilities with their tour dates on the leads page. I came across many to many fields using "through" but I'm not sure if that's even the right option to use in this case. ManyToMany Fields with extra fields How can i use a many to many field using "through" and have the through field automatically be generated for each facility i add to my lead with the many to many field? Or is using through not a good option? I'm using Django Rest Framework with a React Frontend: models.py class Facility(models.Model): Name = models.CharField(max_length=150, null=True, blank=False) mainimage = models.ImageField(null=True, blank=True) Email = models.EmailField(max_length=150, null=True, blank=True) TelephoneNumber = models.CharField(max_length=30, null=True, blank=True) FacilityDescription = models.TextField(max_length=1000, null=True, blank=True) def __str__(self): return self.Name class … -
How to see certificate contents for incoming request in Django?
I am building an Endpoint to receive data inside POST request, And a webserver is going to send that request to my server, and they have SSL Certificate, Now i need to verify inside my API View that the request is coming from them not anyone else, And i will check that by getting their Digital Certificate and check it, Now how can i view their certificate inside the request in Django View? -
KeyError in django when using a textarea
I want to do a very simple operation : 1-taking some info form the form 2-saving the data in the database But i get this error and i don't know the reason of it! can you please help . this is the forms.py : class ContactForm(forms.Form): title = forms.CharField(max_length=500) phone_mail = forms.CharField(max_length=30) body = forms.Textarea() this is the models.py : class Contact(models.Model): title = models.CharField(max_length=500) phone_mail = models.CharField(max_length=30) text = models.TextField() this is the views.py : def contact(request): if request.method == 'POST': form = forms.ContactForm(request.POST) if form.is_valid(): data = form.cleaned_data Contact.objects.create(title = data['title'] , text = data['body'] , phone_mail = data['phone_mail']) return redirect('accounts:profile') else : form = forms.ContactForm() con = {'form' : form} return render(request , 'home/contact.html' , con) And this is the form : <form class="row g-3 p-3" method="post"> {% csrf_token %} <div class="col-md-6"> <label for="title" class="form-label">title</label> <input type="text" class="form-control" id="title" name="title"> </div> <div class="col-md-6"> <label for="phone_mail" class="form-label">phone or email</label> <input type="text" class="form-control" id="phone_mail" name="phone_mail"> </div> <div class="col-12"> <label for="inputtext" class="form-label">text:</label> <textarea type="text" class="form-control" name="body" id="inputtext" minlength="20" maxlength="10000" required></textarea> </div> <div class="col-12"> <button type="submit" class="btn btn-primary">Send</button> </div> </form> And i get this error for them when i use the form to send the data : KeyError at /contact/ 'body' … -
How to mock settings in Django Unit testing
I am new to Django Unit testing and am trying to write unit test for a simple function which is like below: utils.py #some import statements from django.conf import settings if platform.system() == 'Linux': cx_Oracle.init_oracle_client(lib_dir=settings.GAP_DB_LIB_DIR) else: cx_Oracle.init_oracle_client(lib_dir=settings.LOCAL_DB_LIB_DIR) db_password = settings.DB_PASS db_user = settings.DB_USER db_connection_dsn = settings.DB_CONNECTION_DSN def project(repo): pieces = parse.urlsplit(repo) return pieces.path.rstrip('/').split('/')[-1] I am writing unit tests in test.py fie as below from django.test import TestCase from common import utils from utils import project from django.test import override_settings # Create your tests here. class UtilsTest(TestCase): def setUp(self): self.repo = "http://test/testrepo" @override_settings(LOCAL_DB_LIB_DIR="c:/testdir") def test_project(self): response = utils.project(self.repo) self.assertEqual(response,"testrepo") When I run tests am getting below error: AttributeError: 'Settings' object has no attribute 'LOCAL_DB_LIB_DIR' Please help me where I am doing wrong and correct my coding. Thanks in advance. -
In Django with all-auth, how do I pass the authenticated user from the front end to be saved in the database table through a form?
I have been able to get my form to write to the database but I have two issues. One with passing the site_name to the slug field so that the user doesn't have to manually enter a slug and one passing the authenticated user to the "pilot" field automatically. I'd like to address the user issue with this question. When I render all fields of the model as a form I am able to manually select the user from a drop-down list of the possible users (all users) when submitting a form. I would like to take this field away from the form and have it auto-populate with the name of the currently authenticated user. Is there a way to set the default value in 'pilot' field of the model to be the currently authenticated user? I have tried a few different ways but I am running into different errors. I am very new to Django so don't have a great understanding. I have included the previous attempt in the view commented out. Thanks for your help. View def UploadFlyingSite(request): if request.method == "POST": form = SiteUpload(request.POST) if form.is_valid(): site_details = form.save() site_details.pilot = request.user.username site_details.slug = site_details.site_name site_details.save() # … -
Пытаюсь привязать Postgresql с Django.Библиотека psycopg2 установлена.Данные базы данных изменены,но при попытке запустить сервер выходит такая ошибка
Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 263, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\postgresql\base.py", line 215, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 564, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 58, in init self.build_graph() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 323, in cursor return self._cursor() File "C:\Users\GIGABYTE\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py", line 299, in … -
Directional/ guidance related to Django, secured code hosting
I just joined today and this is my first post. I hope everyone is doing well. First, NOT AT ALL am a programmer and therefore there may be some elementary dependency in my posts (note this first). For some reasons, I was tasked to start a web application (small with, but have the potential to be scaled in the future with a proper dev team)... My questions below are very conceptual, I would need your thoughts/expert advice here. NOTE: The application is an analytics tool that is 80% forms, tables, tree charts, dropdowns and popups that interact with the database to extract the data on the front end and manipulate the data in the database based on user input. To develop the application in less time, we use the Django framework. In the YouTube tutorials, I see that the web UI is open on localhost:8000. How can I redirect this address so that it appears in my URL? How secure are the shared domains offered by web hosting companies (like GoDaddy, Hostinger, etc.)? When the time is right, all applications need to be hosted in the cloud, with proper security encryption of the data. Is there a good data management … -
Celery current_task.update_state not working
I'm trying to add a long running async task and make it update it's progress status in intervals. I'm using a Django-rest-framework server, RabbitMQ broker, Celery worker. I'm able to add a task to celery, and even able to successfully retrieve the result upon task completion. However whenever trying to get the state before task completion I get the following: task.result = None, task.state = PENDING, task.info = None When trying to get state post completion: task.result = None, task.state = PENDING, task.info = None DeployML/ manage.py DeployML/ ... settings.py tasks.py dcelery.py views.py urls.py dcelery.py: import os from celery import Celery import sys sys.path.append('.....DeployML') sys.path.append('.....DeployML/DeployML') # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings') app = Celery('DeployML', backend='rpc://', broker='pyamqp://guest@localhost//', worker_state_db = '/tmp/celery_state') app.config_from_object('django.conf:settings') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') tasks.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DeployML.settings') from celery import shared_task from celery import current_task from dcelery import app import time @app.task(bind=True) def addShrd(self, x, y): for i in range(4): time.sleep(5) progress_percent = i #NOTE update_state not working yet current_task.update_state(state='PROGRESS', meta={'current': i, 'total': 4}) return x + y views.py: #... #... @api_view(['GET', 'POST']) def ml_celer_view(request): print("authentication: ", request.user, request.auth) if request.method == 'GET': result = addShrd.delay(17,10) return Response({'task_id': str(result.id)}) … -
how can I solve this error on angular app
This error is showing after I keeps running ng serve --disable-host-check and have enable for all origin on python django rest framework Access to XMLHttpRequest at 'localhost:8000/supplier/' from origin 'http://localhost:4200' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, chrome-untrusted, https, isolated-app. -
I use POST methon in Django, but my request.method == 'POST' said that it's GET methon
I don't know why my create function worked before, but now is not working. I see only "It's not POST, it's GET". I have tried to delete something, for example: from def index(request): email = str(request.GET.get('autorization_email')) and from def create(request) type_values = Type.objects.all() model_values = Model.objects.all() equipment_values = Equipment.objects.all() It didn't helped url.py urlpatterns = [ path('', views.autorization, name='autorization'), path('home/', views.index, name='home'), path('return_equpment/', views.return_equpment, name='return_equpment'), path('create/', views.create, name='create'), ] create.html {% block content %} <form method="post" action="{% url 'create' %}"> {% csrf_token %} ... <button type="submit" class="btn btn-success">Save</button><br> <span>{{ error }}</span><br> </form> {% endblock%} views.py from django.shortcuts import render, redirect from .models import Booking, Type, Model, Equipment from .forms import BookingForm error = '' email = '' def index(request): global email global error email = str(request.GET.get('autorization_email')) context = { 'title': 'Main page', 'error': error, 'index_email': email } return render(request, 'main/index.html', context) def create(request): type_values = Type.objects.all() model_values = Model.objects.all() equipment_values = Equipment.objects.all() form2 = BookingForm() global error global email context = { 'form': form2, 'error': error, 'type_values': type_values, 'model_values': model_values, 'equipment_values': equipment_values, 'create_email': email } if request.method == 'POST': form2 = BookingForm(request.POST) form2.email = email form2.type = request.POST.get('type') form2.model = request.POST.get('model') form2.number = request.POST.get('number') if form2.is_valid(): form2.save() return redirect('autorization') else: … -
socket "/cloudsql/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022) Is the server running locally and accepting connections on that socket?
I have tested connectivity for cloud SQL instance and started web server in sample Django project. #.\cloud_sql_proxy.exe -instances="instance-name"=tcp:5432 python manage.py runserver It is working fine in sample Django project. But whenever We are trying to execute the above commands by our Django Project, we are facinng the following error when execute the python manage.py runserver. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\KarthikKumar\Documents\GitHub\tnt-deploy\venv\lib\site-packages\psycopg2_init_.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: connection to server on socket "/cloudsql/ajrsd2:us-central1:ajrsd2/.s.PGSQL.5432" failed: Invalid argument (0x00002726/10022) Is the server running locally and accepting connections on that socket. I have checked secrets details in https://console.cloud.google.com/security/secret-manage There are no restrictions in the access permission. Also I have verified steps as per the below reference link. Sir https://cloud.google.com/python/django/appengine#console_3 Please check and let us know the solution. Thanks -
How to handle migrations for 3rd-party django apps in a deployment pipelines?
I'm using a 3rd party dependency modeltranslation-lokalise which requires me to run python manage.py makemigration. This will generate a migration file that sits within the package directory once generated, and therefore are not source controlled. For all other migration files I'm keeping them in source control and would like to do the same for these, as it will allow us to track changes to the database in the environments we use, ensuring they can be easily replicated and that operations are not duplicated on the same database (e.g. by having the same operation exist in differently-named migrations). My question: How are these 3rd party migrations meant to be handled when building and deploying to production (e.g. via a Dockerfile in a build pipeline? My guess would be to find a way to reliably extract the migration files from the package and add it to source control. The alternative would be: run makemigrations within the Dockerfile that builds the deployed image, however that could result in the same migration being run twice on the database should the name of that migration change (e.g. if there's a timestamp in the name). So I'm thinking best to avoid that. Note: this question is … -
django Imagefield accepting all files
In my registration page, I am able to input a file other than an image for example -.txt or .py then save it. Even though my model is an Imagefield it allows files other than images. I have other models with imagefield in them but they are working fine. When I try to save a txt or py file there it raises an error. But in my registration page it directly saves it. I have also added validators still does not work. Note that when I try to edit user from admin page there it raises an error. models.py : from django.contrib.auth.models import User from django.core.validators import validate_image_file_extension from django.db import models from django.utils import timezone from multiselectfield import MultiSelectField # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, help_text=False) profile_pic = models.ImageField(upload_to="profile_pic/",validators=[validate_image_file_extension], null=True , blank=True) def __str__(self): return self.user.username views.py def register(request): accounts = User.objects.all() if request.method == "POST": user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.is_active = False user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() messages.success(request, 'Your account has been created Sucessfully!!!!') messages.success(request, 'You can use your account after it has … -
No Tag matches the given query. on localhost:8000/filter/en
I've been working on a project, where I want to filter a resource on a page by language. But everytime I use that filter, i'm getting redirected to a 404-Page. This is my View: class SomeView(LoggedUserWithOrganizationMixin, ListView): paginate_by = 12 def get_queryset(self): qs = Example.objects.all() selected_language = self.kwargs.get("selected_language",self.request.user.profile.language) return qs.filter(language = selected_language) This is my url in urls.py: path('<str:selected_language>/', views.SomeView.as_view(), name="list-lang-filter"), And this is my HTML-Code for the select where the user can pick the language: <div x-show="dropdownOpen" class="w-full absolute rounded border border-forblueshadow bg-white z-20 font-light text-brightblue pt-1"> {% for language in languages %} <a href="{% url 'list-lang-filter' current_organization.pk language.code %}" class="language_filter_dropdown rounded-t py-2 px-4 block whitespace-no-wrap"> {{ language.name }} </a> {% endfor %} </div> When choosing an option in the filter-menu, i get redirected to a url with the right language code in it, but it just shows a 404. The weird thing is i did the exact same thing on another resource and it worked just fine. Does anybody have an idea?