Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJANGO: ValueError: too many values to unpack (expected 2) when executing makemigrations
I'm getting the error bellow when trying to execute makemigrations on my django app: ERROR Traceback (most recent call last): File "D:\GitHub\Laurant-Bookstore-2\manage.py", line 22, in <module> main() File "D:\GitHub\Laurant-Bookstore-2\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\GitHub\Laurant-Bookstore-2\app\livraria\models.py", line 40, in <module> class Carrinho(models.Model): File "D:\GitHub\Laurant-Bookstore-2\app\livraria\models.py", line 44, in Carrinho name, path, args, kwargs = super().deconstruct() ^^^^^^^^^^^^^^^^^^^^^ File "D:\GitHub\Laurant-Bookstore-2\venv\Lib\site-packages\django\db\models\fields\related.py", line 679, in deconstruct app_label, model_name = self.remote_field.model.split(".") ^^^^^^^^^^^^^^^^^^^^^ ValueError: too many values to unpack (expected 2) MODELS.PY from django.db import models from django.contrib.auth.models import User class GeneroLiterario(models.Model): nome = models.CharField(max_length=20) def __str__(self) -> str: return self.nome class Autor(models.Model): nome = models.CharField(max_length=30, blank=False, null=False) foto = models.ImageField(upload_to="autores/%d-%b") biografia = models.TextField(max_length=2000, blank=False, … -
How can I display byte encoded PDF in HTML?
My goal is to download a file from a file-sharing application (Egnyte) and render it in my own HTML. I'm working in Django. I'm getting a 200 response from the storage service: response.headers: {'Content-Type': 'application/pdf;charset=UTF-8',...etc} response.content: first 100 char. Type <Class Bytes>. b'%PDF-1.6\r%\xe2\xe3\xcf\xd3\r\n12090 0 obj\r<</Filter/FlateDecode/First 2063/Length 4726/N 197/Type/ObjStm>>stream\r\n' However, when I pass the response.content to the template.html as the source for an embed, the page is blank. What am I missing? I've tried using different html containers. I don't get any errors but in all cases the element is just blank. <iframe src="b'%PDF-1.6\r%\xe2\xe3\...etc'"> -
Spotipy token doesnt change with each new authorisation
I have been trying to fix this all day. Basically after setting this authentication flow up i logged in with my spotify account that is also my dashboard account (idk if that makes any difference). Everything worked how i wanted and i could display my top songs and artists. However when i change the spotify user/log into a different spotify account, the infromation doesnt update. Instead it keeps displaying infromation from the first spotify login. Every time the authorisation happens the token seems to remain the same, even though it shouldnt? (I think). sp_oauth = spotipy.oauth2.SpotifyOAuth( client_id='client_id', client_secret='client_secret', redirect_uri='http://localhost:8000/accounts/spotifyStats/callback/', scope=['user-read-email','user-read-private','user-top-read'], show_dialog=True) def spotify_authorize(request): if request.user.is_authenticated: # Create a new SpotifyOAuth object auth_url = sp_oauth.get_authorize_url() return redirect(auth_url) else: return redirect('accounts:signin') def spotify_callback(request): code = request.GET.get('code') token_info = sp_oauth.get_access_token(code) print(token_info['access_token']) request.session['access_token'] = token_info['access_token'] return redirect('accounts:spotifyStats') def spotify_stats(request): access_token = request.session.get('access_token') if not access_token: return redirect('accounts:spotify_authorize') sp = spotipy.Spotify(auth=access_token) userartists = sp.current_user_top_artists(time_range='long_term') usertracks = sp.current_user_top_tracks(time_range='long_term') return render(request, 'spotify_stats.html', {'artists': userartists, 'tracks': usertracks}) I want to display information related to every account that logsin/authorises into my website and im not sure how to do it. -
404 when I use traefik and nginx with django
I try to deploy a django-webapp on an ec2-instance. The project was generated with cookiecutter-django. However i want to host my personal website on the same instance, so I changed the corresponding compose-files traefik-compose services: traefik: image: traefik:latest restart: unless-stopped command: # Experimentell, um das Dashboard ohne Zugriffsschutz aufzurufen #- "--api.insecure=true" - "--providers.docker" - "--providers.docker.exposedByDefault=false" - "--providers.docker.network=traefik_web" - "--entrypoints.http.address=:80" - "--entrypoints.http.http.redirections.entrypoint.to=https" - "--entrypoints.http.http.redirections.entrypoint.scheme=https" - "--entrypoints.https.address=:443" # Vermeidet, dass wir den resolver in jedem container mit "traefik.http.routers.https.tls.certresolver=le" angeben muessen - "--entrypoints.https.http.tls.certResolver=le" - "--certificatesresolvers.le.acme.tlschallenge=true" - "--certificatesresolvers.le.acme.email=myemail@gmail.com" - "--certificatesresolvers.le.acme.storage=/letsencrypt/acme.json" ports: - "80:80" - "443:443" - "8080:8080" volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - ./letsencrypt:/letsencrypt networks: - public networks: public: name: public personal website compose works just fine services: nginx: image: nginx:latest restart: unless-stopped container_name: "personal_website" volumes: - ./src:/usr/share/nginx/html labels: - "traefik.enable=true" - "traefik.http.routers.nginx.rule=Host(`domain.net`)" networks: - public networks: public: external: true the django compose version: '3' networks: public: external: true db: volumes: production_postgres_data: {} production_postgres_data_backups: {} production_traefik: {} services: django: &django build: context: . dockerfile: ./compose/production/django/Dockerfile image: sommelier_production_django depends_on: - postgres - redis env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres command: /start networks: - public - db labels: - "traefik.enable=true" - "traefik.http.routers.sommelier.rule=Host('sub.domain.net')" - "traefik.http.services.sommelier.loadbalancer.server.port=5000" - "traefik.http.routers.sommelier.entrypoints=websecure" - "traefik.http.routers.sommelier.tls.certresolver=myresolver" - "traefik.docker.network=public" - "traefik.http.middleware.sommelier.headers.hostproxyheaders=X-CRSFToken" redis: image: redis:6 networks: - db postgres: … -
Timestamp updating value over every item in a list rather than each one individually
New to Django here, I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) And two functions that add data from one list to another: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And to organize/display that data I am using this function: def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 playinglist = Playinglist.objects.get(id=item.game_id) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: … -
django chained manytomany field filter
class Question(models.Model): subject = models.ForeignKey(Subject, on_delete=models.PROTECT) topic = ChainedForeignKey(Topic, on_delete=models.PROTECT) question = models.TextField(max_length=700, null=False) option_A = models.CharField(max_length=150) option_B = models.CharField(max_length=150) option_C = models.CharField(max_length=150) option_D = models.CharField(max_length=150) correct_option = models.CharField(max_length=150) explaination = models.TextField(max_length=500, null=True ,blank=True) def save(self, *args, **kwargs): # Ensure only one correct option is selected correct_options = [o for o in [self.option_A, self.option_B, self.option_C, self.option_D] if o == self.correct_option] if len(correct_options) != 1: raise ValueError('Exactly one option must be selected as correct') super().save(*args, **kwargs) def __str__(self): return "%s %s %s" % (self.question[:100], self.topic, self.subject) class Quiz(models.Model): name = models.CharField(max_length=255) description = models.TextField(max_length=500, blank=True) subject = models.ManyToManyField(Subject, null=True, blank=True) topics = models.ManyToManyField(Topic, null=True,) questions = models.ManyToManyField(Question) def save(self, *args, **kwargs): super().save(*args, **kwargs) self.questions.set(Question.objects.filter(topics__in=self.topics.all())) def __str__(self): return self.name i want to create view to generate quiz. when user select subjects(2-3)then only related topic (to subject) should appear in topic list. after selectin topic (3-4) only question related to selected topic should appear. if its possible in django-admin that would be more continent -
Django Model - Auto Referencing
class BusinessUnit(models.Model): class Meta: db_table = 'carecode_business_unit' parent_business_unit = models.ForeignKey(BusinessUnit) "BusinessUnit" is not defined. Is it possible to create an auto-referencing model in Django? -
Celery, ModuleNotFoundError
After command 'celery -A store worker -l INFO' (store is a name of project), i`ve error ModuleNotFoundError: No module named 'proj.settings' -----------------------------------------------------------------------------------------------------------. -
How to use a field in django template from a object of foreignkey model
models.py class Position(models.Model): positions = models.CharField(max_length = 200) pub_date = models.DateTimeField('date published') def __str__(self): return self.positions class Candidate(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField('User Email') mobile_no = models.CharField(max_length=10) candidate_image = models.ImageField(null=False, blank=False, upload_to="candidate_images/") description = models.TextField(null=True, blank=True) votes = models.IntegerField(default = 0) positionc = models.ForeignKey(Position, on_delete = models.CASCADE, related_name ='candidateobj') def __str__(self): return self.first_name views.py def candidate_list(request): candidate_list = Candidate.objects.get(pk=1) return render(request, 'candidate_list.html', { "candidate_list": candidate_list, }) candidate_list.html <div class="card-header"> {{ candidate_list.position.positions }} </div> Here I should get to see the position from the 'Position' model. But nothing is rendering for the above code. Other information are showing properly in candidate_list.html. I checked google and found article also . The Stackoverflow solution is the exact issue I believe and I did the similar in my code but didn't get anything in the html page. I'm new in django. -
CSS Background Image not displaying within Django framework
Following the Polls Webapp tutorial in Django. Keep receiving a 404 error through my command line and my image icon is displayed, but not the image itself. Tried changing the path a couple times, resetting the static migration, and changing my static root. Still no image. Here is my style.css li a { color: green; } body { background-image: url('static/images/background.png') no-repeat; } Here is my index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a> </li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} {% load static %} <link rel="stylesheet" href="{% static 'polls/style.css' %}"> <img src="{% static 'static/images/background.png' %}" alt="My Image"> Here is some of my settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Anyone have an idea? -
Heroku deployment not picking up latest commits when building Django app (e.g. recent changes to settings.py )
I'm using git trying to deploy to a staging pipeline on Heroku. My build is failing. Based on the traceback (two of them, below), I have a general sense as to why. It involves my dynamic SECRET_KEY configuration variable in settings.py. The traceback refers to a python-decouple module installed previously. So I commented out the import line to that package in settings.py, removed the package from my requirements.txt, and used this instead: from dotenv import load_dotenv load_dotenv() ... SECRET_KEY = str(os.getenv('SECRET_KEY')) That's the latest version. When I save my changes, commit them, and then push to the staging pipeline, the traceback being returned refers to line 27 as if is still like this: from decouple import config ... SECRET_KEY = config('SECRET_KEY') I’m not sure why Heroku is not picking up the latest and most recent changes. Any ideas? Here is my full build traceback: $ git push staging main Enumerating objects: 4016, done. Counting objects: 100% (4016/4016), done. Delta compression using up to 20 threads Compressing objects: 100% (3932/3932), done. Writing objects: 100% (3965/3965), 6.41 MiB | 3.71 MiB/s, done. Total 3965 (delta 302), reused 0 (delta 0), pack-reused 0 remote: Resolving deltas: 100% (302/302), completed with 15 local objects. … -
Conversation handler not advancing to next state on Heroku correctly
I've developed a webhook-type Telegram bot that is integrated into a Django application using the python-telegram-bot(v13.15) library. Locally, the conversation handler works correctly, but after deploying the application to Heroku, it sometimes fails to advance to the next state in the conversation. Instead, it treats incoming messages as if they are part of the echo handler, and only advances to the next state after the user sends the message again. I've checked that everything is set up correctly on Heroku and there are no delays between messages, so I'm not sure what could be causing the problem. This is what working with the bot looks like using the Heroku version: Example of conversation handler using Heroku This is what working with the bot using the local version looks like: Example of conversation handler locally Here's the relevant code: import json from django.http import HttpResponse, HttpResponseBadRequest from django.views.decorators.csrf import csrf_exempt from telegram_bot.buttons import * from telegram_bot.handlers.cart_handler import * from telegram_bot.handlers.checkout_handler import * from telegram_bot.handlers.delivery_handler import * from telegram_bot.handlers.order_handler import * from telegram_bot.handlers.payment_handler import * from telegram_bot.handlers.product_handler import * from telegram_bot.utils import * @debug_requests def start_handler(update: Update, context: CallbackContext): context.bot.send_message( chat_id=update.effective_chat.id, text="Hello! I'm a bot. What can I do for you?", reply_markup=get_base_reply_keyboard() … -
VISIT LINK is not working in Django Framework and Cannot see the homepage
I have a project presentation on Monday, and the project topic is SPORTS CLUB MANAGEMENT which is based on Django REST API Framework. And I have a basic understanding of Django. My Problems: When I visited http://127.0.0.1:8000/, I couldn't find the admin_home or homepage of the main website. I tried to read this doc and did plenty of changes but can't get it to work :( Here's the problem demo: Some Errors I got while doing this: Traceback Error: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.1.7 Python Version: 3.10.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'scmapp'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\win10\PycharmProjects\sportsClubManagement-django\templates\admin_login.html, error at line 39 'scmapp' is not a registered namespace 29 : 30 : <div class="container-fluid"> 31 : <div class="row justify-content-center"> 32 : <div class="col-lg-6 loginBox"> 33 : Login<br> 34 : <span style="font-size:18px;">{{ status }}</span> 35 : 36 : <div class="row justify-content-center"> 37 : <div class="col-lg-6"> 38 : <div class="inputBox" style="font-size:18px;"> 39 : <form action=" {% url 'scmapp:login_admin' %} " method="post"> 40 : {% csrf_token %} 41 : Username<br> 42 : <input type="text" name="name" autocomplete="off" required> 43 : 44 : Password<br> 45 : <input type="password" … -
razorpay and environ is not importing
I installed all of these but not importing, can you tell me why? I'm using python versin Python 3.9.5... django-environ 0.10.0 django-razorpay 1.1.6 razorpay 1.3.0 whenever I go to omport I get an error like, "environ" is not accessedPylance Import "environ" could not be resolvedPylance and, "razorpay" is not accessedPylance Import "razorpay" could not be resolvedPylancereportMissingImports import environ import razorpay can you please tell me where It occuring? Somewhere I got razorpay is not suitable for python version 3.9, is it true? Can you please guide me on how to integrate Razorpay payment with Django rest framework? -
Timestamp updating value over every item in a list rather than each one
I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) And two functions that add data from one list to another: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And to organize/display that data I am using this function: def profile(request): playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = 0 present_in_playinglist = False if playinglist: for item in playinglist: try: game = Game.objects.get(id=item.game_id) playinglist_items.append(game) present_in_playinglist = True playing += 1 playinglist = Playinglist.objects.get(id=item.game_id) except: present_in_playinglist = False playedlist = Playedlist.objects.filter(user=request.user.username) playedlist_items = [] finished = 0 present_in_playedlist = False if playedlist: for item in playedlist: try: game = Game.objects.get(id=item.game_id) playedlist_items.append(game) … -
upload file with rest api in function based view django
i want to create a file upload file rest api and need to call the rest api in django templates which has upload button option. I am confused in writing exact code for it rest api - view.py def uploadfile(request): message={"status":"uploaded"} try: file=request.FILES['fileuploaded'] message={"status data":"uploded and parsing started"} return Response(message,status=200) except: return Response(message,status=400) django - views.py def fileapicall(request): cont={} if request.method == "POST": context = request.method.POST.get("http://localhost:8000/apidata/") return render(request,'result.html',context) template file <form method='post' enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="filename"> <button type="submit"> upload </button> </form> i wana upload file and display the uploaded file in template (django) to api cal and read that file and display it in template (django). -
Why Django Rest_Framework Response() not setting cookies on my browser but works perfectly fine using postman?
I don't understand this bug or issue. So, i am building an application using Django Framework as the server and Angular as the client side. And consider using JWT on the server side. At first, i was testing Log in api(server) using Postman, works fine when log in and creating cookies and token however. When testing using any browser, then i don't get to see the cookies being set. By the way i am using djangocorsheader and jwt packages. I'll leave my views.py and client side. Also, I'd research and saw a few answers on youtube and here but no luck. The only issue i could think of is either my browser or i need to set something on Django side. Please help, any help appreciate it. Client Side (app-http, set up) app-http.service.ts import { throwError as observableThrowError, throwError } from 'rxjs'; import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http'; import { catchError, map, tap } from 'rxjs/operators'; import { LocalStorageService } from '../localStorage/local-storage.service'; import { environment } from '../../../environments/environment'; import { Router } from '@angular/router'; @Injectable({ providedIn: 'root' }) export class AppHttpService { public hostUrl = environment.API_URL; constructor( public localStorageService: LocalStorageService, public … -
django_tenants not resolving subdomains
I have setup and installed django_tenants with the standard settings and middleware from the documentation and watched Tom's Youtube video. 'django_tenants.middleware.main.TenantMainMiddleware' and the option SHOW_PUBLIC_IF_NO_TENANT_FOUND = True The PostgresSQL scheme segregation is working perfectly and I have created a demo tenant with host demo.localhost I am running the server locally with python3 manage.py runserver localhost:8000 in my browser, localhost:8000 works perfectly however the subdomain, demo.localhost:8000 is never resolved and I see no request in the terminal. Is there something I am missing or logs I can check to try and troubleshoot? -
FATAL: role "root" does not exist while running docker-compose up
I have a Django project and I need to create Docker for that project. Here is my code of docker-compose.yaml file version: "3.2" services: web: image: tdsp:latest build: context: . dockerfile: Dockerfile expose: - 9090 ports: - "9090:9090" volumes: - .:/app - /var/run/docker.sock:/var/run/docker.sock environment: DEPLOYMENT: api COMPOSE_HTTP_TIMEOUT: 3600 LC_CTYPE: en_US.UTF-8 LANG: en_US.UTF-8 LC_ALL: en_US.UTF-8 DEBUG: "True" depends_on: postgres: condition: service_healthy stdin_open: true tty: true env_file: .env restart: always command: bash -c 'python3 src/tdsp/manage.py runserver 0.0.0.0:9090' networks: pgnet: nginx: build: ./nginx/ volumes: - ./src:/data/src - ./nginx/sites-enabled:/etc/nginx/conf.d - ./nginx/passwd:/etc/nginx/passwd environment: COMPOSE_HTTP_TIMEOUT: 3600 links: - web:web networks: pgnet: postgres: image: postgres:alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env expose: - 5432 ports: - "5432:5432" healthcheck: test: [ "CMD-SHELL", "pg_isready" ] interval: 5s timeout: 5s retries: 5 networks: pgnet: volumes: postgres_data: networks: pgnet: After running sudo docker-compose up I got these errors and warnings: Recreating tdsp_postgres_1 ... done Recreating tdsp_web_1 ... done Recreating tdsp_nginx_1 ... done Attaching to tdsp_postgres_1, tdsp_web_1, tdsp_nginx_1 postgres_1 | postgres_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization postgres_1 | nginx_1 | /docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration nginx_1 | /docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/ postgres_1 | 2023-04-05 18:20:00.664 UTC [1] LOG: … -
Choosing The Right TechStack
I am undergoing a bootcamp for web developer and i am about to finish the bootcamp, and for a graduation project,I am thinking about building a sports-betting app/website that uses the blockchain technology(solidity smart contracts),I would also like to incorporate the power of A.I to make some recommendations on the bets for premium users, what type of technologies/techstack would you recommend me to use? and also which currency do you recommend me to use? for the frontend and the backend. During this bootcamp i learned HTML,CSS,JavaScript,Node.js,PHP,Laravel,Mysql,MongoDb and React. i've been advised to use djando in the backend and next js in the fornetend, is this a good advice? -
Django MySql backend errors when getting features from Sphinxsearch
Django MySql backend tries to evaluate MySql settings every time it uses a connection and cannot convert an empty string, that is being returned to an integer. When it does so it throws an error as follows (in this example I am just running manage migrate command): root@2d37585a3d96:/mealplanner/trunk# python manage.py migrate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/py36-default/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/py36-default/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/py36-default/lib/python3.6/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/py36-default/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 64, in runchecks issues = run_checks(tags=[Tags.database]) File "/py36-default/lib/python3.6/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/py36-default/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in checksql_mode with self.connection.cursor() as cursor: File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 256, in cursor return self._cursor() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 233, in _cursor self.ensure_connection() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/py36-default/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect self.init_connection_state() File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "/py36-default/lib/python3.6/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/py36-default/lib/python3.6/site-packages/django/db/backends/mysql/features.py", line 83, in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') File "/py36-default/lib/python3.6/site-packages/django/db/backends/utils.py", line … -
Incorrect syntax near 'OUTPUT' while running Django migrations with mssql-django
I am currently trying to connect my Django application to a MSSQL database. I'm using the mssql-django package and am able to run make migrations, however when I run migrate I get an error when it attempts to insert the first row into the django_migrations table. The error recieved is: pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near 'OUTPUT'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)") If I print out the SQL constructed by the mssql-django package, it looks something like this before the paramaters are inserted: INSERT INTO [backdrop_django_migrations] ([app], [name], [applied]) VALUES (?, ?, ?) OUTPUT INSERTED.[id] As far as I know, this is incorrect syntax and the OUTPUT clause should go before the VALUES. I briefly attempted to figure out if I could hack the library to change it but wanted to see if anyone else has experienced this. I don't see anything in the docs, I've tried changing versions, but I'm within the supported versions and still having issues. Django: 3.2 mssql-django: 1.2 python:3.7.4 SQL Server: 2019 Express OS: Windows 10 -
django queryset annotate and order_by. order_by('quantity') splits results
I'm making this queryset in Django. My goal is to list the Top 10 best selling products. The query works and Sum the two products with the same name. top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by() Result: <QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 15}]> But when adding the order_by('quantity') it separates the summed items in two. One with 10 units and the other with 5. top_10_ordered_products = OrderedProduct.objects.filter(order__in=current_month_orders, vendor=vendor).values('product__product_name').annotate(qty=Sum('quantity')).order_by('-quantity') Result: <QuerySet [{'product__product_name': 'Café Expresso', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 10}, {'product__product_name': 'Pão de nozes', 'qty': 5}]> Does anyone know how if it is possible to use the order_by without dismembering the same product_name in the query in these case? -
Python Keyword Arguments behaving differently when taking Default Values
Python Version: 3.8.10 Django Version: 3.1.7 I have a recursive classmethod which walks through a JSON to find any 'Errors' keys and tracks where it was found to help troubleshooting. However, I was seeing that when Errors were not found by getErrorsFromResponse, the function was returning the last value of 'errorMap' which DID have values and I cannot figure out why. When specifying the loc & errorMap values when calling the function, it works fine. But, when allowing python to use the default values specified in the function definition, it has the issue. Can anyone explain why this would happen? I feel like I'm completely misunderstanding how Python works if this doesn't behave. The Method in Question: @classmethod def getErrorsFromResponse(c, response, loc=[], errorMap={}): if type(response) is dict: if "Errors" in response: err = response["Errors"] if len(err) > 0: errorMap[".".join([*loc, "Errors"])] = err else: for k, v in response.items(): c.getErrorsFromResponse(v, loc=[*loc, k], errorMap=errorMap) elif type(response) is list: for i in range(len(response)): c.getErrorsFromResponse(response[i], loc=[*loc, f"[{i}]"], errorMap=errorMap) else: # Error Handling for the Error Finder return errorMap Call which works (views.py) if settings.DEBUG: errorMap = mainReportQuery.getErrorsFromResponse(response, loc=[], errorMap={}) Call which does not work (views.py) if settings.DEBUG: errorMap = mainReportQuery.getErrorsFromResponse(response) Appreciate any help. Switching … -
Retrieving timestamp data from Django models
New to Django and am having some issues trying to display the timestamps from my models in my code. I have two Django classes representing two different lists: models.py class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now=True) class Playedlist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() finished_on = models.DateTimeField(auto_now=True) When I create a new model I understand that models.DateTimeField(auto_now=True) should create a timestamp in the model for when that model was last saved. The functions I am using to add data to these models look like this: views.py def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Game.objects.get(id=game_id) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") @login_required(login_url='/login') def add_to_playedlist(request, game_id): obj = Playedlist.objects.filter(game_id=game_id, user=request.user.username) if obj: obj.delete() game = Playinglist.objects.get(game_id=game_id) played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") else: obj = Playedlist() obj.user = request.user.username obj.game_id = game_id obj.save() game = Playinglist.objects.get(game_id=game_id) game.delete() played_game = Playedlist.objects.filter(game_id=game_id, user=request.user.username) return redirect("profile") And when I try displaying the data I use these functions: views.py playinglist = Playinglist.objects.filter(user=request.user.username) playinglist_items = [] playing = playinglist.count() present_in_playinglist = False …