Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Making a post request to a Django app on MS Azure from a client that I do not own getting cors error
I have deployed a django app on azure and have been running it for a while. I recently added an endpoint to my app that should get a POST request from the jengahq website. However, I am able to simulate post requests from them to my endpoint and see the responses. Everytime I simulate my POST request, I get an error: Access to fetch at https://notification-webservice.azurewebsites.net/... from origin jengahq site has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource... However, I have enabled cors-origin for this website. It also requires a basic authentication header which I have added appropriately as shown below: CSRF_TRUSTED_ORIGINS = ( ["https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ]) CORS_ALLOWED_ORIGINS = [ "https://" + os.environ["WEBSITE_HOSTNAME"], "https://secondsite", ] CORS_ALLOWED_HEADERS = [ 'Accept', 'Accept-Encoding', 'Authorization', ... ] The first website in my cors allowed is where my frontend is served and I am able to run requests well. This does not work for the second website. When I remove my frontend site from my cors allowed list, I get a similar error, but the endpoint seems different: Access to fetch at mysite from origin myfrontend has been blocked by CORS policy... Even with the addition … -
Can't send a labNumber into an sql query
I'm very confused as to why my _labNumber variable isn't getting sent into the method that I am using to call an SQL query, as it works for other methods in the same class. I have a try catch block in my class that calls the methods where I pass in _labNumber(This is correctly assigned, I have triple checked it) try: _comment = self.dataServices.GetComment(_labNumber) _value2 = self.dataServices.GetValue2(_labNumber) _value1 = self.dataServices.GetValue1(_labNumber) _results = self.dataServices.getResults(_labNumber) except AttributeError: _comment = None _value2 = None _value1 = None _results = None This is one of the methods in the class that is being used to retrieve the data from the database: def GetValue2(self, _LabNumber): _LabNumberStr = str(_LabNumber) try: with connection.cursor() as _cursor: _cursor.execute("{CALL dbo.uspShireXGetValue2(%s)}", _LabNumberStr) row = _cursor.fetchone() if row: return {'VALUE2': row[0]}#21 else: return {'VALUE2': None} except Exception as e: # Handle or log the exception as appropriate print(f"An error occurred: {e}") return {'VALUE2': None} And finally here is the query that I know works as it returns the data when I hard code a lab number: @LabNumber VARCHAR(10) AS SET NOCOUNT ON SELECT WDR.COMMENT FROM dbo.DNA_WORKSHEET_DET WD INNER JOIN dbo.DNA_WORKSHEET W ON WD.WORKSHEET = W.WORKSHEET LEFT OUTER JOIN dbo.DNA_TEST T ON W.TEST … -
127.0.0.1 slowness in django virtual environment running with vscode
After connecting to the server built in awsec2 with a remote of vscode, the django virtual environment was run to make a connection of 127.0.0.1. But its speed is too slow. When you connect using Chrome, the loading is too slow, sometimes it's infinitely loaded, and sometimes there's content that hasn't been loaded even if it's marked. There are even cases where only white pages are displayed. I'm currently using a MAC. Using a Windows laptop, connecting remotely to a remote server using vcode and then connecting to 127.0.0.1 will work fine I've been looking for other posts, but none of them correspond to my issues. I've tried many things. Turn off the process that currently uses 8000 ports on the Mac (but it was not there) Connect django to 8888 port or unused port and view it (this is the same error as well) It used to work very well, but it doesn't work well at some point. What should I do? -
Groups and Permissions in Django
When I am creating a new user, It is getting automatically assigned all the groups to new user. And, vice-versa. I am attaching code for models.py, serializers.py and views.py models.py serializers.py views.py I tried above solution and i am expecting that if I add a new group then It is not automatically assigned to every user or create a new user then also not assign all groups to them. And, in permissions file, I am not getting user groups why? permissions.py -
How to handle migrations in a big project?
i am currently working backend on a project with django and i have been facing problems with migrations mainly because i don't know when to make new migrations at all or only migrate the model i want, and my main problem is when i make a new branch do my work and migrate then merge it with develop the 0001 initial migrations make problems and conflict so i have to drop everything and repeat. Any help would be amazing. I tried creating a migrations.sh that removes migrations and database and migrates every model but surely this isn't the right way. -
ChoiceField renderer not working after update to Django 1.11
I have old project writen in Django 1.8. I try update it to newest version. At this moment i jave problem with version 1.11. I have this code: class HorizontalRadioRenderer(forms.RadioSelect.renderer): """ this overrides widget method to put radio buttons horizontally instead of vertically. """ def render(self): """Outputs radios""" #return mark_safe(u'\n'.join([u'%s\n' % w for w in self])) return mark_safe('\n'.join(['<td>%s</td>\n' % w.tag() for w in self])) medical_question1 = forms.ChoiceField(widget=forms.RadioSelect(_render=HorizontalRadioRenderer), choices=YES_NO) How can i repair it in new Django? This was the legacy code for Django <=1.10. How can i replace it? Please help me -
Wagtail publish images programatically doesn't reflect in FE
Created a management command to import content from Headway app to wagtail. Since headwayapp doesn't have any api's i copied the html to a separate file and parsed it. Everything works fine apart from images, Unless i click publish to that specific page in admin dashboard images doesn't reflect. All other content seems to work fine. Here is the management command Any help would be appreciated! from django.core.management.base import BaseCommand from wagtail.models import Page from wagtail.images.models import Image from wagtail.embeds.models import Embed from home.models import ChangelogPost, Category, Product from bs4 import BeautifulSoup from datetime import datetime import uuid from io import BytesIO import requests import re from django.core.files.images import ImageFile class Command(BaseCommand): help = "Import HTML content into Wagtail as ChangelogPost objects." def handle(self, *args, **kwargs): with open("subscription/migrateHTML/migrate.html", "r", encoding='utf-8') as f: html_doc = f.read() soup = BeautifulSoup(html_doc, 'html.parser') content = [] blog_divs = soup.find_all('div', class_='changelogItem published') for div in blog_divs: h2 = div.find('h2') content_div = div.find('div', class_='content') p = content_div.find('p') img_tags = content_div.find_all('img') img_htmls = [img.prettify() for img in img_tags] h3 = content_div.find('h3') if h3: span_text = h3.text.strip() # Get the content html, ignoring the img tag to_decompose = [] for child in p.next_siblings: soup = BeautifulSoup(str(child), 'html.parser') if … -
AWS SES VerifyEmailIdentity with lightsail
I am trying to use SES VerifyEmailIdentity in python. It works totally fine on my local systen however when we host on lughtsail instance the following error comes: An error occurred (AccessDenied) when calling the VerifyEmailIdentity operation: User: arn:aws:sts::480862114276:assumed-role/AmazonLightsailInstanceRole/i-0e2s3ff15c45e0eb1 is not authorized to perform: ses:VerifyEmailIdentity because no identity-based policy allows the ses:VerifyEmailIdentity action Python code working on localhost but having above error when hosted on lightsail import boto3 ses_client = boto3.client('ses', region_name='ap-south-1') def verify_email_address(email): response = ses_client.verify_email_identity(EmailAddress=email) return response I tried but their is no way to attach a role to lightsail instance in AWS through which i can attach permission. Expected result is just it works fine as on local and send email to intended address for verification. -
Elastic search with django parler
So i am trying to add Parler to my django application and it can't find a field that i want to index models.py class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' translations = TranslatedFields( header = models.CharField(max_length = 32) body = RichTextField() ) category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() language = models.ForeignKey(Language, related_name = "document_language", on_delete = models.CASCADE) def __str__(self): return self.header documents.py for elastic search: from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from . import models @registry.register_document class DocDocument(Document): class Index: name = 'documents' settings = { 'number_of_shards':1, 'number_of_replicas':0 } class Django: model = models.Document fields = [ 'header' ] the error it throws: Document has no field "header" I tried to do it with other fields that are not in translations but it throws the same error: Document has no field "whatever_field_i_have_used" -
Integration of WhatsApp with Python Django
I am currently working on a project that involves incorporating WhatsApp functionality into our web application developed using the Django framework. I am reaching out to inquire about the integration of WhatsApp with a Python Django project. I Want Whatsapp Business API Integration in Django -
importerror: couldn't import djano in windows powershell. im also using vscode [duplicate]
when i enter in WINDOWS POWERSHELL, PS C:\djangoapps\test\venv\src> **python manage.py startapp **stockmgmt, there's an error: importerror couldn't import django. are you sure it's installed and available in your PYTHONPATH environment variable? did you forget to activate a virtual environment? how to solve this? -
Difficulty with Django Rest Framework (DRF) Swagger Authentication Configuration
I'm encountering issues with configuring authentication for the Swagger in Django Rest Framework. I've set up the drf_yasg package along with the necessary configurations in settings.py and urls.py. However, when I try to log out using the Swagger, I'm getting a 403 Forbidden error, and subsequent attempts to access Swagger result in a blank page. settings.py: SWAGGER_SETTINGS = { 'SECURITY_DEFINITIONS': { 'basic': { 'type': 'basic' } }, 'LOGIN_URL': 'rest_framework:login', # Configuring login URL for Swagger 'LOGOUT_URL': 'rest_framework:logout', # Configuring logout URL for Swagger } REDOC_SETTINGS = { 'LAZY_RENDERING': False, } urls.py from django.contrib import admin from django.urls import path, include from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions API_TITLE = "Blog API" API_DESCRIPTION = "A Web API for creating and editing blog posts." # Configuration for drf-yasg schema_view = get_schema_view( openapi.Info( title=API_TITLE, default_version='v1', description=API_DESCRIPTION, ), public=True, permission_classes=[permissions.IsAuthenticated], # Setting permission for the schema_view ) urlpatterns = [ # Routes for admin views and API # ... (other routes) # Routes for Swagger UI documentation in different formats path('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), # Route for ReDoc documentation path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] I've configured the LOGIN_URL and LOGOUT_URL in SWAGGER_SETTINGS and used permission_classes=[permissions.IsAuthenticated] for … -
How to design my Django app database to accommodate multiple level information of an item?
I am trying to create an app on Django. Struggling on how to proceed on Database schema. There are the following tables: 1), table customer: cust_name cust_addr cust_phone created_date ... 2), table customer_assets customer (foreign key pointed to table customer) asset_type asset asset_update_time asset_creation_time ... The major issue is on asset, asset_type, sample data like below: asset_type asset domain aaa.bb.example.com domain *.corp.example.com ip 10.1.2.3 ip 10.8.0.0/16 url http://aaaa url http://bbbbb url http://aaa.bb.example.com/app1/login email xxx@example.com there are some assets like *.corp.example.com, 10.8.0.0/16. The app is supposed to do a discovery and find more assets under them, for example: aaa.corp.example.com bbb.corp.example.com ccc.corp.example.com 10.8.2.2 10.8.2.3 ... The app is then going to scan the open ports on each of them, like: aaa.corp.example.com. (22, 80, 1080) 10.8.2.2 (21, 139, 3306) the app may then scan every ports on the assets to find urls, like: aaa.corp.example.com 80 /home.html aaa.corp.example.com 80 /admin.html bbb.corp.example.com 443 /console Note that: data in customer_assets is basically provided by customer data in customer_assets contains data of various types, for example, 1), wildcard sub domains (.corp.example.com) and exact subdomains (aaa.bb.example.com). 2), exact subdomains in wildcard sub domains (.corp.example.com) will later be discovered what's the best way to organise the database schema? 1), … -
Warrning from unittest on models.DateTimeField with auto_now=True
I got model in Django 4.2.1 that has an autofield updated each time anytching is changed in record. Implemented only by this one line: last_modification = models.DateTimeField(auto_now=True, editable=True) In PGAdmin I see correct created records. And in standard usage I got no warnings inside container terminal. But whent I run tests by command inside container "python manage.py test" I recieve warnings like: warnings.warn( /usr/local/lib/python3.11/site-packages/django/db/models/fields/init.py:1595: RuntimeWarning: DateTimeField SMSNotification.last_modification received a naive datetime (2024-02-02 13:46:49.356514) while time zone support is active./bin/sh: 3: Syntax error: newline unexpected (expecting ")") warnings.warn( /usr/local/lib/python3.11/site-packages/django/db/models/fields/init.py:1595: RuntimeWarning: DateTimeField SMSNotification.last_modification received a naive datetime (2024-02-02 13:46:49.356514) while time zone support is active. Is this a common unittest problem or my implementation of model? If should be ignored, can I configure test framework to avoid printing the warning? -
Trying to lay out a variable number of cards per row with Django and Bootstrap
I have a variable number of items on Bootstrap cards that I will be laying out (maybe 100). I want to lay this out to put as many per row as will fit (let's assume fixed width). On a larger screen, I should get | 1 2 3 4 | On a smaller one: | 1 2 | | 3 4 | I'm looping through the item with a for loop in a Django template. Every method I've found assumes that the server will have a preset number of columns in the row. This makes no sense to me, as I want to set the with for readability (like 20em), and then put as many items per row that fit. This is what I have, it doesn't work. <div class="container-fluid"> <div class="row"> {% for person in people %} <div class="row"> <div class="card width=25%"> <img class="teacher-pic card-img-top" style="float:left; margin: 0 15px 0 0;" src="{{ person.person_photo_url }}"/> <div class="card-body"> <h5 class="card-title">{{ person.person_name }}</h5> <p class="card-text">{{ person.person_description }}</p> </div> </div> </div> {% endfor %} </div> </div> -
Django Busy GPIOs Raspberry Pi 5
When trying to interface with the GPIO of the RPi 5 using gpiozero, I am running into an error stating that the GPIO is busy. The context is that I am running this code in a Celery task in Django. The issue is similar to this, but the fix provided did not work in this context. -
Triggering Python Function on Django + React
I am attempting to send data from my React frontend to a Django backend and trigger a function. I'm developing a Django REST API using Django Rest Framework, and I've set up a view in the calculator app to handle POST requests. The objective of the calculator view is simply concatenate text from frontend: #app/calculator/views.py from django.http import JsonResponse def concat_text(request): if request.method == 'POST': received_text = request.POST.get('text', '') result = received_text + ' =)' print(result) return JsonResponse({'result': result}) else: return JsonResponse({'error': 'Only POST requests are allowed'}) However, when I make a request from my React frontend, I'm receiving a 403 error (Forbidden). I am sending the text value via frontend by: const handleButtonClick = async (e) => { e.preventDefault(); try { const response = await fetch(`${URL}/calculator/calculator/`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ text }), }); The URL is simply the "http://localhost:8000". I have also defined the calculator urls: #app/calculator/urls.py from django.urls import path from .views import concat_text urlpatterns = [ path('calculator/', concat_text), ] My app urls: #app/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView from core import views as core_views … -
Unable to Store data in order placed table and deleting data from cart table after completion of payment
4 i am using razorpay payment gateway web integration for my learning eccomerce project everyhing work fine payment can be done all i want is to store my cart data in OrderPlaced table and delete the cart data from Carts table and redirect the page on home after payment done in my order model using test mode. but in this code something is wrong after payment completion Nothing happen no changes nor in Carts table neither in OrderPlaced table. This is my Checkout View for the payment initiation class checkout(View): def get(self, request): user = request.user add = Customer.objects.filter(user=user) cart_items = Cart.objects.filter(user=user) famount = 0 for p in cart_items: value = p.quantity*p.product.discounted_price famount = famount+value totalamount = famount+30 razoramount = int(totalamount * 100) client = razorpay.Client( auth=(settings.RAZOR_KEY_ID, settings.RAZOR_KEY_SECRET)) data = {"amount": razoramount, "currency": "INR", "receipt": "order_rcptid_12"} payment_response = client.order.create(data=data) print(payment_response) order_id = payment_response['id'] order_status = payment_response['status'] if order_status == 'created': payment = Payment( user=user, amount=totalamount, razorpay_order_id=order_id, razorpay_payment_status=order_status ) payment.save() return render(request, 'app/checkout.html', locals()) And this is my paymentDone View here i try to store all cart items in OrderPlace table and delete item from the Cart table.. def payment_done(request): order_id = request.GET.get('order_id') payment_id = request.GET.get('payment_id') cust_id = request.GET.get('cust_id') user = … -
Handling Multiple dependent drop down lists in a form using Django and jquery
I want to create a form with 4 drop down list in which two of them are dependent on the other two, example i have a country and city drop list in which the city is dependent on the country i.e. when a country is selected only cities in that country will show in the city drop down and its working perfectly but my department and unit are not working as expected. I wand same for my department and units, if a department is selected only units in that department should show. I want to implement this in one form. <form method="post" enctype="multipart/form-data" autocomplete='off' class="mt-3" novalidate id="personForm" data-cities-url="{% url 'ajax_load_cities' %}" data-units-url="{% url 'ajax_load_units' %}"> <div class="row"> <div class="col-3">{{ form.country|as_crispy_field}}</div> <div class="col-3">{{ form.city|as_crispy_field}}</div> <div class="col-3">{{ form.department|as_crispy_field}}</div> <div class="col-3">{{ form.unit|as_crispy_field}}</div> </div> <script> $("#id_country").change(function () { const url = $("#personForm").attr("data-cities-url"); const countryId = $(this).val(); $.ajax({ url: url, data: { 'country_id': countryId }, success: function (data) { console.log(data); $("#id_city").html(data); }); } }); }); $("#id_department").change(function () { const url = $("#personForm").attr("data-units-url"); const departmentId = $(this).val(); $.ajax({ url: url, data: { 'department_id': departmentId }, success: function (data) { console.log(data); $("#id_unit").html(data); } }); }); </script> -
htmx: hx-target-error fails when hx-target defined (django python)
I am using the htmx extension "response-targets" via "hx-ext" in a python django project. The Problem "hx-target-error" will not work when "hx-target" is also defined, but works when it is the only target. Environment htmx 1.9.10, response-targets 1.9.10, python 3.12, django 5.0.1 Example html: <div hx-ext="response-targets"> <button hx-get={% ur "appname:endpoint" %} hx-target-error="#id-fail" hx-target="#id-success" type="submit" > Press Me! </button> </div> hx-target Have tried with various other type of targets such as "next td", "next span", etc. All of them produce value "request.htmx.target" values in the endpoint defined in views.py. hx-target-error Have also tried various alternatives supported in response-targets such as "hx-target-*", "hx-target-404", etc with no change in results. I verified that "response-targets" is installed correctly and being used correctly because when "hx-target" is removed from the "button", then "hx-target-error" works. Error generation in views.ph @login_required def endpoint(request) return HttpResponseNotFound("Not found 404") Logs Bad Request: /testbed/endpoint/ 127.0.0.1 - [27/Feb/2024] "GET /testbed/endpoint/ HTTP/1.1" 400 response-targets extension https://htmx.org/extensions/response-targets/ -
Could anyone tell me the step by step process to implement this project?
𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 : Language translator tool to convert English to Hindi (official Language) which can be used by all the government organizations websites officially. 𝗗𝗲𝘀𝗰𝗿𝗶𝗽𝘁𝗶𝗼𝗻 : The objective is to develop a language translator tool specifically designed for government organizations in India. The tool should provide the capability to translate English content into Hindi, the official language of the country. This will enable government websites to cater to a wider audience, including Hindi-speaking citizens who may have difficulty understanding English. The language translator tool should possess the following key features: Translation Accuracy: The tool should offer accurate translations, maintaining the context and meaning of the original English content. It should handle various language intricacies, idiomatic expressions, and technical terms commonly used in government-related documents. User-Friendly Interface: The tool should have a simple and intuitive interface, ensuring ease of use for both website administrators and end-users. It should seamlessly integrate into government websites, allowing users to translate content with minimal effort. Website Integration: The language translator tool should be compatible with different website architectures and frameworks commonly used by government organizations. It should provide developers with an API or plugin that can be easily integrated into existing websites without significant code … -
Joining Tables in Django ORM with Left Outer Join and Additional Condition
I'm trying to perform a left outer join between two models in Django using the ORM. I need to include an additional condition within the ON clause of the join to filter the results based on specific criteria. from django.db import models class Author(models.Model): id = models.BigIntField(primary_key=True) name = models.CharField(max_length=50) book_title = model.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE, null=True, db_column='author') Is there a way to retrieve all the book objects along with the name of the author where the title and book_title are equal. The sql will look like: select title, author, name as author_name from book left outer join author on (book.author = author.id AND book.title = author.book_title) Since the table is very large ( 13m ) I cannot resort to raw query because I will lose the ability to use PageNumberPagination. I don't want to use extra because this may lead to problems in future. Is there any other way I can achieve the above sql using django orm?? -
Django project deployment on Vercel got me an error
I have created a simple blog application using django and postgres database. While I wants to deploy to vercel it throws a different errors like this error error How can i solve this error? build_files.sh pip install -r requirements.txt python3.10 manage.py collectstatic vercel.json { "version": 2, "builds": [ { "src": "blog/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.10" } }, { "src": "build_files.sh", "use": "@vercel/static-build", "config": { "distDir": "staticfiles_build" } } ], "routes": [ { "src": "/static/(.*)", "dest": "/static/$1" }, { "src": "/(.*)", "dest": "blog/wsgi.py" } ] }``` I have build_files.sh and vercel.json. I think there is no problem. I also have requirements.txt file. Pushed to github and tried deployment but no progress at all. -
django.core.exceptions.FieldDoesNotExist: Document has no field named 'header'
So, i am trying to add parler to my models in order to translate them. models.py from django.db import models from django.utils.translation import gettext_lazy as _ from ckeditor.fields import RichTextField from parler.models import TranslatableModel, TranslatedFields from simple_history.models import HistoricalRecords class Document(TranslatableModel): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' translations = TranslatedFields( header=models.CharField(_("Header"),max_length = 32), body=RichTextField() ) category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header so basically it says that it has no header field, but when i add it outside of the translations it says that it ALREADY HAS header field. How do i fix it? -
Some example schemas on swagger not displaying
New over here.. Has anyone encountered a problem that occurs in swagger where it shows some specific number of urls with their properties and example schemas. While for the rest it just gives the default value "string". E.g If I have a total of 70 urls for the first 30 urls it gives the accurate example schemas while for others it just gives "string" as the example schema My swagger UI The "string" Example value then shows up for all urls after the api/user/verify I have tested both drf_yasg and drf-spectacular but got the same result