Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
“/workspaces/studydjango/studydjango/api/rota” does not exist
Erro no redirecionamento: api/url.py api/view.py studydjando/url.py Quando acesso a api getMessage funciona normal: enter image description here Porém quando tento acessar a api getRoutes retorna que a pagina não existe: enter image description here alguém sabe o que pode ser? -
Django not recognizing my url, cannot get into the app
i am very new to Django, just trying out with a url to a view structure basically this: newyear: (all those app files + templates) test (all those site files + templates) manage.py on newyear urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] on views.py from django.shortcuts import render import datetime # Create your views here. def index(request): now = datetime.datetime.now() return render(request, 'newyear/index.html', { "newyear": now.month == 1 and now.day == 1 }) on urls.py in test from django.contrib import admin from django.urls import path,include urlpatterns = [ path('newyear/', include('newyear.urls')), path('admin/', admin.site.urls), ] I have rerun the server but still only recognizes /admin, please help thanks on settings in test INSTALLED_APPS = [ 'newyear', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] -
Linking Django and nginx containers when deploying
When I use docker-compose to build the images and run the containers, everything works fine, and I can access my app in the browser over the localhost. I then rename/tag the images and upload them to dockerhub. I have written a second docker-compose.yml that pulls these two images from dockerhub, builds, networks, and runs them. They both appear to load properly, but when I direct my browser to localhost, I only get the 'Welcome to Ngninx - further configuration required' screen. I have used 'docker network inspect' to compare the two networks, and all seems to be the same, bar small ip address changes. CHESS_NN_WEBAPP │ docker-compose.yml │ docker-compose_deploy.yml │ Dockerfile │ requirements.txt │ ├───config │ └───nginx │ └───conf.d │ local.conf │ ├───django_wrapper │ │ db.sqlite3 │ │ manage.py │ │ │ ├───django_wrapper │ │ asgi.py │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ │ └───webapp │ │ admin.py │ │ apps.py │ │ chess_tools.py │ │ urls.py │ │ views.py │ │ │ ├───templates │ index.html │ └───other stuff Dockerfile for django/gunicorn app container: # start from official image FROM python:3.10-slim # arbitrary location choice: you can change the directory RUN mkdir -p /opt/services/djangoapp/src WORKDIR /opt/services/djangoapp/src … -
Django : Static served using nginx couldn't work Error 404
I am using homebrew to start the nginx services. Django project directory : core (app) main_app(app) maps(app) static → css folder, js folder etc templates manage.py Steps : I add the static and media URL and path STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = '/static/' STATIC_ROOT = '/Users/nuntea/Documents/Vasundhara Geo technology/vgt-bitmapper-portal-app/staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = '/Users/nuntea/Documents/Vasundhara Geo technology/vgt-bitmapper-portal-app/media/' I then collect the static nuntea@Zonunmawias-MacBook-Air vgt-bitmapper-portal-app % python3 manage.py collectstatic 184 static files copied to '/Users/nuntea/Documents/Vasundhara Geo technology/vgt-bitmapper-portal-app/staticfiles' I add the following server server { listen 8080; server_name _; location /static/ { alias /Users/nuntea/Documents/Vasundhara\ Geo\ technology/vgt-bitmapper-portal-app/staticfiles/; } location /media/ { alias /Users/nuntea/Documents/Vasundhara\ Geo\ technology/vgt-bitmapper-portal-app/media/; } 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; } } to the config file sudo nano /opt/homebrew/etc/nginx/nginx.conf The nginx.conf file (without comment): worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; server { listen 8080; server_name _; location /static/ { alias /Users/nuntea/Documents/Vasundhara\ Geo\ technology/vgt-bitmapper-portal-app/staticfiles/; } location /media/ { alias /Users/nuntea/Documents/Vasundhara\ Geo\ technology/vgt-bitmapper-portal-app/media/; } 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; } } include servers/*; } Here are some further information : nuntea@Zonunmawias-MacBook-Air vgt-bitmapper-portal-app % nginx -t … -
Django - Field lookups LTE Not Working Correctly?
I’m currently building a gaming app where logged in users have access to play different games based on their rank in our application. If a currently logged in user has a rank of lets say 500 than all the games with a game_rank of 500 and below will be displayed. The rest of the games will be locked. I tested with a user set to a rank of 500 but for some reason certain games below 500 are locked when they should be unlocked. What’s going on with my current code that I’m missing to make this work correctly? In my views I'm using When(game_rank__lte=user_profile_rank, then=Value(True)) which is working but not fully like how I would like. The rank field in the User_Info model is for logged in users rank. The game_rank field in the Game_Info model is for the games. Any help is gladly appreciated. Thanks! models.py class Game_Info(models.Model): id = models.IntegerField(primary_key=True, unique=True, blank=True, editable=False) game_title = models.CharField(max_length=100, null=True) game_rank = models.CharField(max_length=1000, null=True, blank=True) game_image = models.ImageField(default='default.png', upload_to='game_covers', null=True, blank=True) featured_game = models.BooleanField(default=0) class User_Info(models.Model): id = models.IntegerField(primary_key=True, blank=True) image = models.ImageField(default='/profile_pics/default.png', upload_to='profile_pics', null=True, blank=True) user = models.OneToOneField(settings.AUTH_USER_MODEL,blank=True, null=True, on_delete=models.CASCADE) rank = models.CharField(max_length=100, null=True, blank=True, default=1) user_games_enabled = models.ManyToManyField(Game_Info, … -
Need help choosing frameworks for my emailing project [closed]
I hope stack overflow allows me to ask this question. I would like to start a new project to add to my resume. My goal is to have a persistent project out there for recruiters to see and display my work. The project in mind will have users create an account and mention their interests. The site will then send a weekly email to these users based on their interests. I have experience with HTML,CSS,JS. However, I feel like Python would be helpful as I have experience with its web scraping package(s). Suggestions on languages / frameworks I should use? I would like to use some sort of newer framework that doesn't have a steep learning curve. What do you suggest I use to manage the mailing system? I see there are companies out there that do it however I feel if it isn't too hard to do it by myself that would be a great addition to the project to show recruiters. I would like users to create accounts and add some sort of encryption to their usernames/emails and passwords. What sort of database or storage method should I use? I did some research and I have a lot … -
Should you use trailing slashes when describing path in Django's urls.py file?
I have a situation where all ajax calls in JavaScript files end without a slash at the end. Meanwhile all Django files in my project (urls, views) have them. Is it better if they are added or not? I'm in a situation where I need to either modify the js files or change settings to APPEND_SLASH = False and modify python files. -
how to resolve: ENV=dev : The term 'ENV=dev' is not recognized as the name of a cmdlet, function, script file?
I have a Django app and I have two env files: dev and prod. I try to distinguish them in settings.py file like: ENVIRONMENT = os.environ.get("EN") if ENVIRONMENT == "dev": os.getenv("./.env") elif ENVIRONMENT == "production": os.getenv("./.env.prod") else: print("Missing ENV variabel") So in the command prompt I execute the command: SET Env:ENV="dev" ENV=dev python manage.py runserver But then I get this error: ENV=dev : The term 'ENV=dev' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + ENV=dev python manage.py runserver And I am using Windows as OS. How to resolve this error? -
got an error while trying to deploy Django on railway
i get this error while trying to deploy my Django app on railway (https://i.stack.imgur.com/39h8Q.png) please has anyone experienced this before, I am new to Django and i do not know where the error is coming from. please can you help. and also if there is any other server where can host the app aside from Heroku -
Django filtering with Custom primary key
I have two tables and I want to get the "description" field. This is what I have currently. school_number =SchoolNumber.objects.filter(school__in=school_list).values("s_number") description = BuildingNumber.objects.filter(number__in=school_number).values("description") print("description: ",description) And for the BuildingNumber model I am using my custom primary key, not the django default 'id'. However this didn't work. I got the following error: ProgrammingError Exception Value: operator does not exist: character varying = bigint LINE 1: ...._number" WHERE "...."."number" IN (SELECT... I read that this happens when you use a custom primary key. But i need to use this and I coudn't find a way to overcome this error -
This is correct?
I have a model that represents the normal login data and I had a question about whether it would be correct that if I verify that some data is not correct, I can return the form again but with a context that mentions the error and I don't know how to do it. I need ideas class User(models.Model): nombre = models.CharField(max_length=60,unique=True) edad = models.IntegerField() contraseña = models.CharField(max_length=60) gmail = models.EmailField(max_length=60,unique=True) def __str__(self): return self.nombre def save(self, *args, **kwargs): if User.objects.filter(nombre=self.nombre): raise ValueError("Ya existe el usuario") elif self.edad >0 and self.edad <99: super().save(*args, **kwargs) else: Where is the else: is where the template should return again, that would be correct or maybe I should implement it another way -
Django,NOT NULL constraint failed: main_app_staff.course_id
i'm copying a project on github,the code is following: models: class CustomUser(AbstractUser): #some info need to submit class Course(models.Model): name = models.CharField(max_length=120) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Staff(models.Model): course = models.ForeignKey(Course,on_delete=models.DO_NOTHING) admin = models.OneToOneField(CustomUser,on_delete=models.CASCADE) def __str__(self): return self.admin.last_name + " " + self.admin.first_name ''' views.py: ''' if request.method == 'POST': if form.is_valid(): first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') address = form.cleaned_data.get('address') email = form.cleaned_data.get('email') gender = form.cleaned_data.get('gender') password = form.cleaned_data.get('password') course = form.cleaned_data.get('course') passport = request.FILES.get('profile_pic') fs = FileSystemStorage() filename = fs.save(passport.name, passport) passport_url = fs.url(filename) try: user = CustomUser.objects.create_user( email=email,password=password,user_type=2,first_name=first_name,last_name=last_name,profile_pic = passport_url ) user.gender=gender user.address=address user.save() staff = Staff(course = Course.objects.get(name=course),admin = user) staff.save() messages.success(request,"Successfully Added") return redirect(reverse("add_staff")) except Exception as e: messages.error(request, "Could Not Add " + str(e)) else: messages.error(request, "Please fulfil all requirements") return render(request,"hod_template/add_staff_template.html",context) but when i debug it ,it continuing noting me "NOT NULL constraint failed: main_app_staff.course_id", i'm not sure if i need to create a Staff object i dont know how to solve it .... please -
How to switch from .env file and .env.prod file with django?
I have a django app. And I have two .env files: one for local(.env) and one for production(.env.prod). And I have installed the pakcakge: django-dotenv==1.4.2 And I try to distinguish this two files in settings.py file. Like this: from django.utils.encoding import force_str import django from os import environ from pathlib import Path import os import dotenv dotenv.read_dotenv() django.utils.encoding.force_text = force_str # JJ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ ENVIRONMENT = os.environ.get("EN") if ENVIRONMENT == "development": environ.get.Env.read_env("./.env") elif ENVIRONMENT == "production": environ.Env.read_env("./.env.prod") else: print("Missing ENV variabel") But I get this error: Method 'get' has no 'Env' memberPylintE1101:no-member Question: how to use the package django-dotenv to distinguish between .env files? -
Not Found: /socket.io/ with Django and React
I need to establish a socket connection between the frontend React and the backend Django. socketio.js Socket Client in React import { io } from 'socket.io-client'; URL = 'http://127.0.0.1:8000/prices'; export const socket = io.connect(URL, { cors: { origin: 'http://127.0.0.1:8000', credentials: true, } }); socketio.py Socket Server in Django from threading import Thread import socketio sio = socketio.AsyncServer(async_mode='asgi', logger=True, engineio_logger=True, cors_allowed_origins='*') thread = Thread() URL = '' //Empty for now def getPrices(): print("Fetching Data") while True: data = requests.get(URL) data = data.json() data = data['stockList'] socketio.emit('stocks', {'data': data}, namespace='/prices') socketio.sleep(60) @sio.on('connect', namespace='/prices') def connect(): global thread print('Client connected') if not thread.is_alive(): print("Starting Thread") thread = socketio.start_background_task(getPrices) @sio.on('disconnect', namespace='/prices') def disconnect(): print('Client disconnected') asgi.py server import os from django.core.asgi import get_asgi_application import socketio from main.socketio import sio os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') application = get_asgi_application() SocketApplication = socketio.ASGIApp(sio, application) I have used Uvicorn as the ASGI web server and I have added the Uvicorn in the INSTALLED_APPS in settings.py and I have also added ASGI_APPLICATION = 'myproject.asgi.application' -
Average of top 5 value in a model
I've got a django model with a lot of fields. I'm trying in a single query to get the avg value of a given field and the average value of the top 5 values of that same field (from my other question regarding pure SQL: Average of top 5 value in a table for a given group by). Not that it should matters but: my database is redshift. I've found two different ways to achieve this in SQL, but I'm having trouble implementing those queries using django ORM Here is an example of what I want to do using Cars: class Cars(models.Model): manufacturer = models.CharField() model = models.CharField() price = models.FloatField() Data: manufacturer | model | price Citroen C1 1 Citroen C2 2 Citroen C3 3 Citroen C4 4 Citroen C5 5 Citroen C6 6 Ford F1 7 Ford F2 8 Ford F3 9 Ford F4 10 Ford F5 11 Ford F6 12 Ford F6 19 GenMotor G1 20 GenMotor G3 25 GenMotor G4 22 Expected Output: manufacturer | average_price | average_top_5_price Citroen 3.5 4.0 Ford 10.85 12.2 GenMotor 22.33 22.33 Here are two pure SQL queries achieving the desired effect: SELECT main.manufacturer, AVG(main.price) AS average_price, AVG(CASE WHEN rank <= … -
Switching from local to prod in .env file doensn't work
I have a django app. And I am using the .env file for the environment settings. But what I notice is that if I switch from local environment settings to production environment settings and vice versa and restart the django service. Nothing changes. So I have my local settings in the .env file. And the .env file is in the same directory as the settings.py file: DEBUG=1 SECRET_KEY="django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u" DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] DB_NAME="dierenwelzijn" DB_USER="dierenwelzijn" DB_PASS="8Bit235711" DB_HOST=localhost DB_PORT=5432 and in settings.py file I have this: from django.utils.encoding import force_str import django from os import environ from pathlib import Path import os import dotenv dotenv.read_dotenv() django.utils.encoding.force_text = force_str BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = bool(int(os.environ.get('DEBUG', 1))) ALLOWED_HOSTS = ['localhost', '0.0.0.0', '192.168.1.135', '10.0.2.2', '10.14.194.138', '0.0.0.0', "127.0.0.1", 'zijn.azurewebsites.net', 'zijndocker.azurewebsites.net', 'https://dierenwelzijndocker.azurewebsites.net'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) CSRF_TRUSTED_ORIGINS = [ "https://dockerzijn.azurewebsites.net", "https://zijndocker.azurewebsites.net", "http://0.0.0.0:8000", "http://10.0.2.2:8000", "http://localhost:8000", "http://10.14.194.138:8000", "http://127.0.0.1:8000/"] and I restart the django app with: python manage.py runserver It is still using the production environment variables. Because if I go to: http://127.0.0.1:8000/ Not Found The requested resource was not found on this server. And it also uses the production database. And not the local database. So is there some kind of ommand that … -
Multi database in django
I am implementing multi database in django and i want to route the use to a specific database bases on the country in the user's request header call 'X-Country'. Here is my custom middleware class CountryMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): country = request.headers.get('X-Country', None) request.country = country print("Country Middleware - Country:", country) return self.get_response(request) And my custom router from django.conf import Settings class CountryBasedRouter: def __init__(self): self.country_database_mapping = { 'databaseng': ['NG', 'GH'], 'databaseothers': ['US'], } def db_for_read(self, model, **hints): print("urequestrequestrequestrequestdua", hints.get('request')) return self.get_database_for_country(**hints) def db_for_write(self, model, **hints): return self.get_database_for_country(**hints) def allow_relation(self, obj1, obj2, **hints): return getattr(obj1, 'country', None) == getattr(obj2, 'country', None) def get_database_for_country(self, **hints): request = hints.get('request', None) if not request or not hasattr(request, 'country'): raise ValueError("Country information not found in the request.") # Prioritize 'X-Country' header over the 'country' attribute in case both are present country = request.headers.get('X-Country', request.country) for db, countries in self.country_database_mapping.items(): if country in countries: return db raise ValueError(f"No matching database found for country: {country}") And some excerpt in my settings.py DATABASE_ROUTERS = ['routers.db_router.CountryBasedRouter'] DATABASES = { 'default': {}, 'databaseng': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'host', 'PORT': 5432, }, 'databaseothers': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'name', … -
Django Forms and Formset edit
I am trying to create a edit fbv but my edit is not saving up. views.py def editplayform(request,id): play = Play.objects.get(id=id) if request.method =='POST': form = forms.PlayForm(request.POST, instance=play) time_shown_formset = forms.TimeShownFormSet(request.POST, instance=play) if form.is_valid() and time_shown_formset.is_valid(): form.save() time_shown_formset.save() return redirect("play:home") else: form = forms.PlayForm(instance=play) time_shown_formset = forms.TimeShownFormSet(instance=play) return render(request, 'play/fbvplayform.html', context={'form':form, "time_shown_formset":time_shown_formset, 'play':play}) edit.html <form method="POST"> {% csrf_token %} <h1>Edit PLAY</h1> <div>{{ form.non_form_errors }} {{ form.as_p }}</div> <h1>Edit Timeshown</h1> <!-- prettier-ignore --> {{ time_shown_formset.non_form_errors }} {{ time_shown_formset.management_form}} {% for form in time_shown_formset %} <div>{{ form.times.label }}: {{ form.times }}</div> {% if time_shown_formset.can_delete %} <div>{{ form.DELETE }} {{ form.DELETE.label }}</div> {% endif %} {% endfor %} <div> <button type="submit">Update Play</button> </div> </form> It is returning POST response on the terminal but the edit is not saving and its not returning to home.html. What am i doing wrong please? -
Is there a way to specify library types and versions on GitHub other than using requirement.txt?
I've been exploring different approaches to specify library types and versions on GitHub for my solo project using Django and React. In my research, I've predominantly come across the use of requirement.txt files for managing project libraries. I've tried reviewing documentation and online discussions, but I'm curious to hear from the community about their experiences. Specifically, I'm interested in knowing if using requirement.txt is a widely adopted practice in the industry for managing project dependencies. Additionally, I'm open to learning about alternative methods that developers might find effective. What approaches have you tried for specifying library types and versions in your GitHub projects, and what were your expectations regarding the ease of maintenance and collaboration? Thank you for sharing your insights! -
Django Rest + Vuejs axion CSRF not working
I try using Django Rest Framework together with VueJS and axion. But always I get the MSG: CSRF Failed: CSRF token missing. But my Header in the frontend looks correct. And in the developer tools the cockie is correct loading into the header. {"Accept": "application/json, text/plain, /","Content-Type": "application/json","X-CSRFToken": "*******"} my csrf settings in django settings.py CSRF_COOKIE_NAME = "csrftoken" CSRF_HEADER_NAME = 'X-CSRFTOKEN' CSRF_TRUSTED_ORIGIN = ['http://.127.0.0.1', 'http://.localhost'] CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_SECURE= False I have no problems with the get requests. Only than it come to POST, PUT, DELETE. Thank you for your advice. With regards Philipp Homberger I try: CSRF_TRUSTED_ORIGIN = ['http://*.127.0.0.1', 'http://localhost'] as well. My Dev deployment build with 3 docker images. 1 Nginx as reversproxy to get both on the same port. 1 Container with Bakcend (Django) 1 Container with VueJs Frontend. What were you expecting? I expecting that I can do Post Requests as well without disable CSRF. Than I use the swagger frontend of my restapi all work fine as well. -
User can chose from a great amount of configurations/templates, need a way to handle without creating Django views/forms for every single one
Currently i am working on a project in Django which will let the user generate a router/switch configuration based on what type of service/router brand/router model he chooses. View: config list (List of registered configurations to generate) User -> Service_1 for router X model Y Then i would need to present the user with a page which will take the inputs needed to generate such configs View: generate config (Form that will ask the user for inputs needed to create X config file) Ex.: IP Address / Subnet Mask / is DHCP needed / routes needed This input will then be passed to variables which will be used to populate a jinja2 template file for said service/router model/router brand in a function Assume the structure is: -Router Brand X --Model Y ---Service1.j2 ---Service2.j2 ---Service3.j2 --Model Z ---Service1.j2 ---Service2.j2 ---Service3.j2 -Router Brand Y --Model Y ---Service1.j2 ---Service2.j2 ---Service3.j2 --Model Z ---Service1.j2 ---Service2.j2 ---Service3.j2 I have a big part of the project already done, right now i can save the config templates to my database, show said templates for the user to choose from and i gave it a try to create a page to generate the config. The issue i have … -
DJANGO websocket 404 not Found with wss
I am trying to connect my web socket with wss over https protocol. But getting 404 in logs saying not found. But it works fine in development over http://localhost in settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [ ("redis-container", 6379) ], }, }, } I am using Redis for the host and my asgi.py import os from django import setup from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from NotificationApp.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.settings") setup() application = ProtocolTypeRouter( { "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( URLRouter( websocket_urlpatterns, ) ), } ) and my ***routes.py*** file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/notify/", consumers.NotificationConsumer.as_asgi()), ] on frontend const createWebSocket = () => { const socket = new WebSocket( `wss://localhost:8000/ws/notify/` ); socket.onopen = function (e) { console.log("Socket successfully connected."); }; socket.onclose = function (e) { console.log(e); console.log("Socket closed unexpectedly"); // Try to reconnect every 5 seconds // setTimeout(createWebSocket, 5000); }; socket.onmessage = function (e) { const data = JSON.parse(e.data); document.getElementById("bellIcon").className = "shakeIt"; const wait = async () => { await sleep(2000); document.getElementById("bellIcon").className = ""; }; wait(); setNotifications((prevNotifications) => [data, ...prevNotifications]); setUnreadNotifications((prevCount) => prevCount + 1); }; return socket; }; const … -
Arcpy not supporting in djnago in all machine but some machine it supporting
I have a Django application running in a virtual Conda environment generated from ArcPro. I need to use the arcpy library in this Django application, which is why I used the virtual environment. However, the class I used with arcpy is working on some machines but not on others. I used the subprocess method, and it worked at that time since arcpy is running outside of Django with that method. Why is arcpy not compatible with Django? -
Can anyone help? I'm following a tutorial to make a basic blog site using Django and PostgreSQL and I can't add a database
I've added a 'templates' folder into the blog directory but I can't get the Django database urls to recognise it. I think I need to add my url into the settings.py file but I have no idea how I'm supposed to do that. When I try to run the server I get this error: Traceback (most recent call last): File "/workspace/django-blog/manage.py", line 22, in <module> main() File "/workspace/django-blog/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/core/management/__init__.py", line 363, in execute settings.INSTALLED_APPS File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/gitpod/.pyenv/versions/3.12.1/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 994, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/workspace/django-blog/codestar/settings.py", line 91, in <module> 'default': dj_database_url.parse(os.environ.get("DATABASE_URL")) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/workspace/.pyenv_mirror/user/current/lib/python3.12/site-packages/dj_database_url/__init__.py", line 126, in parse raise ValueError( ValueError: No support for 'b'''. We support: cockroach, mssql, mssqlms, mysql, mysql-connector, mysql2, mysqlgis, oracle, oraclegis, … -
Django runserver Problems
Everytime I start the python manage.py runserver command I get this Error: python manage.py runserver ModuleNotFoundError: No module named '<your_project_name>' I created the virtual Enviroment, installed djangoo and sucefully created a project but after that I cant start the server somehow.