Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django unexpected amount of queries executed
given models.py: from django.db import models class Menu(models.Model): name = models.CharField(max_length=255) menu_url = models.CharField(max_length=255) def __str__(self): return self.name class MenuEntry(models.Model): menu = models.ForeignKey("menu", null=True, blank=True, on_delete=models.CASCADE) parent = models.ForeignKey("menuentry", null=True, blank=True, on_delete=models.CASCADE) text = models.CharField(max_length=255) def __str__(self): return self.text when execuring in another file draw_menu.py the following: from django import template from menu.models import MenuEntry from django.db import connection register = template.Library() @register.simple_tag def draw_menu_tag(menu_name): queryset = MenuEntry.objects.raw("WITH RECURSIVE \ my_menu_items \ AS( \ SELECT * FROM menu_menuentry WHERE menu_menuentry.menu_id=(SELECT id FROM \ menu_menu WHERE name=%s) \ UNION \ SELECT m.* FROM menu_menuentry m \ INNER JOIN my_menu_items r ON m.parent_id = r.id \ WHERE m.parent_id IS NOT NULL \ ) \ SELECT * FROM my_menu_items mmi INNER JOIN menu_menu mm ON mm.id = mmi.menu_id", ["menu_B"]) q = list(queryset) resulting_html = str(queryset_to_dict(q)) breakpoint() return 'resulting_html' def queryset_to_dict(queryset): out_dict = {} out_dict['menu'] = queryset[0].menu.name out_dict['menu_url'] = queryset[0].menu.menu_url num_queries = len(connection.queries) print(f"Number of queries executed: {num_queries}") return out_dict when loading the page with the tag, I get "Number of queries executed: 2". This following gives an extra query out_dict['menu'] = queryset[0].menu.name But I have joined the corresponding menu items. It should be retrieved without any extra queries. Please help, thanks a lot! -
Django: View uploaded docs/pdf files
I'm trying to fetch a file that I uploaded. But when I click the file, it returned the page where I'm in. Or if I try to download the file, it shows the html file of the page. My code is the same in uploading images, but I have no problem viewing the image. I did the same thing in uploading a file, but it didn't show the file. Here is my code: models.py class File(models.Model): id = models.AutoField(db_column='id', primary_key=True) soano = models.CharField(db_column='SoaNo', max_length=20) studentid = models.ForeignKey('Student', on_delete=models.CASCADE, db_column='studentid') file = models.FileField(db_column='file', upload_to='soa/', verbose_name="") class Meta: managed = True db_table = 'soa' views.py def file_upload(request): if request.method == 'GET': student = Student.objects.all() return render(request, 'admin/file_upload.html', {'student': student}) if request.method == 'POST': upload = Soa() randomid = ''.join(random.choices(string.digits, k=5)) upload.soano = f"{randomid}" studentid = request.POST.get('studentid') upload.studentid_id = studentid if len(request.FILES) != 0: upload.file = request.FILES['file'] upload.save() return redirect('/students/file/') file.html {% for obj in query %} <tr> <td>{{ obj.fileno }}</span></td> <td>{{ obj.student.lrn }}</span></td> <td><a href="{{ obj.file.url }}" download="{{ obj.file.url }}">{{ obj.file }}</a></td> </tr> {% endfor %} I checked the directory and the file I uploaded was there. But I just can't view it with {{ obj.file.url }}. I don't know what am … -
How to set tailwind-css or bootstrp and js file in django for offline work?
In django, is there any way to link-up bootstrap css and js file to work in offline? I find solution for link-up tailwind-css with my django project also. I create a static folder globally. I keep these files in static folder. Then I try to link-up these files by using and tags from base.html file which is located in templates folder. I also set dirs = ['templates'] in my settings.py file. But they don't work. -
Mai apna fam pay account delete krna chahta hu
Mera old number off hone wala hai isliye mai apna number change krna chahta hu Mera account delete ho jaye Please aap kaise bhi krke mere account ka number change kr deejiye nhi toh account delete kr deejiye please Mere new mobile no hai 7068527369 -
Plotting a bar graph in expense tracker app
I want a bar graph of date as x-axis and amount as y-axis. The date is as date list that can have duplicate values but is guarranted to have same len as that of amount list. for eg-date=[2014-1-4,2014-1-4,2014-1-4,2014-1-5] and amount is [100,5000,1000,2000]. The bar graph that I have created is showing duplicate dates as one and other dates as one. Can anyone have a solution? -
How to filter images by collection in Wagtail API v2
I have a Page type with a foreign key to Collections: class PageWithManyPhotos(Page): collection = models.ForeignKey("wagtailcore.Collection", ...) I would like to retrieve all images of the collection selected for a page via the API. Ideally from the pages endpoint, but from the images endpoint would do too (it'd need an extra request, first to get the collection id and then to filter images by collection) 1st approach When I add an APIField to my Page model: api_fields = [APIField("collection", serializer=CollectionSerializer())] class CollectionSerializer(ModelSerializer): images = ImageSerializer(read_only=True, many=True) class Meta: model = Collection # fields = ["id", "name", "images"] exclude = [] and make a request at /api/v2/pages/?type=base.GalleryPage&fields=collection, I get a reply but without the images: "collection": { "id": 8, "path": "000100050003", "depth": 3, "numchild": 0, "name": "Collection 1" } I cannot get the reverse relationship. Perhaps because Collection is an MP_Node and not a models.Model? 2nd approach I also tried the second aproach, to add a custom viewset in the /api/v2/images/?collection=<collection_id> endpoint and filter images by collection in the images endpoint. The collection field is not in the default fields . I tried to add it doing something like: class CollectionField(Field): def get_attribute(self, instance): return instance def to_representation(self, image): return image.collection_id … -
Update Increment If Value is Equal Django
I'm trying to create a versioning system in django. I want separate versioning per asset name. I've been able to setup a custom increment tool but I can't quite work out how to check what I'm currently trying to create against what's already there. This is the code I currently have: def next_version(): latest = Asset.objects.order_by("version").last() if not latest: return 1 return latest.version + 1 class Asset(models.Model): path = models.CharField(max_length=255, unique=True, primary_key=True) name = models.CharField(max_length=255) version = models.IntegerField(default=next_version) asset_type = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.CharField(max_length=255) dependencies = models.JSONField(null=True) def __str__(self): return self.name But the problem I'm having is that the next_version function can't read the name of the asset I'm currently trying to create (or at least I think it can't). So the goal I'm trying to achieve is for the created asset to check the name it's trying to set and if it already exists to bump up the version. Can anyone tell if this is possible? Thanks, Mitchell -
i created a template file but it dosen't work.what can i do?
I created a template file but when go to that file and create a .html file, my file shows a dj icon by the file name and html snippet does not work in that file. it's picture of my app and my template in vscodeWhat can i do? I created a template file but it does not work. What can i do? -
pytest-django test collection behavior is inconsistent
I have a Django project that is set up with pytest-django and everything seemed to be running just fine. However, I recently added tests to a test file and noticed that they weren't being picked up by the pytest command. Here are a few of the things I've tried: Adding @pytest.mark.django_db to the new tests causes them to be correctly collected, but this decorator should only be used when database access is needed, and these tests don't need database access. Moving the unmarked tests so they come after the marked test in the same file causes the 3 unmarked tests to be picked up by the test runner, but now the marked test fails to be collected. Running pytest on that specific file causes all tests to be collected (and pass) with or without the decorators on the tests that don't need them. I've been unable to identify anything wrong with my pytest configuration, though I did note that we're also using the Coverage tool with it to measure code coverage of the tests. The pytest.ini file is very simple: [pytest] env_files = .env addopts = --cov . --cov-report html --cov-report xml --cov-config "coverage/.coveragerc" --disable-warnings DJANGO_SETTINGS_MODULE = config.settings.test I've also … -
raw postgresql query in django
Please help me with raw postgresql query: given models.py: from django.db import models class Menu(models.Model): name = models.CharField(max_length=255) menu_url = models.CharField(max_length=255) def __str__(self): return self.name class MenuEntry(models.Model): menu = models.ForeignKey("menu", null=True, blank=True, on_delete=models.CASCADE) parent = models.ForeignKey("menuentry", null=True, blank=True, on_delete=models.CASCADE) text = models.CharField(max_length=255) def __str__(self): return self.text I am trying to retrieve a menu item with related tree of menuentries, in another file: queryset = MenuEntry.objects.raw("WITH RECURSIVE \ my_2ndmenu_items (id, parent, text) \ AS( \ SELECT * FROM menu_menuentry WHERE menu_menuentry.menu_id=(SELECT id FROM menu_menu WHERE name=%s) \ UNION \ SELECT m.* FROM menu_menuentry m \ INNER JOIN my_2ndmenu_items r ON m.parent_id = r.id \ WHERE m.parent_id IS NOT NULL \ ) \ SELECT * FROM my_2ndmenu_items", ["menu_B"]) But I'm getting the following error, trying to get queryset[0]: *** ValueError: Cannot assign "'menu_B_1lvl_entry'": "MenuEntry.parent" must be a "MenuEntry" instance. Thanks a lot for your help! -
“/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 <= …