Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django queryset stops working after multiple uses and filters
I am currently working on a task which requires me to divide my model data into multiple parts based on conditions and then process them differently. I am able to get data from my model correctly and check all available details that they exists. But after applying certain number of filters, suddenly the queryset stops working and don't give the correct results. I don't know why this is happening, can someone explain? Here is part of my code that is causing issue: def test_selection(): po_numbers = ( Model1.objects .filter(schedule__isnull=True) .filter(order_hold_type__isnull=True) .filter(so_line_status='Awaiting Supply') .values_list("customer_po", flat=True) .distinct() ) rows = Model1.objects.filter(customer_po__in=po_numbers).annotate( total_qty=Sum(F('line_item_quantity')*F('cup_count')) ).all() old_sizes = Sizes.get_old_sizes() old_po = rows.filter( item_size__in=old_sizes).values_list('customer_po', flat=True).distinct() rows = rows.filter(~Q(customer_po__in=old_po)).all() partially_scheduled = rows.filter( customer_po__in=list(rows.filter(schedule__isnull=False).values_list( 'customer_po', flat=True).distinct()) ).all() unscheduled = rows.filter( ~Q(customer_po__in=list(partially_scheduled.values_list( 'customer_po', flat=True).distinct().all())) ).all() model2_po = Model2.objects.values_list('customer_po', flat=True).distinct() g1 = unscheduled.exclude(customer_po__in=model2_po) po_list = g1.values_list('customer_po', flat=True).distinct() print(rows.count(), po_list) I thought the problem is in my flow so I created a separate function to test this and this is the point after which the problem starts occurring. This is not throwing any error but coming up empty and I have tried searching for anyone having similar issue but cannot find anything. I have tried following things uptil now: Use filter(~Q()) … -
Error: "libsecp256k1.so.0: cannot open shared object file" with pytonlib on Ubuntu
I'm running a Django project on Ubuntu, and I'm using the following requirements.txt: asgiref==3.8.1 bitarray==2.9.2 certifi==2024.8.30 cffi==1.17.1 charset-normalizer==3.3.2 crc16==0.1.1 crc32c==2.7.post1 Django==5.1.1 djangorestframework==3.15.2 idna==3.8 mysqlclient==2.2.4 pycparser==2.22 PyNaCl==1.5.0 pytonlib requests==2.32.3 sqlparse==0.5.1 tonsdk==1.0.15 tvm-valuetypes==0.0.12 tzdata==2024.1 urllib3==2.2.2 However, I’m facing the following error during runtime: {'msg': 'libsecp256k1.so.0: cannot open shared object file: No such file or directory', 'method': 'deposit'} Exception in tonlibjson.__del__: Traceback (most recent call last): File "/path/to/venv/lib/python3.12/site-packages/pytonlib/tonlibjson.py", line 133, in __del__ self._tonlib_json_client_destroy(self._client) AttributeError: 'TonLib' object has no attribute '_tonlib_json_client_destroy' Exception ignored in: <function TonLib.__del__ at 0x72e2b810da80> Traceback (most recent call last): File "/path/to/venv/lib/python3.12/site-packages/pytonlib/tonlibjson.py", line 136, in __del__ raise RuntimeError(f'Error in tonlibjson.__del__: {ee}') RuntimeError: Error in tonlibjson.__del__: 'TonLib' object has no attribute '_tonlib_json_client_destroy' Steps I’ve already tried: Installed libsecp256k1 using sudo apt-get install libsecp256k1-dev. Verified the installation with ldconfig -p | grep libsecp256k1, and the library is listed. Despite these steps, the error persists. It seems related to the pytonlib and possibly an issue with the TonLib class. Any help on resolving this error or further debugging steps would be greatly appreciated! -
django after submit login info, does not lead to intended detail view page
Thanks for takint the time. I don't know what to do here after a few days of trying differnt ideas. I am learning django, I had read many posts and tutorials, and finally came to this sets of code. After I submit the the prop login email and password, the page does not do anything. It just says "Invalid password" I am not sure my login view is connected to the sqllite. I am thinking my mistake is where the login view file, but not sure. I also use chatgpt to see if it can identify where the mistake is, but it didn't come up with anything. If anyone can point me where I need to adjust, would be much appricated. If I go to the address of the http://127.0.0.1:8000/user/2/, then, the page shows correctly. Unfortuanlly, the codes are long. Here are all the codes: views.py: import random from django.shortcuts import render from django.views.generic import (ListView, DetailView) from django.views.decorators.csrf import csrf_exempt from .models import CustomUser, Events from rest_framework.views import APIView from .serializers import CustomUserSerializer, EventsSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.renderers import TemplateHTMLRenderer from django.contrib.auth import authenticate, login from django.contrib import messages from django.shortcuts import redirect, … -
how to receive webhooks events in django?
I have a webhook registered and have a php file that receives the message and dump it under text file. I want to achieve the same in django but the function never gets called when the event is triggerd the php code '' <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $input = file_get_contents('php://input'); $data = json_decode($input, true); file_put_contents('messages_log.txt', print_r($data, true), FILE_APPEND); $formatted_output = ''; $timestamp = date('d-M-Y-H:i'); if (isset($data['data']['message']['body_message']['content']) && !empty($data['data']['message']['body_message']['content'])) { $content = $data['data']['message']['body_message']['content']; $from_contact = isset($data['data']['message']['from_contact']) ? $data['data']['message']['from_contact'] : 'Unknown'; $formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content); } else { $messages = isset($data['data']['data']['messages'][0]) ? $data['data']['data']['messages'][0] : null; if ($messages) { $message = isset($messages['message']) ? $messages['message'] : []; $content = isset($message['conversation']) ? $message['conversation'] : ''; $from_contact = isset($messages['verifiedBizName']) ? $messages['verifiedBizName'] : ''; if (!empty($content) && !empty($from_contact)) { $formatted_output = sprintf("%s :: %s --> %s", $timestamp, $from_contact, $content); } } } if (!empty($formatted_output)) { file_put_contents('formatted _messages_log.txt', $formatted_output . PHP_EOL, FILE_APPEND); } http_response_code(200); echo json_encode(['status' => 'received']); } else { http_response_code(405); echo json_encode(['status' => 'Method Not Allowed']); } ?> ''' So whenever I receive or send a message from whatsapp it gets dumped here with "messages_log.txt" Python django code (views.py) import os import json from django.http import JsonResponse from … -
Using specific Django LTS version with cookiecutter-django
Currently, the Cookiecutter Django template uses Django 5.0, which is not a long-term support (LTS) release. I couldn't find clear instructions in their documentation on how to specify a different Django version during installation. I'd like to use Django 4.2 with cookiecutter-django since it has LTS support until 2026. How can I do this? -
How to use for loop in django email template
On my website, email is send to the admin email address when ever a user place an order. The problem I am facing, I cannot get for loop working in the email template. How can I use for loop to loop through the products ordered by the user, and display those products in the email. Below is my code email.html {% if order.cart %} <h2> Food Ordered</h2> <table style="border:1px solid black"> {% for obj in products %} <th style="border:1px solid black">Name</th> <th style="border:1px solid black">Quanity</th> <th style="border:1px solid black"> Amount</th> <tr> <td style="border:1px solid black"> {{obj.food.name}} </td> <td style="border:1px solid black"> {{obj.quantity}} </td> <td style="border:1px solid black">{{obj.amount}}</td> </tr> {% endfor %} {% endif %} I want to be able to loop products in the email template def reservationEmail(order): context={ 'order':order.cart, 'products':order.cart.foods.all(), 'name':order.name, 'number':order.number, 'date':order.datetime , 'seats':order.seats, 'OrderId':order.orderid, 'total':order.sumamount, 'quantity':order.reserved.count() } template = get_template('home/reservationnotification.html') mail_subject='Reservation/catering made' content = template.render(context) to_email='narlianafricanboucareau@gmail.com' email=EmailMultiAlternatives(mail_subject,content,to=[to_email]) email.attach_alternative(content, "text/html") email.send() -
python telegram bot async not working simultaneously in 2 groups
I have a telegram bot written with python telegram bot package with the latest release and i have a problem, the bot runs fine everything works but when i try to run it in 2** different groups** at the same time, the bot first finishes the first request in group A then process the request from group B this is a example code async def start_blackjack(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: if not await check_player(update, context): return chat_id = update.message.chat_id game = await sync_to_async(lambda: Game.objects.filter(chat_id=chat_id).order_by('-id').first())() if not game or game.ended: game, created = await sync_to_async(Game.objects.get_or_create)(chat_id=chat_id, ended=False) game.betting = True game.started = False await sync_to_async(game.save)() await asyncio.sleep(2) # Non-blocking sleep await context.bot.send_message(chat_id=chat_id, text="🃏 Set the bet amount for the blackjack game to start.") await create_poll(update, context) # Assume this is an async function await asyncio.sleep(2) # Non-blocking sleep await context.bot.send_message(chat_id=chat_id, text="🃏 Betting process has started!") return if game.betting: await update.message.reply_text("A Blackjack game is in betting progress. Wait for the betting process to end and use /join to join the game.") elif game.started: await update.message.reply_text("A game has already started. Use the /next command to be prompted when the next game starts.") elif game.join_time: await update.message.reply_text("A game is in join time. Use the … -
Heroku changing base_dir to 'app' in Django & React app
I have a django/react app with the file structure funcon(main directory // django project - contains manage.py) -funcon (sub directory // django) -core (sub directory // django) -funcon-frontend (subdir // react) When I run the project locally, everything works great. The react project is the first thing I see when I go to localhost:8000, and the auth requests work between it and the api. When I deploy to heroku, for some reason it seems like it converts my BASE_DIR to app/funcon-frontend and I can't find why it's doing that or how to change it. I am just trying to deploy the react + django app together. I use whitenoise (in my requirements.txt) settings.py BASE_DIR = Path(__file__).resolve().parent.parent dotenv_path = os.path.join(BASE_DIR, '.env') load_dotenv(dotenv_path) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'funcon-frontend', 'build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [] frontend_static = os.path.join(BASE_DIR, 'funcon-frontend', 'build', 'static') if os.path.exists(frontend_static): STATICFILES_DIRS.append(frontend_static) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' WHITENOISE_ROOT = os.path.join(BASE_DIR, 'funcon-frontend', 'build') django_heroku.settings(locals(), staticfiles=False) I have a package.json at my root directory, otherwise heroku doesn't recognize the Nodejs app and it goes "name": "funcon", "version": "1.0.0", "scripts": { "heroku-postbuild": "echo … -
I can not enter the data through DRF API for model Band_qilish even it is empty
I have validation error when attempting to enter the data for the model Band_qilish through DRF API even it is empty. Help me with how to solve this problem. You can try it here: https://github.com/Diamondman51/AVIA.git Just enter some data for models Chipta and Yolovchi after that try entering data through API for the model Band_qilish passing for it existing "ismi" field from model Yolovchi and existing "raqam" field from model Chipta. It must raise exception about existing "raqam" even there is no data in Band_qilish model. I tried everything but it worked only when I removed the parameter unique from the model Chipta from field raqam. But the field raqam in this case must be unique. -
connection to server at "db" (host), post 5432 failed: FATAL: database "<db_name>" does not exist
version: '3.7' services: db: image: postgres:13 restart: always environment: POSTGRES_DB: <db_name> POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres ports: - "5432:5432" networks: - internal_network volumes: - postgres_data:/var/lib/postgresql/data backend: image: backend-image volumes: - static_volume:/src/backend/static - media_volume:/src/backend/media env_file: - ./backend/.env build: ./backend ports: - "8000:8000" depends_on: - redis - db networks: - internal_network volumes: static_volume: media_volume: postgres_data: networks: internal_network: driver: bridge I have a problem after some time I delete the database about 3 days after I do docker-compose up -d The docker-compose.yml itself is written correctly but I don't understand why the database is deleted. In the logs I looked at logs:2024-09-11 08:43:23.829 UTC [11436] FATAL: password authentication failed for user "postgres"2024-09-11 08:43:23.829 UTC [11436] DETAIL: Password does not match for user "postgres". Connection matched pg_hba.conf line 99: "host all all all md5"2024-09-11 08:44:24.551 UTC [11437] FATAL: canceling authentication due to timeout2024-09-11 08:55:20.062 UTC [11486] FATAL: database "<db_name>" does not exist -
Cannot execute shell command on Microsoft IIS
After hosting the Django application on IIS, this fragment of code doesn't work, when I try to execute the command manualy on cmd it works fine but it's doesn't work when the application hosted on IIS execute that command with the code bellow. I've tried to grant all permissions to DefaultAppPool but nothing changes. def convert_to_pdf(input_file, output_file): wordfile = input_file command = ["soffice", "--convert-to", "pdf", wordfile, "--outdir", os.path.dirname(output_file)] subprocess.call(command, shell=True) It works good when the application is outside of IIS environnement. Code -
Why is my Django page not being found, even though I have created a model instance for the page?
Details: I have a Django application where I'm trying to create a dynamic view that displays a detail page for a model instance based on a URL parameter. I have set up the following: Model Code: class Card(models.Model): background_image_id = models.CharField(max_length=100) border_id = models.CharField(max_length=100) image = models.ImageField(upload_to='cards/') number = models.IntegerField() name = models.CharField(max_length=30) subtitle = models.CharField(max_length=100) title = models.CharField(max_length=200) card_paragraph1 = models.TextField() card_paragraph2 = models.TextField() card_paragraph3 = models.TextField() card_paragraph4 = models.TextField() card_button_class = models.CharField(max_length=100) card_detail_url = models.CharField(max_length=100, blank=True, null=True) card_modal_class = models.CharField(max_length=100) card_temple_url = models.CharField(max_length=100, blank=True, null=True) quote = models.CharField(max_length=255) background_modal_image_id = models.CharField(max_length=100) modal_title = models.CharField(max_length=100) View Code: from django.shortcuts import render from .models import Card def card(request, name): try: # Attempt to retrieve the card with the given name card = Card.objects.get(name=name) except Card.DoesNotExist: # If no card is found, render the placeholder template return render(request, 'cards2/temples_placeholder.html') else: # If the card is found, render the card detail template return render(request, 'cards2/card.html', {'card': card}) URL Code: from django.urls import path from . import views urlpatterns = [ path('card/<str:name>/', views.card, name='card_detail'), ] Issue: When I try to access a URL like http://127.0.0.1:8000/card/arepage/, I get a 404 error, indicating that the page cannot be found. ("arepage" being the name of my … -
Django/nginx/gunicorn giving this in deployment: GET https://.../ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)
In development my app runs fine, when deployed to my server running django with nginx/gunicorn I get this error on some (not all) pages when I goto them: GET https://mywebpage.yes.com/longhtmlpage/ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK) I am not even sure where to start with this one, I only see the error by bringing up the browser's dev console. I know its happening though as the web site 'dies' when I hit a page that produces this error, by dies I mean like the menus don't work and I have to reload not the page causing the error but something like the index. Never seen this before and not sure where to start hunting it down, I am curious if its some timeout happening? These pages are pretty large of lots of text(copied straight HTML over from an old site and put it into a static django page) -
Django/Docker multiple containers error - could not translate host name "db" to address: Temporary failure in name resolution
I am working on creating directory and subdirectories: main project directory that contains backend and frontend code/containers. I am working on the connection of main directory and the backend first. Here's my backend docker-compose.yml: `services: db: image: postgres volumes: # - ./docker/docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d - ./data:/var/lib/postgresql/data/ # volumes: # - ./data:/app/backend/data environment: POSTGRES_DB=postgres POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres backend: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app/backend env_file: - docker/environment/db.env ports: - "8000:8000" restart: on-failure depends_on: - db links: - db:db Here's my backend Dockerfile: >! `FROM python:3 >! ENV PYTHONDONTWRITEBYTECODE=1 >! ENV PYTHONUNBUFFERED=1 >! WORKDIR /app/backend/ >! COPY requirements.txt /app/backend/ >! RUN pip install -r requirements.txt >! COPY . /app/backend/ >! EXPOSE 8000 >! CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]` >! >! >! Also, here's the database settings in settings.py: >! `DATABASES = { >! 'default': { >! 'ENGINE': 'django.db.backends.postgresql', >! 'NAME': os.environ.get('POSTGRES_NAME'), >! 'USER': os.environ.get('POSTGRES_USER'), >! 'PASSWORD': os.environ.get('POSTGRES_PASSWORD'), >! 'HOST': 'db', >! 'PORT': 5432, >! } >! }` My backend container works fine if I cd into backend and do a docker compose up. I am trying to set up a docker-compose.yml from the main folder so that I can do a docker compose up from main directory and it would spin … -
Django API - CORS Error with Login (Avoiding Django REST Framework & corsheaders)
I'm new to Django and building a web API without Django REST Framework. My Setup: Angular for frontend (compiled for production) Django backend with user login/register functionality as a First step Used collectstatic command to include Angular's compiled assets Done the setup in urls.py points to Angular's index.html for the main URL -----------------------urls.py------------------- from django.contrib import admin from django.urls import include, path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('api/auth', include('user_auth.urls')), path('', TemplateView.as_view(template_name='index.html')), path('<path:path>', TemplateView.as_view(template_name='index.html')), ] -----------------------settings.py------------------- STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'frontend/dist/frontend/browser'] STATIC_ROOT = BASE_DIR / 'static' CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", # Angular dev server "http://127.0.0.1:4200", "http://localhost:8000", # Django server "http://127.0.0.1:8000", ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'http://127.0.0.1:8000' ) CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_HEADERS = [ 'content-type', 'X-CSRFToken', 'authorization', 'Access-Control-Allow-Origin', 'Access-Control-Allow-Headers' ] Issue: I'm encountering a CORS error when making a login request to http://127.0.0.1:8000/api/auth/login. Attempts: I tried using the corsheaders package to resolve the issue with CORS and CORS issue has been resolved but then faced a CSRF token issue when make a post request to the http://127.0.0.1:8000/api/auth/login.. I understand by using the csrf_exempt decorator i can resolve the issue, Question: Is my approach of building a custom API without external packages feasible and correct? Thank … -
how to create an object for a Django model with many to many field?
class Date(models.Model): date = models.DateField() def __str__(self): return str(self.date) class Time(models.Model): time = models.TimeField() def __str__(self): return str(self.time) class Showtimes(models.Model): theater = models.ForeignKey(Theater,on_delete=models.CASCADE,related_name="theater") movie = models.ForeignKey(Movie,on_delete=models.CASCADE,related_name="movie") show_date = models.ManyToManyField(Date) show_time = models.ManyToManyField(Time) how can i create a objects with multiple date and time by passing aruguments in objects.create function call Showtimes.objects.create(theater=th,movie=m,show_date = Date.objects.all(),show_time = Time.objects.all()).save() i want to create a object for ShowTimes by function call objects.create by passing all date and time field -
Is there a way to use bcc with django mailgun mime
I am using Mailgun mime with my django project to send out newsletters but i'm not sure if their is a way to use blind carbon copy so that every recipient can't view every other recipients email addresses i have looked from through the documentation for mailgun and the mailgun mime module but it doesn't seem to be very clear if you can or not -
Not redirecting to correct template
So I am practicing django cbvs and I am using update veiw to update model data and I created a button which is suppose to redirect to the form to update but it is showing me the same template page with jst url updated and id infront of it. I have django 1.11.25 installed currently heres my app url and views and the details page: urls: from django.conf.urls import url from Cbvs_app import views app_name = 'Cbvs_app' urlpatterns = [ url(r'^$',views.School_List.as_view(),name='list'), url(r'(?P<pk>\d+)/$',views.School_Detail.as_view(),name='details'), # it simply grabs the primary key provided in href and displays corresponding detail view to the primary key url(r'^create/$',views.School_Create.as_view(),name='create'), # print("Registering SchoolUpdateView URL"), url(r'^update/(?P<pk>\d+)/$',views.SchoolUpdateView.as_view(),name='update'), ] Views: class School_Create(CreateView): # my create view is working fine fields = ('name','principal','location') model = models.School template_name = "Cbvs_app/school_form.html" class SchoolUpdateView(UpdateView): fields = ("name","principal") model = models.School template_name = "Cbvs_app/school_form.html" forms: {% extends "Cbvs_app/Cbvs_app_basic.html" %} {% block body_block %} <div class="jumbotron"> <h1>Welcome to detail of all schools</h1> <h2>School details: </h2> <p>Name: {{school_detail.name }}</p> <p>Principal: {{school_detail.principal }}</p> <p>Location: {{school_detail.location }}</p> <p>Students:</p> {% for student in school_detail.students.all %} <p>{{student.name}} who is {{student.age}} years old.</p> {% endfor %} <p>Id: {{school_detail.pk}}</p> <p><a class='btn btn-warning' href="{% url 'Cbvs_app:update' pk=school_detail.pk %}">Update</a></p> </div> {% endblock %} I tried to … -
Is it reasonable to use Vue + Django / React + Django?
I've decided to create a portfolio project using vue and django. But i've asked myself a question if i should do this. Im not going to use SPA, vue is required only for unifining and more comfortable working with ui (forms, buttons etc.) I wondered if such a choice will bring worse user experience and make my project more difficult for nothing. Have anyone worked with such cases? I have been working with those frameworks one-by-one, but have never tried to combine those. -
CSS/JS Issue: Grey Space Appears Between Navbar and Content on Page Load, Then Disappears on Interaction
I'm working on a Django-based website and encountering an issue with a grey space appearing between my fixed navbar and the content on the home page. The grey space appears only on the initial page load, and once I interact with the page (like scrolling), the grey space disappears, and the layout corrects itself. Here's what happens: On initial load: A grey space appears between the navbar and the content. After any small interaction: The grey space disappears, and the page layout behaves as expected. What I've Tried: I’ve traced the issue to this JavaScript that adjusts the margin of the content based on the height of the navbar: document.addEventListener("DOMContentLoaded", function () { var navbar = document.getElementById("navbar"); var content = document.querySelector(".content"); function adjustContentMargin() { var navbarHeight = navbar.offsetHeight; content.style.marginTop = navbarHeight + "px"; } // Adjust margin on page load window.onload = function() { adjustContentMargin(); }; // Re-adjust on window resize window.addEventListener('resize', function () { adjustContentMargin(); }); }); Problem: When the JS is active, the page initially loads with the grey space between the navbar and the content. The margin-top gets applied, but it looks like it happens after the grey space appears. If I remove the JS, the page … -
Storing time and date in postgre database based on local time in django project
I have a virtual server in Europe where a series of csv files are uploaded I am trying to use a script to read the information from csv and store it in the database(postgresql) My problem is when I read the date from the csv file, the date is based on Iran's time zone and I want it to be saved in the same way, but the time is saved based on utc this is a sample of date records in csv files 2024-09-12 08:00:00,.... and this is my command from read data from csv: AnemometerData = apps.get_model("DataLoger", "AnemometerData") class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("from_date", type=str) def handle(self, *args, **options): self.read_csv(options["from_date"]) def validate_date(self, date): try: _date = datetime.strptime(date, "%Y-%m-%d").replace(minute=0, second=0, microsecond=0) return _date except Exception as e: raise CommandError(e) def read_csv(self, from_date): from_date = self.validate_date(from_date) base_path = settings.BASE_DIR path = os.path.join(base_path, "DataLoger", "FTP") iran_tz = pytz.timezone('Asia/Tehran') current_time = datetime.now(iran_tz).replace(minute=0, second=0, microsecond=0, tzinfo=None) while from_date <= current_time: for id in ["G241156", "G241157"]: try: time_str = from_date.strftime("%Y%m%d_%H%M") file_path = os.path.join(path, f'{id}_{time_str}.csv.gz') df = pd.read_csv(file_path, compression='gzip', header=0, sep=',', quotechar='"') remove_columns = ['Anemometer 100m;wind_speed;Count', 'Anemometer 96m;wind_speed;Count', 'Anemometer 60m;wind_speed;Count', 'Anemometer 45m;wind_speed;Count', 'Wind Vane 94m;wind_direction;Count', 'Wind Vane 45m;wind_direction;Count', 'Hygro/Thermo 95m;humidity;Count', 'Hygro/Thermo 10m;humidity;Count', 'Hygro/Thermo 95m;temperature;Count', 'Hygro/Thermo 10m;temperature;Count', … -
Is it possible to switch to a through model in one release?
Assume I have those Django models: class Book(models.Model): title = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book) I already have a production system with several objects and several Author <-> Book connections. Now I want to switch to: class Book(models.Model): title = models.CharField(max_length=100) class BookAuthor(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) author = models.ForeignKey("Author", on_delete=models.CASCADE) impact = models.IntegerField(default=1) class Meta: unique_together = ("book", "author") class Author(models.Model): name = models.CharField(max_length=100) books = models.ManyToManyField(Book, through=BookAuthor) If I do this Migration: from django.db import migrations def migrate_author_books(apps, schema_editor): Author = apps.get_model('yourappname', 'Author') BookAuthor = apps.get_model('yourappname', 'BookAuthor') for author in Author.objects.all(): for book in author.books.all(): # Create a BookAuthor entry with default impact=1 BookAuthor.objects.create(author=author, book=book, impact=1) class Migration(migrations.Migration): dependencies = [ ('yourappname', 'previous_migration_file'), ] operations = [ migrations.RunPython(migrate_author_books), ] then the loop for book in author.books.all() will access the new (and empty) BookAuthor table instead of iterating over the existing default table Django created. How can I make the data migration? The only way I see is to have two releases: Just add the new BookAuthor model and fill it with data, but keep the existing one. So introducing a new field and keeping the old one. Also change every single place where author.books … -
Cannot get User Information within B2C Access Token
def get_access_token(authorization_code): token_url = "https://login.microsoftonline.com/xxxx-xxxx-xxxx-xxxx-xxxxcxxxxe/oauth2/v2.0/token" redirect_uri = "https://localhost/api/oauth2/callback" client_id = "xxxxxx-xxx-xxxx-xxx-xxxxxx" client_secret = "xxxx~xxxxx~xxxx_xxxxxxxxx" scope = "https://graph.microsoft.com/.default" headers = {'Content-Type' : 'application/x-www-form-urlencoded'} token_data = { 'grant_type': 'client_credentials', 'code': authorization_code, 'redirect_uri': redirect_uri, 'client_id': client_id, 'client_secret': client_secret, 'scope': scope, } response = requests.post(token_url, headers = headers, data=token_data) token_json = response.json() if 'access_token' in token_json: return token_json['access_token'] else: raise Exception(f"Error fetching access token: {token_json.get('error_description', 'Unknown error')}") I can't find any user information within the bearer that Microsoft provides. The token end point seems to be correct and I get all the user info within Microsoft Graph Explorer but can't on my django app. -
Color problem in disqus in Django and Tailwind
I tried to use disqus in my django project: <div> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables */ var disqus_config = function () { this.page.url = "{{ request.path }}"; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = "{{ news.id }}"; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function () { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://site-name.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> But I got this error: Uncaught Error: parseColor received unparseable color: oklch(0.7464770.0216264.436) I'm using tailwind in project and I guessed that problem might be because of it. So I completely removed tailwind styles and it worked. But my whole project works with tailwind, I can't remove or replace it. I tried using the prose class from the @tailwindcss/typography plugin, but that didn't work either. -
Django date format puzzle in multi language app - SHORT_DATE_FORMAT not used with English
We use Django 4.2.11 and I have a bit of a date format puzzle regarding localization in different languages in our project. We are using jquery datepicker and configure it with the current active language. The behaviour of date fields is consistent in languages such as German, Italian and French. Dates are displayed according to the SHORT_DATE_FORMAT of Django, and the returned dates of datepicker show the same formatting. Only with English it's different. The SHORT_DATE_FORMAT is defined as being m/d/Y - but the date get's displayed in the form of YYYY-MM-DD. This leads to the weird behaviour that the user gets displayed a date like for instance 2024-09-08 and when chosing a date from the datepicker the same field shows a value of 09/08/2024. But still the form can be saved without errors and the date is handled correctly. The date field is defined as declarationDate = models.DateField() in the model. We are using django-crispy-forms 2.1 with bootstrap 5. Any ideas what goes wrong here? Where can I look? (I've looked for some time now ...)