Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker, problem creating and running container. Error creating or running container: 409 Client Error .../exec: Conflict (container...is not running)
In Django, in development phase i'm building and running a Docker container using a pool. I'm new to Docker. As you can see, I deliberately don't use the shell for personal project reasons. The code worked correctly until yesterday, then after turning the PC off and on again the code doesn't work today. PROBLEM. If I understand correctly, the problem is that I am trying to follow commands in a container that is not running, but after trying various solutions to wait, it seems that waiting is useless. The error is: Error creating or running container: 409 Client Error for http+docker://localhost/v1.44/containers/76950z4e1c65fx9hq7f8756db496eb2c0f7870609756g904452231580aa6e596b/exec: Conflict ("container 76950z4e1c65fx9hq7f87 56db496eb2c0f7870609756g904452231580aa6e596b is not running") SOLUTION ATTEMPTS. I have already tried several solutions, such as checking the state of the container in a loop (with for or while) and waiting for it to become "running" before proceeding with the creation of the running instance, or I have also tried time.sleep or other similar types of time). But this doesn't solve the problem. OBSERVATION: So the problem isn't about WAITING and I don't want a solution where you have to wait, because otherwise it means something is wrong. I also checked to close all previously created containers in … -
It is impossible to add a non-nullable field 'name' to table without specifying a default
class Track(gisModels.Model): track = gisModels.PolygonField() class GeoFence(gisModels.Model): track = models.ForeignKey(Track, on_delete=models.CASCADE) fence = gisModels.PolygonField(geography=True) The above code is my models. It is impossible to add a non-nullable field 'track' to geofence without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Select an option: I have no idea to solve it out. -
Using Django filter inside Javascript
I am beginner at django, I stuck at using Django filter inside javascript. I was trying to implement Load More data using ajax. Everything works fine but i am not able to append new data to the html container. In my home view which is extends to base.html. i have the following html content- {% block content %} {% for post in posts %} <article class="media card border-secondary" style="margin: 1rem 0;"> <div class="card-body media-body"> <h5 class="card-title">{{post.post_title}}</h5> <h6 id="reading-time" class="card-subtitle mb-2 text-muted">{{post.post_content | readtime }}</h6> <p class="card-text">{{post.post_content | truncatewords:50 |markdown|striptags }}</p> <!-- | safe --> <a href="{% url 'article-page' post.post_id post.post_title|slugify %}" class="stretched-link">Continue Reading</a> </div> </article> {% endfor %} <button type="button" id="loadmorebtn" class="btn btn-outline-primary mx-auto d-block btn-lg">Load More</button> {% endblock content %} I am using some built-in django filter and one custom filter. On Load More button clicked i have some ajax code which runs fine and return the data- <script type="text/javascript"> $(document).ready(function () { var offset = 5 const loadBtn = $('#loadmorebtn'); loadBtn.click(function (e) { e.stopImmediatePropagation(); $(this).prop('disabled', true); // Disable the button $(this).html('<span class="spinner-grow spinner-grow-lg align-middle" role="status" aria-hidden="true"></span> Loading...'); // Change button text $.ajax({ url: "{% url 'load-more-posts' %}", type: "GET", data: { 'offset': offset }, dataType: 'JSON', success: function … -
Dockerized nginx and django on Apache installed VPS
I'm trying to deploy my dockerized django project with nginx container to a VPS server which has apache. Nginx conf with 80 port, I'm getting port already in use error. Therefore, I've changed my config as following. nginx.conf; server { listen 8080; server_name sub.example.com; resolver 127.0.0.11 ipv6=off valid=10s; charset utf-8; location /static { alias /var/www/static; } location / { proxy_pass http://app; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } docker-compose.yml; version: '3.8' services: nginx: restart: unless-stopped build: context: ./nginx dockerfile: './Dockerfile' ports: - "8080:8080" volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf - staticfiles:/var/www/static container_name: nginx depends_on: - app app: image: core build: ./ restart: always container_name: app command: bash -c "python manage.py collectstatic --noinput && python manage.py migrate && gunicorn --bind 0.0.0.0:8000 core.wsgi:application --reload" volumes: - ./storage/assets/staticfiles:/app/storage/assets/staticfiles - staticfiles:/app/storage/assets/staticfiles/ - .:/app expose: - 8000 ports: - 8000:8000 env_file: - .env depends_on: - redis redis: restart: always image: redis:latest expose: - "6379" worker: build: ./ command: celery -A core worker -l info -Q celery environment: - C_FORCE_ROOT=true volumes: - .:/app depends_on: - redis beat: build: ./ command: celery -A core beat -l info volumes: - .:/app links: - redis depends_on: - redis volumes: staticfiles: When I build and run the project on … -
BaseSSHTunnelForwarderError django, python, linux (Ubuntu 22)
I was trying to run my django app (python framework v3.10.12, pip v24.0, django v4.2.5) on Linux (Ubuntu 22) and when executing the command python3 manage.py runserver I got this error message: 2024-02-28 15:58:07,627| ERROR | Could not open connection to gateway Traceback (most recent call last): File "/home/jheison/web_app/lambda_project/manage.py", line 22, in <module> main() File "/home/jheison/web_app/lambda_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/core/management/__init__.py", line 382, in execute settings.INSTALLED_APPS File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/django/conf/__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/jheison/web_app/lambda_project/lambda_project/settings.py", line 96, in <module> ssh_tunnel.start() File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/sshtunnel.py", line 1331, in start self._raise(BaseSSHTunnelForwarderError, File "/home/jheison/.local/share/virtualenvs/web_app-yZNsHh7j/lib/python3.10/site-packages/sshtunnel.py", line 1174, in _raise raise exception(reason) sshtunnel.BaseSSHTunnelForwarderError: Could not establish session to SSH gateway Note: I ran git clone xxxxx correctly, installed requirements.txt with pipenv install -r requirements.txt Note: I have already … -
Nginx www to root redirection not working
this is my nginx config upstream django { server unix:///var/tmp/******.sock; } server { listen 80; server_name mydomain.com; charset utf-8; client_max_body_size 75M; location /static { alias **********; } location / { uwsgi_pass ********; include *************; } } server { listen 80; server_name www.mydomain.com; return 301 $scheme://mydomain.com$request_uri; } here mydomain is working fine when i go to www.mydomain i am not getting redirected. and lands on nginx default page. -
Is there an automated way to generate CRUD templates on django Project/App
I'm new in django, and it seems as it says batteries included FW, and I was wondering if this feature is available in django to generate CRUD templates for each entity using CLI.. like Python manage.py createCrud books, Member This might include the urls, views etc Is there something like that.. or maybe a plugin can do this? I haven't yet resulted something valuable. Expecting python code or plugin installation then super-tuning -
Django conditional annotation using python variable
Trying to figure out a way to use annotation depending of python variable condition check. Example: some_variable = 10000,50 #float expenses_by_categories = ( Category.objects.filter(transactions__operation="expenses") .annotate( expenses_sum=Sum('transactions__value', filter=Q( transactions__date_created__month=datetime.date.today().month) & Q( transactions__date_created__year=datetime.date.today().year)), ) .annotate( percentage=Round( ExpressionWrapper( F('expenses_sum') / some_variable * 100, output_field=FloatField() ), 2)) .order_by('-percentage') ) It works as long as some_variable greater then 0 otherwise zero devision exception rised. Is there is a way to carry out some checks inside annotation with such a logic: if some_variable > 0: percentage = F('expenses_sum') / some_variable * 100 else: percentage = 0 -
React Native (Expo) + Django app: TypeError: Network request failed
I have a React Native (Expo go) frontend and Django based backend. I have the django backend setup with some API endpoints, which I am trying to reach from frontend. When using npx expo start --tunnel command instead of npx expo start command to launch the frontend, the web requests to the backend fail. This is the full setup: In django settings, I have these settings setup: CORS_ALLOWED_ORIGINS = [ 'exp://julyt-u-anonymous-8081.exp.direct', 'http://localhost:19006', 'http://192.168.153.13:8081', '10.0..rest_of_the_ip', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ('*') ALLOWED_HOSTS = ['*'] I am launching the django server with: python manage.py runserver 10.0..rest_of_the_ip:8000 I am launching the frontend with: npx expo start --tunnel When sending webrequest to the api endpoint, I get this in the frontend side: E.g., ERROR API::loginUser->FAILED TO LOGIN USER: [TypeError: Network request failed] Backend side does not receive anything. This same setup works when I am using same wifi for both backend and frontend, for example when I am at a cafe: python manage.py runserver local_IPv4:8000 npx expo start And for the record, using npx expo start does not work when I am using this current wifi. The phone (expo go app) won't connect to the server, and thus it is not an option … -
Django social network application - which machine learning model should I use and how to store it?
I am writing a Django project for a social network application. I need to create a machine learning model that - using existing data on a user's hobbies, interactions with content, current friends, etc - predicts the top 20 users to be matched. Which is the best model type to use for this situation? I thought about creating a model for each user but would that be optimal? How can I generalize the model to fit as many users as possible? Should I store the model on file or as part of the models.py in my Django project? -
issue with adding new category models and searching posts using it
Good afternoon! I have django application, on main(index) page i have posts, and there is side bar on that sidebar i have code for showing and searching posts in concrete category, (i copied it from tutorial, and teacher didnt showed how to work with that), now there is only 1 category that work succesfully (named just as "category"), i must add 2 new categories model, with same functionality, but with other models (datepublication and univercity) here is base html (sidebar with functionality here) {% load static %} {% load women_tags %} <!DOCTYPE html> <html> <head> <title>{{title}}</title> <link type="text/css" href="{% static 'women/css/styles.css' %}" rel="stylesheet" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="shortcut icon" href="{% static 'women/images/main.ico' %}" type="image/x-icon"/> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <table class="table-page" border=0 cellpadding="0" cellspacing="0"> <tr><td valign=top> {% block mainmenu %} <div class="header"> <ul id="mainmenu" class="mainmenu"> <li class="logo"><a href="{% url 'home' %}"><div class="logo"></div></a></li> {% for m in menu %} <li><a href="{% url m.url_name %}">{{m.title}}</a></li> {% endfor %} {% if request.user.is_authenticated %} <li class="last"> {{user.username}} | <a href="{% url 'logout' %}">Выйти</a></li> {% else %} <li class="last"><a href="{% url 'register' %}">Регистрация</a> | <a href="{% url 'login' %}">Войти</a></li> {% endif %} </ul> <div class="clear"></div> </div> {% endblock mainmenu %} <table class="table-content" … -
Multiple Objects Returned. Django AllAuth
I am trying to get GitHub sign up option setup. But it keeps returning multiple objects. What I've learned until now is that there must be 2 entries in the social apps in Django admin. I checked and there is only 1. MultipleObjectsReturned at / No exception message supplied Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.0.10 Exception Type: MultipleObjectsReturned Exception Location: /usr/local/lib/python3.11/site- I have setup everything correctly in settings.py. I don't think that is causing the issue. <li class="nav-item"> <a href="{% provider_login_url 'github' %}">Git</a> </li> This in the template is causing the error. -
Django user_id from django db missing in application models.py
A few Days ago I started this tutorial on Django: https://www.youtube.com/watch?v=sm1mokevMWk The video is about how to set up your first django project, using some libraries from django, as well as bootstrap to style your website. He goes on about how to setup the database, website and everything else you need for the example of a todolist website and at the end of the video series he goes over setting up Users, as well as user specific todo lists. I tried recreating the process and up to the point of the user specific todo lists it was all very understandable and easy to follow. Yet as I tried implementing pretty much the last step of the implementation i get the following error: OperationalError at /create/ table main_todolist has no column named user_id Request Method: POST Request URL: http://127.0.0.1:8000/create/ Django Version: 5.0.1 Exception Type: OperationalError Exception Value: table main_todolist has no column named user_id Exception Location: C:\Entwicklung\Python\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: main.views.create Python Executable: C:\Entwicklung\Python\Python312\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\brenneckeo\Desktop\Django Projekt\meineSeite', 'C:\Entwicklung\Python\Python312\python312.zip', 'C:\Entwicklung\Python\Python312\DLLs', 'C:\Entwicklung\Python\Python312\Lib', 'C:\Entwicklung\Python\Python312', 'C:\Entwicklung\Python\Python312\Lib\site-packages'] Server time: Wed, 28 Feb 2024 14:18:52 +0000 The Error pops up when I try to create a ToDoList. When you do … -
smart_text from django-jenkins(sites-packages of my project) doesn't match with django 5.0.1 after upgrade. How to solve this problem?
jenkins test /../python3.11/site-packages/django_jenkins/runner.py", line 9, in <module> from django.utils.encoding import smart_text ImportError: cannot import name 'smart_text' from 'django.utils.encoding' (/../python3.11/site-packages/django/utils/encoding.py) Exit with return error: 1 -
How to run python script in django?
I have a python script which does web scraping and takes the input from the user for product name and then it displays the result. I want this same thing to be done on a webpage. Like user enters the input on webpage and result is displayed on webpage only (currently it is being displayed in python terminal) I tried doing django implementation but not able to do. Can I use streamlit library for this? If yes pls expand it steps how can I connect it to my existing webpage of website. -
Python social media Android application
I want to create a social media application with kivy for front end and django for backend, I never worked with this both together I need a src code or a reference video that how to work with kivy and django I searched many videos, but all are webapps and those who have made apks all are simple apps like task manger -
Heroku errors when upgrading Wagtail CMS
I'm attempting to update a very out-of-date Wagtail-based website that is hosted on Heroku. I'm upgrading from Wagtail 2.13 to 2.14. The upgrade goes fine on my local machine, but when pushing the upgrade to Heroku, and I'm struggling to interpret the errors: remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.8.7 remote: -----> Installing pip 23.3.2, setuptools 68.2.2 and wheel 0.42.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting anyascii==0.1.7 (from -r requirements.txt (line 1)) remote: Downloading anyascii-0.1.7-py3-none-any.whl.metadata (1.6 kB) remote: Collecting asgiref==3.3.1 (from -r requirements.txt (line 2)) remote: Downloading asgiref-3.3.1-py3-none-any.whl.metadata (8.9 kB) remote: Collecting beautifulsoup4==4.8.2 (from -r requirements.txt (line 3)) remote: Downloading beautifulsoup4-4.8.2-py3-none-any.whl (106 kB) remote: Collecting boto3==1.17.15 (from -r requirements.txt (line 4)) remote: Downloading boto3-1.17.15-py2.py3-none-any.whl.metadata (6.0 kB) remote: Collecting botocore==1.20.15 (from -r requirements.txt (line 5)) remote: Downloading botocore-1.20.15-py2.py3-none-any.whl.metadata (5.3 kB) remote: Collecting certifi==2020.12.5 (from -r requirements.txt (line 6)) remote: Downloading certifi-2020.12.5-py2.py3-none-any.whl.metadata (3.0 kB) remote: Collecting chardet==4.0.0 (from -r requirements.txt (line 7)) remote: Downloading chardet-4.0.0-py2.py3-none-any.whl.metadata (3.5 kB) remote: Collecting dj-database-url==0.5.0 (from -r requirements.txt (line 8)) remote: Downloading dj_database_url-0.5.0-py2.py3-none-any.whl (5.5 kB) remote: Collecting dj-static==0.0.6 (from -r requirements.txt (line 9)) remote: Downloading dj-static-0.0.6.tar.gz (3.4 kB) remote: Preparing metadata (setup.py): started remote: … -
Page not found (404). No Category matches the given query
I am building an Ecommerce site thru Django framework. While creating category section which takes user to individual category to access all its items, following error occurs. Page not found (404) No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/search/ring/ Raised by: store.views.category_list Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ [name='all_product'] item/<slug:slug>/ [name='product_detail'] search/<slug:category_slug>/ [name='category_list'] The current path, search/ring/, matched the last one. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. Here is the urls.py file from django.urls import path from . import views app_name = 'store' urlpatterns = [ path('', views.all_product, name='all_product'), path('item/<slug:slug>/', views.product_detail, name='product_detail'), path('search/<slug:category_slug>/', views.category_list, name='category_list'), ] views.py file from django.shortcuts import get_object_or_404, render from .models import Product, Category # Create your views here. def categories(request): return { 'categories': Category.objects.all() } def all_product(request): product = Product.objects.all() return render(request, 'store/home.html', {'product': product}) def category_list(request, category_slug): category = get_object_or_404(Category, slug=category_slug) product = Product.objects.filter(category=category) return render(request, 'store/products/category.html', {'category': category, 'product': product}) def product_detail(request, slug): product = get_object_or_404(Product, slug=slug, in_stock=True) return render(request, 'store/products/detail.html', {'product': product}) models.py file from django.db import models … -
Docker cannot assign requested address in Django
When I request the docker-compose up --build command, docker gives me an error: prediction-1 | django.db.utils.OperationalError: connection is bad: Cannot assign requested address prediction-1 | Is the server running on host "::1" and accepting prediction-1 | TCP/IP connections on port 5432? I downloaded PostgreSql from the official website. My settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASSWORD"), 'HOST': 'localhost', 'PORT': '5432', } } My docker-compose.yml version: '3.8' services: postgres: restart: always image: postgres:latest container_name: postgres-db environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: 5332Dialog POSTGRES_DB: site ports: - "5432:5432" prediction: build: context: ./mysite ports: - "8000:8000" depends_on: - postgres environment: DEBUG: "False" DB_USER: "postgres" DB_PASSWORD: DB_HOST: "postgres" My Dockerfile FROM python:3.10.4 WORKDIR /app COPY . /app/ RUN apt-get update && apt-get install -y python3 && pip install -r requirements.txt CMD ["bash", "-c", "python manage.py migrate && python manage.py loaddata categories.json && python manage.py loaddata things.json && python manage.py runserver 0.0.0.0:8000"] I wanted to learn how to use Docker using your text this video: https://www.youtube.com/watch?v=0uLDObuutFs&ab_channel=ElenaDeykun-PythonBlog but somehow it didn’t work out that way -
Django/Python - Delete function in UpdateView is duplicating rather than deleting
i have created a Django app that allows users to enter their stock trades, as a journaling tool. When a user clicks on an individual journal entry from the index page, they will be taken to a detail page showing all the information on that individual entry (single_entry.html). This page is handled by an UpdateView. From this page, a user can edit/update any info, as well as DELETE that specific entry. To accomplish this, I've imported the DeletionMixin module from django.views.generic.edit. However, when I click on the "Delete" button in the form, the entry is duplicated instead of deleted! Does anyone know why that's happening?? Thanks for your help! Here's my class based view in views.py: class SingleEntryView(UpdateView): template_name = "single_entry.html" model = Entry fields = ['ticker', 'strategy', 'result', 'comments', 'image'] success_url = '/' def post(self, request, *args, **kwargs): if "delete_button" in self.request.POST: return self.delete(request, *args, **kwargs) def update_post(self, form, pk): if "update_button" in self.request.POST: form.instance.user = self.request.user return super(SingleEntryView, self).update_post(form) single_entry.html: {% extends 'base.html' %} {% block title %} Trading Journal - Entry {% endblock title %}Trading Journal {% block content %} <form method="POST" action="/"> {% csrf_token %} {% for field in form %} {{field.label_tag}} {{field}} {% if field.errors … -
Summenote doesn't send data values in nested fields
I'm trying to create nested fields with htmx and summernote: When the user clicks in the button "Adicionar nova alternativa" it returns another section. <button class="button is-info" hx-get="{% url 'create_alternativa' espaco=espaco.title %}" hx-target='#alternativas_criadas' hx-trigger="click" name="alternativa" hx-swap="beforeend" > <span class="icon is-small"> <i class="fa-solid fa-circle-plus" ></i> </span> <p>Adicionar nova alternativa</p></button> the problem is that summernotes dosen't send the text values. <div class="column is-9"> {% render_field form_alternativa.text style="height:291px;" %} </div> views.py if request.method == 'POST': print(request.POST) the print result for the same input as in the image when i try to submit the form: <QueryDict:{'text': ['<p>Test1</p>', '', '']}> The problem doesn't happen when I don't use summernote. When I use just a 'textarea', the form is submitted properly. Thanks! -
Django with Freenom [closed]
I just got started on Django and web development (i love it so far). I have gotten far enough to start considering deployment options. Getting a domain name for free is always a challenge. I have been using Heroku for quite sometime now but they put up some limits to it that has become a blocking stone. So I did a "little" research and found out that i could get a domain name for free on freenom.com that should last for a year. But then i could not figure out a way to connect that domain name to a Django project. How would I host the project files? Is there a better option that I can check out? I wanted to see if i could somehow connect my free domain at freenom.com and a django project i created. -
Making a post request to a Django app on MS Azure from a client that I do not own getting cors error
I have deployed a django app on azure and have been running it for a while. I recently added an endpoint to my app that should get a POST request from the jengahq website. However, I am able to simulate post requests from them to my endpoint and see the responses. Everytime I simulate my POST request, I get an error: Access to fetch at https://notification-webservice.azurewebsites.net/... from origin jengahq site has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource... However, I have enabled cors-origin for this website. It also requires a basic authentication header which I have added appropriately as shown below: CSRF_TRUSTED_ORIGINS = ( ["https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ]) CORS_ALLOWED_ORIGINS = [ "https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ] CORS_ALLOWED_HEADERS = [ 'Accept', 'Accept-Encoding', 'Authorization', ... ] The first website in my cors allowed is where my frontend is served and I am able to run requests well. This does not work for the second website. When I remove my frontend site from my cors allowed list, I get a similar error, but the endpoint seems different: Access to fetch at mysite from origin myfrontend has been blocked by CORS policy... Even with the addition … -
Can't send a labNumber into an sql query
I'm very confused as to why my _labNumber variable isn't getting sent into the method that I am using to call an SQL query, as it works for other methods in the same class. I have a try catch block in my class that calls the methods where I pass in _labNumber(This is correctly assigned, I have triple checked it) try: _comment = self.dataServices.GetComment(_labNumber) _value2 = self.dataServices.GetValue2(_labNumber) _value1 = self.dataServices.GetValue1(_labNumber) _results = self.dataServices.getResults(_labNumber) except AttributeError: _comment = None _value2 = None _value1 = None _results = None This is one of the methods in the class that is being used to retrieve the data from the database: def GetValue2(self, _LabNumber): _LabNumberStr = str(_LabNumber) try: with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", _LabNumberStr) row = _cursor.fetchone() if row: return {'VALUE2': row[0]}#21 else: return {'VALUE2': None} except Exception as e: # Handle or log the exception as appropriate print(f"An error occurred: {e}") return {'VALUE2': None} And finally here is the query that I know works as it returns the data when I hard code a lab number: @LabNumber VARCHAR(10) AS SET NOCOUNT ON SELECT WDR.COMMENT FROM dbo.DNA_WORKSHEET_DET WD INNER JOIN dbo.DNA_WORKSHEET W ON WD.WORKSHEET = W.WORKSHEET LEFT OUTER JOIN dbo.DNA_TEST T ON W.TEST … -
127.0.0.1 slowness in django virtual environment running with vscode
After connecting to the server built in awsec2 with a remote of vscode, the django virtual environment was run to make a connection of 127.0.0.1. But its speed is too slow. When you connect using Chrome, the loading is too slow, sometimes it's infinitely loaded, and sometimes there's content that hasn't been loaded even if it's marked. There are even cases where only white pages are displayed. I'm currently using a MAC. Using a Windows laptop, connecting remotely to a remote server using vcode and then connecting to 127.0.0.1 will work fine I've been looking for other posts, but none of them correspond to my issues. I've tried many things. Turn off the process that currently uses 8000 ports on the Mac (but it was not there) Connect django to 8888 port or unused port and view it (this is the same error as well) It used to work very well, but it doesn't work well at some point. What should I do?