Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django automatic conversion/casting when doing lookups
Could someone explain to me where I can find information about why this works in Django? I did some research in the official documentation and couldn't find anything. from django.db import models class Document(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) # Query using an integer document1 = Document.objects.get(id=1) # Query using a string that can be converted to an integer document2 = Document.objects.get(id='1') # Both queries should yield the same result I check this pages in the official documentation: https://docs.djangoproject.com/en/5.0/ref/models/fields/#model-field-types https://docs.djangoproject.com/en/5.0/topics/db/queries/ https://docs.djangoproject.com/en/5.0/ref/models/lookups/ -
Using Records from One Model in Another Model's Column in Django
I Want to Using Records from One Model in Another Model's Column in Django in the Following Code: The Code Says a Model that Add Products as Record and I want to add a model that gives me a Product Records as Column and integer value for giving order. For Example: I Have Apple and Orange in my records and i want to have a model to order 3 Apple and 5 Orange. Note: If I add another Product Record, It Must Add Another Column in Order Model. My Product Model Code is this: class Product(models.Model): name = models.CharField(max_length=255) priceWholeseller = models.IntegerField() priceSeller = models.IntegerField() def __str__(self): return self.name -
Django urlpatterns including / at the back
I'm a student learning Django. I have a question and I'd appreciate it if someone could help me. When I navigate to 127.0.0.1:8000/feeds/1, it correctly displays the feed with ID 1. However, I encounter an issue when I navigate to 127.0.0.1:8000/reviews/1, and I get the following error says page not found This problem can be resolved by adding a slash in the reviews/urls.py path section like this: "int:review_id/". My question is: why does the feeds URL work without the trailing slash in the urlpatterns, but for reviews I have to include the trailing slash to make it work? here is the main urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path("admin/", admin.site.urls), path("feeds/", include('feeds.urls')), path("users/", include('users.urls')), path("reviews/",include('reviews.urls')) # path("boards/", include('boards.urls')) ] # feeds/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.Feeds.as_view()), path("<int:feed_id>",views.FeedDetail.as_view()) ] # reviews/urls.py from django.urls import path from . import views urlpatterns = [ path("", views.Reviews.as_view()), path("<int:review_id>/", views.ReviewDetail.as_view()) ] -
I want to install Docker Desktop for Windows 11
After installing Docker, when I run Docker I get an error "wsl --update" And when I run the code "wsl --update" in 'windows powershell' I get an error: "The service cannot be started, either because it is disabled or because it has no enabled devices associated with it" What is the problem? -
Why doesn't DataDog show BEGIN queries?
I am using DataDog with a Django site running on gunicorn with a Postgresql database. We have atomic DB transactions enabled by default. Postgres and Python traces are both configured per the DataDog documentation. In DataDog we can see the Postgres spans for the transaction COMMIT queries, but the transaction BEGIN queries are missing. I am trying to debug some performance issues with our site and would like to see if the BEGIN queries are somehow at fault, but it's nearly impossible to confirm this when they aren't showing up in DataDog. How do I get the transaction BEGIN queries to show in DataDog? This is a screenshot of a trace from the /health endpoint, which executes zero SQL queries but is still wrapped in a DB transaction. You can see that most of the response time is a black hole where I cannot see what is happening. This trace was only 9ms, but sometimes this delay can take up to 10 seconds which is totally baffling. -
Is there an way to go around the "Field 'id' expected a number" when dealing with a queryset?
I am working on a learning platform. I want to be able to track user progress of the chapters completed. I cerated a new model and inserted it into the html using a form. However when I submit, I keep getting a TypeError with the specifics that "Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['YMvOO6ZYGWVVfxfgoFLVEanZ9zK70CrqlRIx5Y2LOkbzH8Mx3UHPlQYczqLbq1Qt'], 'chapter': ['2'], 'completed': ['on'], 'student': ['1']}>" I tried converting all the variables I was using to identify the user, student and chapter to their primary keys but I got even more complicated error. If there is an easier way to track the progress or a tutorial on a way to do it, please share. Here's what I tried This is he StudemtProgress Model class StudentProgress(models.Model): student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="student_progress" ) chapter = models.ForeignKey( Chapter, on_delete=models.CASCADE, related_name="student_progress" ) completed = models.BooleanField(default=False) This is the form. Some of the code is to pick only the current logged in user and the chapter of th page that it is being displayed. class StudentProgressForm(forms.ModelForm): class Meta: model = StudentProgress fields = ("chapter", "completed", "student") # widgets = { # "student": forms.HiddenInput(), # } def __init__(self, user, student_slug, chapter_slug, *args, **kwargs): super(StudentProgressForm, self).__init__(*args, **kwargs) student_queryset = … -
Error 403 while running Docker image on Windows, but works on RHEL8
I have a web application made in Django, I build it and run it in Linux Redhat 8 and it works fine. Trying to run it on Windows using Docker allows me to get into webpage, but I can't login, I just get [POST] Error 403 (Forbidden), But the image is the same at both envs. I'm accesing it via 127.0.0.1:8000, which is CSRF Enabled in settings.py and in ALLOWED_HOSTS and works on RHEL8, but doesn't allow me to login on Windows (same for 0.0.0.0:8000 and localhost:8000) How I run it in both environments docker run -it --rm -p 8000:8000 my_image_name Dockerfile: FROM my_image_repo ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY . /app/ EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] settings.py: CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', 'http://0.0.0.0' ] ALLOWED_HOSTS = [ 'http://localhost', 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://127.0.0.1', 'http://0.0.0.0', 'localhost', '0.0.0.0', 'localhost:8000', '127.0.0.1', '127.0.0.1:8000' ] Are there any firewall settings I need to change for it to allow me to do that on windows? I usually work on Linux only, but company requires me to make this work on Windows as well I tried adding more URLS to ALLOWED_HOSTS and CSRF, as well as I added to settings.py this line: SECURE_PROXY_SSL_HEADER = … -
How to fix Constant Errors When Implementing Google OAuth Sign-in with Django
I decided to put a google sign in method into my Django website, but I have been encountering errors related to the social_auth_app_django library. For example, at first I got a ValueError (Expected 2 got 1) from one of the utils.py in the library code. Note that I am new to adding google sign in to a Django application. Here are my version specifications: Django version 4.2.13 Python version 3.10.5 social_auth_app_django library version 5.4.1 Here is my settings.py (note that the API keys will be hidden for security purposes) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "games.apps.GamesConfig", "account.apps.AccountConfig", "forums.apps.ForumsConfig", "play.apps.PlayConfig", "make_game.apps.MakeGameConfig", "administration.apps.AdministrationConfig", "bootstrap5", "payments.apps.PaymentsConfig", "social_django" ] 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', 'account.middleware.DeviceDetectionMiddleware', # "django.middleware.debug.DebugMiddleware", 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'superstarstudios.urls' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = "my-google-key" SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = "my-google-secret" SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "email", ] AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2' ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates" ], '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', 'account.context_processors.device_type', "social_django.context_processors.backends", 'social_django.context_processors.login_redirect' ], }, }, ] LOGIN_REDIRECT_URL = "/games" LOGOUT_REDIRECT_URL = "/" SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'account.pipeline.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) Here is the function where the main ValueError is … -
Django: subclass, separate class or entirely separate classes
I'm building a forum app in Django as a learning project. I'm unsure of how to approach the creation of Post objects. I want users to be able to post threads (i.e. new topic), I want users to be able to post replies to those threads as well as replying to other replies. I want to include features like reactions to posts, and replies. I'd appreciate some feedback on the different approaches I'm considering: My thinking is that, since the two types of posts are so similar, they should inherit common fields/methods from a parent class. I'm unsure how Django would represent that in the DB tbh. Intially this was an abstract class class Post(models.Model): post_body = models.TextField(max_length=2000) publish_date = models.DateTimeField("date posted") author = models.ForeignKey(User, on_delete=models.CASCADE) class ThreadPost(Post): post_title = models.Charfield(200) is_solved = models.BooleanField("is_issue_solved", default=False) class ReplyPost(Post): is_solution = models.BooleanField("is_this_the_solution", default=False) thread_post = models.ForeignKey(ThreadPost, on_delete=models.CASCADE) Later I started using this, based on a stackoverflow response. However, I'm finding it a bit clunky to work with, as I often have to filter by whether a post is a thread or a reply, and have to find the thread which a post replies to. In that case, just having seperate classes seems … -
Protecting publicly accessable endpoints in Django and React
I have an endpoint urls.py from django.urls import path from . import views app_name = 'Main' urlpatterns = [ path("helloKitty/", views.helloKitty, name='helloKitty'), ] views.py def helloKitty(request): hello = pd.read_csv('static/data/helloKitty_data.csv') hello = hello.to_json(orient='records') return HttpResponse(hello) It's currently accessible by anyone at /helloKitty and it needs to be prevented. I use React on the front-end to access this endpoint and retrieve the data import React from "react"; import { create } from 'zustand'; import axios from 'axios'; const kittyStore = create((set) => ({ kitten: [], fetchKitty: async () => { const response = await axios.get('/helloKitty'); const hello = response.data.map((h) => { return { name: h.name, age: h.age, } }); set({ kitten }) }, })); export default kittyStore; The endpoints /helloKitty needs to be protected from being publicly accessible, and just the React app can view and fetch the data. -
Django REST 404 sending params in the url
Good day, I'm having problems with django/ django rest apí Back: url(r'^' + baseurl + etl + eph + 'salud_folder_xls/listar/<str:accion>/', etlEPHSaludXLSListar), url(r'^' + baseurl + etl + eph + 'salud_folder_xls/descargar/(?P<nombre_archivo>.+\\.xls)', etlEPHDescargarSaludFolderXLS), Front: const response = await axios({ url: '/etl/v1/eph/salud_folder_xls/listar/', method: 'GET', }); When I try salud_folder_xls/listar/ works fine but when I add accion, axios returns always ERROR 404 Any idea? -
Voucher Appears on Both Debit and Credit Sides in Sundry Creditors Ledger in Logistic Accounting Software
I am currently working on existing logistic company's accounting software.the sundry creditors ledger data function returning a single voucher entry twice: once on the debit side and once on the credit side. This behavior seems incorrect as the voucher should only be listed once.its only happening journal Vouchar entry for eg: - as you can see the 100 rs transaction effects on both dr and cr side its journal Vouchar entry rest of the vouchar types working perfectly def get_sundry_creditors_coa_response(coa, start_date, end_date, user): invoices = Invoices.objects.filter(date__range=[ start_date, end_date], invoice_type='Purchase', company__users__email=user.email).order_by('date') respone = [] res_obj = {} for invoice in invoices: cost_entrys = CostEntry.objects.filter( invoice__id=invoice.id, is_included=True) for cost_entry in cost_entrys: res_obj = { "account": invoice.client_name.name if invoice.client_name else "", "date": invoice.date, "currency": invoice.currency_sar, "invoice_number": invoice.invoice_number, "vat_percent": 0, "fcy_amount": 0, "vat_amount": 0, "amount": 0, "dr_amount": 0, "cr_amount": 0, "net_amount": 0, "type": "Invoice", "voucher": "", "party_account": invoice.party_account.name if invoice.party_account else "", "job_no": invoice.job.job_number if invoice.job.job_number else "", "narrations": invoice.narration if invoice.narration else "", "branch": invoice.branch if invoice.branch else "", "language_name": coa.language_name if coa.language_name else "" } fcy_amount = float( cost_entry.fcy_amount if cost_entry.fcy_amount else 0.0) amount = float(cost_entry.amount if cost_entry.amount else 0.0) vat_percent = float( cost_entry.tax_group_code if cost_entry.tax_group_code else 0.0) vat_amount = float((vat_percent * … -
How to override queryset for newly added fieldset in Django Admin Panel
I have added "permissions" fieldset in my User model on Admin Panel, but when I try to add a User it takes a lot of queries due to permissions (500) in my case, I am not able to optimize the code because get_queryset is not executing while adding an object. I want to know how can I fetch all related permissions in add user form, so it should fetch all select related permissions to optimize the admin panel interface. -
Get values from request
I am trying to write values from a request.POST to a string format. By default, these always start with "epochs-NUMBER-". Therefore, I should draw a For loop so that a new line is created for each number. The complete request looks like that. But I only need the 'epochs-NUMBER-' values csrfmiddlewaretoken=hJmSuP3O6GmtwBeJhfqb99LaCVOKxgngGNIEqoqhQQR7tQELUVGHeXRXxfnRE1Ah&base-TOTAL_FORMS=1&base-INITIAL_FORMS=0&base-MIN_NUM_FORMS=0&base-MAX_NUM_FORMS=1000&base-0-time=25.06.2024+13%3A36%3A00&base-0-show_differences=on&base-0-show_null=1&source=Manual&epochs-TOTAL_FORMS=3&epochs-INITIAL_FORMS=3&epochs-MIN_NUM_FORMS=0&epochs-MAX_NUM_FORMS=1000&unit_selector=m&unit_selector=m&unit_selector=m&unit_selector=m&epochs-0-target_name=250.01.G&epochs-0-easting=55555&epochs-0-northing=5555&epochs-0-height=555&epochs-0-azimuth=&epochs-0-zenithangle=&epochs-0-slope_dist=&epochs-1-target_name=170.01.G&epochs-1-easting=44646&epochs-1-northing=6554&epochs-1-height=544&epochs-1-azimuth=&epochs-1-zenithangle=&epochs-1-slope_dist=&epochs-2-target_name=150.01.G&epochs-2-easting=78979878&epochs-2-northing=4645&epochs-2-height=455&epochs-2-azimuth=&epochs-2-zenithangle=&epochs-2-slope_dist= The request looks like that: def nmea_string(self, request, target_name): my_dict = {} keys = [] values = [] target_raw_string = ("PTER," + self.short_name + "_TRG," + target_name + "," + self.time.strftime("%Y-%m-%d %H:%M:%S") + "," + str(self.status_target)) for key, value in request.POST.items(): keys.append(key) values.append(value) for i in range(len(keys)): my_dict.update({keys[i]: values[i]}) for k, v in my_dict.items(): if k.startswith('epochs-0-'): if v == '': v = '-9999.999900' if k.startswith('epochs-0-target_name'): target_raw_string += "," + v else: target_raw_string += "," + v + ",0.000000" tg_checksum = self.get_checksum(target_raw_string) tg_nmea_string = "$" + target_raw_string + "*" + tg_checksum + "\n" nmea_string += tg_nmea_string return nmea_string The end result should look a bit like this: $PTER,TS_TRG,TP-008,2024-04-22 23:00:00,129,675666.252000,0.000000,252132.398000,0.000000,412.137000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1F $PTER,TS_TRG,TP-009,2024-04-22 23:00:00,129,675704.440000,0.000000,252162.055000,0.000000,412.341000,0.000000,-9999.999900,0.000000,-9999.999900,0.000000,-9999.999900,0.000000*1A -
Error Decoding JSON Access Token for Daraja API When Hosting Web Service on Render
i am trying to deploy my api on render as a webservice... i have the same code in my local machine as in my git repo from which i building the service to deploy . on the deployed site hosted on render, when i send a post request to daraja api (an mpesa mobile payment natively fom kenya) i get an internal server error with this as the message JSONDecodeError at / Expecting value: line 1 column 1 (char 0) Request Method: POST Request URL: http://rycha-pay.onrender.com/ Django Version: 5.0.6 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: /opt/render/project/src/.venv/lib/python3.11/site-packages/requests/models.py, line 978, in json Raised during: mpesa_client.views.pay Python Executable: /opt/render/project/src/.venv/bin/python Python Version: 3.11.9 Python Path: ['/opt/render/project/src/django_mpesa_payments', '/usr/local/lib/python311.zip', '/usr/local/lib/python3.11', '/usr/local/lib/python3.11/lib-dynload', '/opt/render/project/src/.venv/lib/python3.11/site-packages'] Server time: Tue, 25 Jun 2024 10:18:40 +0000 ... on the other hand hand the api works perfectly fine offline and i can send requests to daraja api from my local machine and get valid response as shown in this response body ...*{"MerchantRequestID": "f1e2-4b95-a71d-b30d3cdbb7a7541949", "CheckoutRequestID": "ws_CO_25062024132114897799004096", "ResponseCode": "0", "ResponseDescription": "Success. Request accepted for processing", "CustomerMessage": "Success. Request accepted for processing"}.... *this is the section of code that is being flagged `# Configure logging logger = … -
Is there any way to download files or folders from the public share URL of OneDrive belonging to other users (external resources)?
I have a requirement to download files from the public URL of any OneDrive file or folder belonging to another user using the Django framework. I have written the code, but it gives me an error when accessing the file_id. I am trying to access the file info from below code, but it is now working I have also give the and use msal library for the same #permission "Sites.Read.All", "Sites.ReadWrite.All", "Files.ReadWrite.All", "Files.Read.All" #code where the problem occurs file_info = get_drive_item_id(access_token, encoded_share_url) #code class DownloadView(APIView): def post(self, request): def encode_share_url(share_url): encoded_url = base64.urlsafe_b64encode(share_url.encode()).decode().rstrip("=") return f'u!{encoded_url}' def get_drive_item_id(access_token, share_url): url = f"https://graph.microsoft.com/v1.0/shares/{share_url}/driveItem" headers = { 'Authorization': f'Bearer {access_token}' } response = requests.get(url, headers=headers) response.raise_for_status() return response.json() def resolve_shortened_url(short_url): response = requests.head(short_url, allow_redirects=True) return response.url AUTHORITY = "https://login.microsoftonline.co`your text`m/tenant-id/" CLIENT_ID = "client_id" CLIENT_SECRET = "client_secret" SCOPES = ["https://graph.microsoft.com/.default"] link = request.data.get("link") # Initialize MSAL client application app = ConfidentialClientApplication(CLIENT_ID, authority=AUTHORITY, client_credential=CLIENT_SECRET ) result = app.acquire_token_for_client(scopes=SCOPES) if "access_token" in result: access_token = result['access_token'] headers = {"Authorization": f"Bearer {result['access_token']}"} encoded_share_url = encode_share_url(link) file_info = get_drive_item_id(access_token, encoded_share_url) # Resolve the shortened URL resolved_url = resolve_shortened_url(link) # Parse the file ID from the resolved URL parsed_url = urlparse(resolved_url) query_params = parse_qs(parsed_url.query) # Use the file ID … -
Why /static/ not showing up for /admin in Django project?
So I ahve been trying a bunch of things. settings look good to me but maybe I am missing something, need help. I use: PostegreySQL, Reddis, Celery beat, nginx, gunicorn. the problem: maybe its permission issue, maybe directories, I cannot figure it out. enter image description here [error] 280897#280897: *40433 open() "/app/crm_market/collected_static/grappelli/js/grappelli.min.js" failed (2: No such file or directory), client: 31.128.32.152, server: my_domen.com, request: "GET /static/grappelli/js/grappelli.min.js HTTP/1.1", host: "my_domen.com", referrer: "https://my_domen.com/admin/login/?next=/admin/" (venv) root@fuvscqxzga://root/CRM-WB# docker compose exec web ls -l /app/crm_market/collected_static/ total 12 drwxr-xr-x 6 www-data www-data 4096 Jun 25 09:15 admin drwxr-xr-x 4 www-data www-data 4096 Jun 25 09:15 debug_toolbar drwxr-xr-x 9 www-data www-data 4096 Jun 25 09:15 grappelli project structure: enter image description here settings.py: STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_ROOT = os.path.join(BASE_DIR, "collected_static") /etc/nginx/sites-enabled/default server { server_name my_domen.com; location /static/ { alias /app/crm_market/collected_static/; } location /admin/ { proxy_pass http://127.0.0.1:8000; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; listen 443 ssl; Dockerfile FROM python:3.9-slim WORKDIR /app/crm_market COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ["gunicorn", "--bind", "0.0.0.0:8000", "CRM-WB.wsgi:application"] docker-compose.yml services: db: image: postgres:latest … -
Django printing out a JSON file [closed]
I want to print out the json data in HTML file row by row, by just the specific data. But it print all of the data. Print just specific information, not whole document like it happens now. `def show(request): response = requests.get( 'https://api.twelvedata.com/stocks?country=pl').json() return render(request, 'index.html', {'response': response})` ` {% for k,v in response.items %} {{k.section}} :{{v}} {% endfor %}` -
django-import-export: Customizable storage not working with minio
Following the documentation, I'm trying to configure the library to store temporary import files from the admin page into a MinIO bucket. This is my STORAGES configuration: IMPORT_EXPORT_TMP_STORAGE_CLASS = "import_export.tmp_storages.MediaStorage" STORAGES = { "default": { "BACKEND": "django.core.files.storage.FileSystemStorage", }, "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.ManifestStaticFilesStorage", }, "import_export": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": os.getenv("PORTAL_S3_BUCKET_NAME"), "region_name": os.getenv("PORTAL_S3_REGION_NAME"), "access_key": os.getenv("PORTAL_S3_ACCESS_KEY"), "secret_key": os.getenv("PORTAL_S3_SECRET_KEY"), }, }, } I suppose that when I import a file from the admin page and reach the confirmation step, I should be able to see the file I'm trying to upload in the bucket, but that's not happening. Nothing is being uploaded. When not setting anything relative to storage and using the default host server storage, I can see the files in the host machine once I'm in the confirmation step, so I assume I should be able to see the file in the bucket as well once it's configured. I've also tried to debug the library, but I am not able to see any information regarding the connection to the bucket. The problem has nothing to do with the MinIO configuration. I've tried retrieving and uploading files to the bucket using Postman with the keys I use in the STORAGES dict … -
How to Override CSS and JS in Folium Map Implementation
All I want is to override the CSS of my Folium map. When I override the styles in my template, they do not reflect on my Folium map. However, when I edit the CSS in the browser's developer tools, it works. I edited the CDN of my Folium map (leaflet.css). Note that I did not manually add the leaflet CDN to my header; Folium automatically includes it. Views.py - Creating a Customized Folium Map from django.views import View import folium def create_map(): f = folium.Figure(width='100%', height='100%') m = folium.Map( location=[14.0000, 122.0000], tiles='https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}{r}.png', attr='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>', zoom_start=6, zoom_control=False, scrollWheelZoom=True, doubleClickZoom=False, ) f.add_child(m) return m Rendering the Map in Django Template class RegionalMalnutritionView(View): template_name = "gis_app/malnutrition_view/regional_pages.html" def get(self, request, *args, **kwargs): context = {} # Assuming 'coodinate_locations' is your GeoJSON data source serializer = RegionalLevelGeoJSONSerializer(coodinate_locations, many=True) geo_data = { 'type': 'FeatureCollection', 'features': serializer.data } folium_map = create_map() for feature in geo_data['features']: html_popup = generate_html_popup_malnutrition(feature) folium.GeoJson( geo_data, highlight_function=highlight_function, style_function=style_function, popup=folium.Popup(html=html_popup, max_width=500), tooltip=folium.features.GeoJsonTooltip( fields=['name'], aliases=['Region Name: '], labels=True, localize=True, sticky=False, style=""" background-color: #F0EFEF; border-radius: 3px; box-shadow: 3px; padding: 20px; """ ), name='Regional Levels', ).add_to(folium_map) context['folium_map'] = folium_map._repr_html_() return render(request, self.template_name, context) templates <div class="map-container">{{ folium_map|safe }} </div> "I want to … -
django_get_or_create doesn't let me create instances
I'm using ModelFactory through SubFactory and there was django_get_or_create Meta field with ('code') inside. I put my 2 new added to model fields to this field django_get_or_create and it literally stopped making countries with 'RU' code and didint fill my array? There's an issue with this field or im doing something really wrong? I did try to search for similar problem but didn't find anything [ class ModelFactory(DjangoModelFactory): code = "RU" predefined_amounts_one_time = [500, 1000, 3000] predefined_amounts_recurring = [500, 1000, 3000] class Meta: model = Model django_get_or_create = ("predefined_amounts_one_time", "predefined_amounts_recurring", "code")] 1 this is what i get multiple times in tests when i try to print those fields: Turkey [] Turkey is an aliase to TR -
How to Quickly Calculate Days Since Latest Uncovered Sales
I have a large set of data for a company's sales and payments received. How can I quickly find the latest sale that cannot be covered by the total payments for each customer? Eg. Suppose the data table looks like this Date Customer ID Type Amount 2024-01-01 1 SALE 100 2024-01-08 1 PAYMENT 50 2024-01-15 1 SALE 100 2024-01-22 1 PAYMENT 100 2024-01-02 2 SALE 200 2024-01-09 2 SALE 200 2024-01-16 2 PAYMENT 150 For Customer 1, it would be 2024-01-15, since total payment amount is 150, so the first sale gets covered; And for customer 2, it would be 2024-01-02, since the only payment cannot cover its first sale. So far I use a window function to compute the cumulative sales and total payments. Then use this generated table to compute the latest uncovered sale, and other statistics. with cumsum_entry as ( select id, date, customer_id, type, amount, sum(amount) filter (where type='PAYMENT') over win_customer - sum(amount) filter (where type='SALE') over win_cumsum as cover from entry window win_customer as (partition by customer_id), win_cumsum as (partition by customer_id order by date rows between unbounded proceeding and current row) ) select customer_id, sum(amount) filter (where date >= '2024-01-01') as monthly_total, min(date) filter … -
Django django.contrib.auth.urls auth - redirect after login
Using python 3.11.9 and Django 5.0.6. I don't have a login/authentication function in views.py that I can write code of desired redirect in. I am using django.contrib.auth.urls for authentication. How do make Django redirect user after successful authentication? I want the user to be redirected to /test after authentication. urls.py urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), path('admin/', admin.site.urls), url('test', views. Test, name='test'), url('', views.home, name='home'), ] views.py @csrf_protect def home(request): return render(request, 'landing.html') @csrf_protect def test(request): if request.user.is_authenticated: return render(request, 'test.html') else: return redirect('/') -
ValueError: The view cart.views.cart_add didn't return an HttpResponse object
I am sure this may have been addressed. I am having this issue for the past week and cannot get past it. I have tried all possible solutions in every site I could find. I would appreciate some help. Thank you here is my error on the console and code ValueError: The view cart.views.cart_add didn't return an HttpResponse object. It returned None instead. from django.shortcuts import render, get_object_or_404 from .cart import Cart from store.models import Product from django.http import HttpResponse, JsonResponse from django import template from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse def cart_summary(request): cart = Cart(request) return render(request, 'summary.html', {'cart': cart}) def cart_add(request): # Get the Cart cart = Cart(request) # test to POST if request.POST.get('action') == 'post': # get Stuff product_id = int(request.POST.get('product_id')) # lookup product in DB product = get_object_or_404(Product, id=product_id) # save to Session cart.add(product=product) # Return a reponse cart_quantity = cart.__len__() # Return Repesponse # response = JsonResponse({'Product Name ': product.name}) response = HttpResponse({'qty ': cart_quantity}) return response def cart_delete(request): return def cart_update(request): pass I have tried everything under the sun -
function' object has no attribute 'objects'
Exception Type:AttributeErrorException Value:'function' object has no attribute 'objects'Exception Location:C:\Users\abdullohdev\Desktop\Projects\koram\main\views.py, line 110, in contact_us <div class="col-xxl-8 col-xl-9 col-lg-10"> <form method="POST" action="{% url 'contact-us' %}" class="contact-form text-center"> <div class="row"> <div class="col-md-6"> <div class="form-grp"> <input name="name" type="text" required placeholder="Ism va Familiyangiz"> </div> </div> <div class="col-md-6"> <div class="form-grp"> <input name="email" type="email" required placeholder="Elektron pochta manzilingiz"> </div> </div> <div class="form-grp"> {% csrf_token %} <textarea name="message" id="message" required placeholder="Xabar"></textarea> </div> </div> <button type="submit" class="btn">Yuborish</button> </form> </div> My contact page def contact_us(request): if request.method == "POST": email = request.POST.get('email') name = request.POST.get('name') message = request.POST.get('message') e = contact.objects.create(ism=name, email=email, msg=message) e.save() text = 'Xabar\n Email: '+email+'\nIsm: '+name+'\nXabar : '+message url = 'https://api.telegram.org/bot7349223445:AAEm_BVOUyH8pmHryWF_yJzcDko3NyRxe9M/sendMessage?chat_id=500919341' requests.get(url+'&text='+text) return redirect('index')