Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
While Clicking On Razorpay Pay Now Using CARD / WALLET The New Tab Is about:blank#blocked , Django
I used to integrate django and razor pay , but when i click on pay now on options like , card , wallet , ( the payment needed to be in open in new tab ) the page become blank , i cannot access the success page Note: Upi is working and i am getting the result in dashboard , also payment id is generated and its reflecting in razorpay dash board Script Also Loaded My template .html <button id="rzp-button1" class="btn btn-primary my-2 w-100">Pay with Razorpay</button> <script> var options = { "key": "KEY", // Enter the Key ID generated from the Dashboard "amount": "{{payment.amount}}", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise "currency": "INR", "name": "Acme Corp", "description": "Test Transaction", "image": "https://example.com/your_logo", "order_id": "{{payment.id}}", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 // "callback_url": "https://eneqd3r9zrjok.x.pipedream.net/", "prefill": { "name": "Gaurav Kumar", "email": "gaurav.kumar@example.com", "contact": "9000090000" }, "handler": function (response){ alert(response.razorpay_payment_id); alert(response.razorpay_order_id); alert(response.razorpay_signature) }, "notes": { "address": "Razorpay Corporate Office" }, "theme": { "color": "#3399cc" }, }; var rzp1 = new Razorpay(options); rzp1.on('payment.failed', function (response){ alert(response.error.code); alert(response.error.description); alert(response.error.source); alert(response.error.step); alert(response.error.reason); alert(response.error.metadata.order_id); alert(response.error.metadata.payment_id); }); document.getElementById('rzp-button1').onclick = function(e){ … -
How to check if model has something inside in django?
I have a model of Branch, and a model of Worker. I want to filter only these branches, which have at least one user inside. models.py class Branch(models.Model): name = models.CharField(max_length=100) class Worker(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) fullname = models.CharField(max_length=150) branch = models.ForeignKey(Branch, on_delete=models.SET_NULL, null=True, related_name='branch') position = models.CharField(max_length=200) manager = models.BooleanField(default=False) I tried to add related_name to worker-branch, but now I don't know how to use it, and is it right way to do so? I also tried to filter like that: Worker.objects.filter(branch=?).exists(). But it doesn't make sense. At the end I want to have a list of branches which have at least one worker. -
Django. How to write the time to the database in UTC when using the settings 'TIME_ZONE' and 'USE_TZ = True'
There is a Django version 4.0 project. In it, in one of the tables, I use a field to save the datetime. I need the datetime stored in UTC in the database PostgreSQL. What I did: settings.py ... USE_TZ = True TIME_ZONE = "UTC+3" ... models.py class ManualMeasurements(models.Model): ... timestamp = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now) .... At the same time, migration to PostgreSQL created field with time zone: "timestamp" timestamptz NOT NULL Ok, but according to the documentation, this is enough so that in the form of the admin panel, the time in this field is displayed in the time field specified in settings.py , and the database was written in UTC. But no. I found that the database is currently written like this: 2023-07-10 14:55:17.000 +0300 In admin.py I'm overriding the save method: def save_model(self, request, obj: ManualMeasurements, form, change, debug=True): if obj.timestamp: obj.timestamp = obj.timestamp.astimezone(time_func.get_timezone('UTC')) super().save_model(request, obj, form, change) And still in the database I get the time in the current time zone with the time zone indication. What am I doing wrong and how do I get what I need? -
How to change the default language and add it_IT.UTF-8 locale to locale.gen on Azure?
I'm trying to change the default language on the Azure machine hosting my app. Currently, the default language is set to en_US.UTF-8 and is the only one in locale.gen, but I need to configure it to it_IT.UTF-8 to support my Django project. When I start my app and the Django app execute the "import locale" command followed by "locale.setlocale(locale.LC_TIME, 'it_IT.utf8')", I get the "unsupported locale setting" error. I suspect that the Italian language is not properly configured in the system. What are the necessary steps to change the default language and add the it_IT.UTF-8 locale to locale.gen on Azure? Or any others solution? Thank you in advance for your assistance! I created a startup.sh file in the home directory (the only persistent location) with the following commands: echo "it_IT.UTF-8" >> locale.gen locale-gen Then, in the Azure App configuration under General settings, I specified the path /home/startup.sh in Stack Settings > Startup Command. However, when I attempted to start the machine with this configuration, the startup failed for unknown reasons. I expected the startup.sh script to modify the locale.gen file and generate the it_IT.UTF-8 locale successfully. -
проблема в django. Проблема с кодировкой в uri [closed]
после деплоя Django проекта на хостинг. Слетает кодировка в киррилических url enter image description here во время get запроса не находит запись enter image description here На локальной машине все было нормально. На хостинге такая беда Не находит данные в бд. Из-за кода на киррилице -
Unexpected behavior of class method arguments [duplicate]
While writing the next unit test, I discovered the non-obvious behavior of the argument in the class method. The create_data method was supposed to create a dictionary with the default values of the arguments on each call. However, it turned out that if, after creating the dictionary, you change the value of one of the keys, then now IT will become default. from rest_framework.test import APITestCase class Test(APITestCase): def create_data(self, foo={'foo': 1}): return {'foo': foo} def test_1(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 1}} default_data['foo']['foo'] = 2 print(default_data) # {'foo': {'foo': 2}} def test_2(self): default_data = self.create_data() print(default_data) # {'foo': {'foo': 2}} Thus, after changing the value in the dictionary in the test_1 method, in the test_2 method, create_data will return a dictionary with the value that we set in test_1. Linter flake8 writes: Do not use mutable data structures for argument defaults. They are created during function definition time. All calls to the function reuse this one instance of that data structure, persisting changes between them. However, doesn't the line "All calls to the function reuse this one instance of that data structure" mean that each method call should use the original data structure written when the method … -
Sending email after Login Django Allauth
I’m new using Django Allauth, is there a way I can implement sending email after login? For example; every time someone logged into my account I will receive an email automatically. -
Django - Default schema (dbo) to custom schema name for native django apps?
I would like django to change the reference to the native django table(s) schema(dbo) as seen in the sql below. I have renamed the schema to meta in SQL, but when I run the app, it recreates the tables on the dbo schema again in the DB. So I deleted them again and renamed my meta schemas back to dbo in TSQL and tried to get django to migrate them to the new schema name by running, python manage.py inspectdb > models.py The models.py generates and then changing the following in the models.py file in the root folder. eg. class AuthGroup(models.Model): # model fields... class Meta: db_table = 'meta.auth_group' Then I run makemigrations and then migrate does not detect the models.py changes. Is this the correct approach or are we still stuck in changing the user running django to have a default schema to be set to "meta"? ALTER SCHEMA dbo TRANSFER [meta].[django_admin_log] ALTER SCHEMA dbo TRANSFER [meta].[admin_interface_theme] ALTER SCHEMA dbo TRANSFER [meta].[auth_group] ALTER SCHEMA dbo TRANSFER [meta].[auth_group_permissions] ALTER SCHEMA dbo TRANSFER [meta].[auth_user] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_groups] ALTER SCHEMA dbo TRANSFER [meta].[auth_user_user_permissions] ALTER SCHEMA dbo TRANSFER [meta].[django_content_type] ALTER SCHEMA dbo TRANSFER [meta].[django_migrations] ALTER SCHEMA dbo TRANSFER [meta].[django_session] ALTER SCHEMA … -
Django how to display a pdf in canvas-wrapper
I have been given a task to make a page.inside it should be a Pdf that people can read without downloading if they don't want to. Now the problem is that meanwhile i can embed or Iframe the pdf i can not display it in way the template has been given to me Loading... <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> <div class="spinner-grow text-primary" role="status"> <span class="visually-hidden">Loading...</span> </div> </div> <canvas id="pdf-canvas" class="onload-pdf" data-url="{% static 'apply/pdf/terms.pdf' %}"> </canvas> </div> As you can see there is a canvas wrapper that pdf should be inside how can i do that? -
How to make crud operation on Django without page reload
Hello I am trying make crud operation on Django without page reload and also implement Django Form validation like duplicate messages and error messages -
how to host projects in pythonAnywhere, when i'm try to do i have got an error
when I'm going to do app deployment , open my pythonAnywhere--->console---->bash I've to make virtual environment first, but I got an error here my command is:- 09:19 ~ $ mkvirtualenv test --python=usr/bin/python3.11 got Error is below :- RuntimeError: failed to find interpreter for Builtin discover of python_spec='usr/bin/python3.11 I tried to do but actually got this error:- error in Bash console -
Django unique_together with df.to_sql not working
I am using df.to_sql to insert data into database table. But I don't want to have some duplicated rows for some columns. I tried unique_together but it doesn't seem working. class InsertionOrdersRealSpents(InsertionOrdersCommonFields): def __str__(self): return "%s" % self.insertion_order # return "{}".format(self.insertion_order) class Meta: db_table = 'InserstionOrdersRealSpents' unique_together = ['date', 'advertiser', 'dsp', 'insertion_order', 'impressions'] Any method or suggestion? If there is identical row in the database, skip that row in the file to upload ? -
Could not parse the remainder: '|' from '|' in Django template while paginating
while paginating the blog app , the following error showed up. TemplateSyntaxError at /home/ Could not parse the remainder: '|' from '|' Request Method: GET Request URL: http://127.0.0.1:8000/home/?page1 Django Version: 4.2.2 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '|' from '|' Exception Location: C:\Users\chand\venv\Lib\site-packages\django\template\base.py, line 703, in init Raised during: blog.views.PostListView Python Executable: C:\Users\chand\venv\Scripts\python.exe Python Version: 3.11.3 Python Path: ['C:\Users\chand\django_project', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\chand\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\chand\AppData\Local\Programs\Python\Python311', 'C:\Users\chand\venv', 'C:\Users\chand\venv\Lib\site-packages'] Server time: Mon, 10 Jul 2023 10:24:46 +0000 This was the html template I wrote: {% extends "blog/base.html" %} {% block content %} {% for post in posts %} <article class="media content-section"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.content }}</p> </div> </article> {% endfor %} {% if is_paginated %} {% if page_obj.has_previous %} <a class="btn btn-outline-info mb-4" href="?page=1">First</a> <a class="btn btn-outline-info mb-4" href="{{ page_obj.previous_page_number }}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{num}}</a> {% elif num > page_obj.number | add:'-3' and num < page.obj.number | add:'3' %} <a class="btn btn-outline-info … -
Angular HTTP DELETE request not working with Django backend
I am facing an issue with performing HTTP DELETE requests from my Angular frontend to my Django backend. The deletion works fine when testing it with Django Postman, but it fails to work when triggered from the Angular interface. Here is the relevant code snippet: deleteClick(item: any) { if (confirm('Are you sure?')) { const departmentToDelete = { DepartmentId: 145742, DepartmentName: 'TELECOMM', description: 'it is a department to sale' }; this.service.deleteDepartment(departmentToDelete).subscribe( (data) => { alert(data.toString()); this.refreshDepList(); }, (error) => { console.log('Error occurred while deleting the department:', error); alert('Error occurred while deleting the department.'); } ); } } Backend code (Django): elif request.method == 'DELETE': department_data = JSONParser().parse(request) department = Departments.objects.get(DepartmentId=department_data['DepartmentId']) department.delete() return JsonResponse("Deleted Successfully!!", safe=False) When triggering the deletion from the Angular interface, I receive the following error in the console rest_framework.exceptions.ParseError: JSON parse error - Expecting value: line 1 column 1 (char 0) [10/Jul/2023 12:00:02] "DELETE /department/145742 HTTP/1.1" 500 98390 I have verified that the URL and headers are correct, and the request payload seems to be in the expected JSON format. However, I can't figure out why the deletion is not working in the Angular interface. Any help or guidance on how to troubleshoot and resolve this issue would … -
update_or_create only for first record
I want to check if multiple records are equal to IS_USABLE = False then update only one record to IS_USABLSE = True.But it fails. new_invoice = N_INVOICE.objects.update_or_create(INVOICE_IS_USABLSE = False, defaults={'INVOICE_IS_USABLSE':True,})[0] -
System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique
System check identified some issues: WARNINGS: ?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace No installed app with label 'first_app'. In terminal after I typed python manage.py make migrations first_app I am facing this issue. Plz help -
How can we run two services with one common model DB in Django?
How can we run two services with one common model DB in Django? I have project structures like below A Project has Model C in its project. ( which should be public ) B Project has Model C in its project. ( which should not be public ) They share Model C. But when Project B needs to change Model C then we had to manually change model script of Project A. It created many problems. How can we deal with this? Should we merge two projects in two apps on one project? Then How can we make only one app private? -
ModuleNotFoundError: No module named 'bootstrap5' getting this error after moving my django project to docker
Hi I just moved my Django project on the docker. And created an image successfully. But when,I tried running it using docker run -p 8000:8000 my-django-app I am getting the error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner self.run() File "/usr/local/lib/python3.11/threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/local/lib/python3.11/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 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap5' I have even added the bootstrap5 in the django settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'firstapp', 'bootstrap5', ] And I have added it in the requriments.txt django-bootstrap5==23.3 This if my dockerfile # Use an official Python … -
Kafka and Django management command
Hello everyone hope I find you well! So I'm trying to setup a new project with Django and a Kafka consumer. I'm using confluent-python package to create my consumer. So I'm facing a very odd situation. When I start my project through my docker entrypoint I run a django management command with the following code: import simplejson from confluent_kafka import Consumer from django.core.management import BaseCommand from loguru import logger from apps.<my_service> import KafkaHandler class Command(BaseCommand): help = "Start Reporting Kafka Consumer" def handle(self, *args, **kwargs): logger.debug("Starting consumer") consumer = Consumer( {"bootstrap.servers": "kafka:19091", "group.id": "reporting"} ) consumer.subscribe(["test_producer"]) kafka_handler = KafkaHandler() try: while True: logger.debug("Consuming") msg = consumer.poll(1.0) if msg is None: continue if msg.error(): logger.debug(f"Consumer error: {msg.error()}") continue event_message = msg.value().decode() logger.debug(f"Received message: {event_message}") json_message = simplejson.loads(event_message) kafka_handler.handle(json_message) finally: consumer.close() After I start my project through command docker-compose up I see that the log "Start consumer" is printed two times and that I have two consumer connections instead of only one so I suspect that this code is being run twice which is very odd. Can someone help me with this situation? Bellow I share my docker-entrypoint !/bin/bash set -e if [[ "${PROJECT_RUN_MODE}" == "production" ]]; then exec <run production mode> … -
Django + SQLite3 in Docker - Database automatically rolled back to initial state after new Docker build and start
I have a Django project which uses SQLite3 database running in Docker container. Dockerfile: # Base image FROM python:3.10-slim-buster # Set working directory WORKDIR /app # Copy the entire project directory COPY . /app # Install project dependencies RUN pip install -r requirements_dev.txt # Expose port EXPOSE 8000 # Run the development server CMD ["python", "doc_manager/manage.py", "runserver", "0.0.0.0:8000"] docker-compose.yml: version: '3' services: web: build: context: . dockerfile: Dockerfile ports: - "8000:8000" volumes: - ./:/app/doc-manager-web When I want to build/deploy new version in this set-up, I execute these 2 commands: docker compose build docker compose up Both commands are successfully executed. But, consider this use case: I deploy the current version using the given set-up. I perform some modifications in the database (CRUD operations). The database is now modified. I then perform some changes in the code itself (not in the Dockerfile or in docker-compose.yml). I re-run the docker compose build and docker compose up commands. Then, I end up with the initial state of the database without the modifications I performed in step number 2. How do I make sure that my SQLite3 database keeps it's modifications regardless of the code modifications I'll do in the future and regardless of … -
Why did I get 302 Error instead of the asked page in Django
When I try to go to the update page for my "Project" object by pressing a button, Page load, and nothing happend (just return the same page). url behind is "/projects/1/update". I have the same behavior for and other object called "Version". (Pression but and go to update page). But for this one it's works properly. the part url.py the part views.py I checked following issues: URL is correctly generated by "{% url ... %}" in the template I'm testing it with a admin account, permission shall be correct. The view.py, and URL, are the same as for Version, (where it's works). template "projects/project_form.html" also exist. When put the URL "http://localhost:8000/projects/1/update" in the URL I get the code 302 and go back to home "/". Someone has an Idea why could be go wrong ? -
is there some one know why django restframework not working for me
i have a problem with wy backend that is written with django and djanorestframework i have been installed my djangorestframework within my project but it didn't work it show me this error Import "rest_framework.response" could not be resolved this is the setting.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'base', ] ``` and this is my view.py file ``` from django.shortcuts import render from django.http import JsonResponse from rest_framework.response import Response from rest_framework.views import APIView # Create your views here. def getRoutes(request): return JsonResponse('hello',safe=False) he didn't know djangorestframework and this is my packages that installed inside my virtual environment Django==4.2.3 djangorestframework==3.14.0 pytz==2023.3 sqlparse==0.4.4 tzdata==2023.3 please help me -
django rest framework accept post request from postman not from android virtual device flutter
Map<String, dynamic> jsonData = { "brand": brand, "quantity": t_quantity, "transaction_type": selectedChoice, "almari": almari, "emp_id": emp_id, "emp_name": emp_name, "user_name": it_support, "opr_name": "flutter admin", "asset_name": pk, }; String jsonString = jsonEncode(jsonData); var a_response = await http.post( Uri.parse('http://10.10.148.148:8000/api/transaction/'), headers: {"Content-Type": "application/json"}, body: jsonString); if (a_response.statusCode == 200) { print('POST request successful'); } else { print('Request failed with status: ${a_response.statusCode}'); } Bad Request: /api/transaction/ [10/Jul/2023 13:36:27] "POST /api/transaction/ HTTP/1.1" 400 58 -
Best doable way to deploy micorservices in AWS Lambda
I have been trying to use AWS Lambda for a deployment. I have a single frontend for where users can select a service they want and each of these will be redirected to a different Lambda function. I'm using S3 to store static files and for authentication and data, MySQL in RDS is used. My current application is a Django I want to know what's the best possible way to do this. I have followed tutorials to deploy lambda functions using zappa, zappa in a docker image and docker image as a whole. I also find it difficult to deploy django in aws python image. Is django a suitable framework, or are there better lightweight options considering it being a full-stack framework? Is docker images the best way to run these applications? -
Docker compose build doesn't create an image/container even with successful execution
I have been trying to deploy my application on "https://ip_address/3000" with a react front end and Django backend. The app works well in my PC, but when i try to access it from a different PC im unable to get the backend data on the frontend. Im guessing this is because of the unsucessful creation of the docker image? This is my backend dockerfile FROM python:3.8-slim-buster # Sets environment variable ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /backend # Install dependencies: COPY requirements.txt . RUN pip install --upgrade pip && pip install -r requirements.txt # Copy the rest of the code COPY . . This is my docker-compose.yml version: "3.7" services: backend: build: /home/ibds/Desktop/Dashboard command: python manage.py runserver 0.0.0.0:8000 volumes: - /home/ibds/Desktop/Dashboard:/backend ports: - 8000:8000 depends_on: - db frontend: build: /home/ibds/Desktop/Dashboard/frontend volumes: - /home/ibds/Desktop/Dashboard/frontend:/frontend - /frontend/node_modules ports: - 3000:3000 environment: - NODE_ENV=development command: npm start db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=dbname volumes: postgres_data: This is my dockerfile in the frontend # Use an official node runtime as a parent image FROM node:14-alpine # Set work directory WORKDIR /frontend # Install dependencies COPY package.json . COPY package-lock.json . RUN npm …