Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get foreign key related objects in Django
I have 3 models: class (models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name class AppealForm(models.Model): form_name = models.CharField(max_length=100) def __str__(self): return self.report_form_name class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE, blank=True, null=True) appeal_number = models.CharField(max_length=100, blank=True, null=True) applicant_first_name = models.CharField(max_length=100, blank=True, null=True) applicant_second_name = models.CharField(max_length=100, blank=True, null=True) date = models.DateField(blank=True, null=True) appeal_body = models.TextField() Objects of models: **Organization** |#|name| |-|-| |1|Apple| |2|Samsung| |3|Dell| AppealForm |#|form_name| |-|-| |1|Written| |2|Oral| Appeal |#|organization|appeal_form|appeal_number|applicant_first_name|applicant_second_name|date|appeal_body| |-|-|-|-|-|-|-|-| |1|Apple|Written|abc1|Oliver|Jake|06/22/2023|Test appeal body text| |2|Apple|Oral|abc12|Jack|Connor|05/22/2023|Test appeal body text| |3|Apple|Oral|abc123|Harry|Callum|04/22/2023|Test appeal body text| |4|Dell|Written|abc1234|Charlie|William|03/22/2023|Test appeal body text| |5|Dell|Oral|abc12345|George|Reece|02/22/2023|Test appeal body text| I want to generate a table like this below querying from Organization model: | # | Organization | Total amount of appeals | Written appeals amount | Oral appeals amount | | - | --- |--- |--- |--- | | 1 | Apple | 3 | 1 | 2 | | 2 | Samsung | 0 | 0 | 0 | | 3 | Dell | 2 | 1 | 1 | How the query will look like? Thanks in advance! -
Django Admin Panel: Page not found (404) after deploying to Vercel
I deployed my Django-Web-Application to Vercel. Everything works except opening the Add/Edit pages of specific models in the admin panel. I always get the error "page not found (404"). When I run the app on the local server, everthing works within the admin panel. I assume, that it has something to do with my App-Name "Aufträge" due to the "umlaut ä" in the name. But I don't know exactly. error I tried to compare the request url and the urls out of the application, But I can't understand why it is working in the test environmement. -
Avoid repetition of models in Django
I've a Django app that collects climatic data from different sources. Let's say for simplicity Temperature, Precipitation and Wind Speed, although in reality they are many more. I've a Django model for each of these magnitudes, representing a table that looks like (simplified version): datetime location id average 2022/3/10 10:25 1 27 2022/3/10 10:35 1 2022/3/10 10:37 2 9999 2022/3/10 10:40 3 27 With hundreds of thousands of rows, collecting data for many years and many locations, and growing. Now, this is the raw data: sometimes there is missing information (eg. row 2) and sometimes the data makes no sense (eg. row 3, with that 999). For this data to be useful for any purpose, it needs to be clean up and validated, and hourly, daily and monthly averages (for each location) calculated. The curated data has exactly the same fields that the raw data. So, I have 4 sets of identical models (raw, hourly, daily and monthly) for each of the magnitudes of interest, as well as identical filters and views. If this were just 3 magnitudes (Temperature, Precipitation and Wind Speed), it could be OK, but I have over 20 which results in A LOT of code repetition. … -
DJANGO: combobox doesn't print in textarea. Error in views.py or in html
In the home.html page I have a combobox and a textarea. I would like to achieve that if I click on an item in the combobox, using an (if) condition in views.py, I get the printout in the textarea. For example if I select "Red" then it must print "You chose red". Very simple. But there is something wrong with my code. It's probably the home.html file, or function def home in views.py file Problem: combobox(independent and not attached to a database) correctly browses items from list, but the condition doesn't apply. When I click on button, nothing happens. How can I execute the condition correctly and print in the textarea when I select the combobox item? I'm new to django, can you show me an answer with the code please? home.html <form method="post"> {% csrf_token %} {{ combobox }} <button type="submit">submit</button> </form> <form method="post"> {% csrf_token %} {{ textarea }} </form> views.py colours = ["Red", "Blue", "Black", "Orange"] @login_required def home(request): #Combobox if request.method == "POST": combobox = SimpleCombobox(request.POST) if combobox.is_valid(): print(combobox.cleaned_data) return redirect("home") else: combobox = SimpleCombobox() #TextArea if request.method == "POST": textarea = SimpleTextbox(request.POST) if textarea.is_valid(): print(textarea.cleaned_data) return redirect("home") else: textarea = SimpleTextbox() message = "" picked … -
django the second html page not concting to the existing one
i got the error , because I couldn't connect to other html pages, so please help me to debug the error. I want the output to show the connecting html page, but the out put idegate there is no such a path. app(view.py) from django.urls import path from django.views import View from .import views urlpatterns = [path('',views.index,name='index'), path('contact/', views.contact,name='contact') ] -
How to map Leaflet drawn objects (polygons, points etc.) to PostGIS entries?
I have a Leaflet map, Django project that uses it (template) and a PostGIS as DB. I am looking for a way to synchronize my Leaflet map with the underlying DB including support for loading, editing and deleting of DB entries directly in the web browser. Currently I have a single test table in the DB (beside the typical Django ones) that can be recreated using the following SQL script: CREATE TABLE public.test_pois ( id int8 NOT NULL GENERATED BY DEFAULT AS IDENTITY, geometry public.geometry(point, 4326) NOT NULL, prop_name varchar(128) NOT NULL, prop_description varchar(1024) NOT NULL, CONSTRAINT test_pois_pkey PRIMARY KEY (id) ); CREATE INDEX test_pois_geometry_1b8e72a8_id ON public.test_pois USING gist (geometry); The Model is as follows: from django.db import models import django.contrib.gis.db.models as gis_models class POI(gis_models.Model): geometry = gis_models.PointField() prop_name = models.CharField(max_length=128) prop_description = models.CharField(max_length=1024) class Meta: db_table = 'test_pois' Using map.on('pm:remove', (layer) => { console.log('Deleting action detected', layer); /* TODO Ajax DELETE request here */ }); in my template gave me an insight of what is passed around during the deletion procedure: layer: Object { _initHooksCalled: true, _popupHandlersAdded: true, _leaflet_id: 385, … } _eventParents: Object { 386: {…} } _events: Object { dragend: (1) […], click: (2) […], keypress: (1) … -
javascript fetch is fired double
I have a simple function in javascript that fetch and URL and update the HTML page when it got a response like: function post_db(self) { // other code here async function postData() { const url = "fetchnewseq" const response = await fetch(url, { method: 'POST', headers: { 'X-CSRFToken': csrftoken, 'Content-Type': 'application/json' }, body: JSON.stringify(comandi_json) }); return await response.json() } postData().then((data) => { window.location.replace(data.url); }); } The post_db function is fired by a button like <button onclick="post_db(this)" class="btn btn-success">Conferma</button> On the backend I'm using Django and the view that manages that URL is def fetch_new_seq(request): json_ricevuto = json.loads(request.body.decode("utf-8")) print(json_ricevuto) messages.success(request, "Ricevuto") redirect_url = reverse('newSeq') return JsonResponse({'url': redirect_url}) For some reason, the fetch is fired two times as I'm seeing the function on the backed with the same results two times I can't understand why it happens tho as, the button is clicked just one I'm also seeing on the console of Mozilla Browser I got the error Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. -
Django+DjangoRestFramework+React(TS): React-Image component showing my images' size as 1295x0
In Django; I have Group, Class, Model and Product as, well, models. These are in a hierarchy of Group{Class{Model{Product}}}. So I made dropdowns which works like: Group Checkbox |-Inner Classes of Selected Group |-Inner Models of Selected Class |-Inner Products of Selected Model (<Image> element here) The Product models has an image field, which is returned succesfully from the response.json. I can open the image files, e.g. http://localhost:8000/media/images/p1111.png. Its width is smaller than 1295px and its height is bigger than 0px, ofc. But in website it does not show. Then I open Chrome DevTools. Component is there, in component's source code <div>s and <img> are there, but image's size is shown as 1295x0. I open image url, it's smth like, 256x256. I can (of course) make image width 500x500 using CSS, but what if the use inputs an image with different image ratio and size? That will make it look worse or make the image show partially, so both possibilities are bad. So, can I solve it by changing the React part? Or I'm gonna write a function to Django part? index.tsx: import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; … -
Django error python raise ImproperlyConfigured
raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I added setting.configure() in every file -
Issue with generating access token in Django using Zendesk API
I'm working on a Django project where I need to integrate with the Zendesk API to generate an access token. I have implemented the following code, but I'm encountering an issue where the access token is not being generated correctly: class ZendeskAuthView(APIView): def get(self, request): parameters = urlencode({ "response_type": "code", "client_id": settings.ZENDESK_CLIENT_ID, "redirect_uri": settings.ZENDESK_REDIRECT_URI, "client_secret": settings.ZENDESK_CLIENT_SECRET, "scope": "tickets:read users:read organizations:read read", }) authorization_url = f"https://{settings.ZENDESK_SUBDOMAIN}.zendesk.com/oauth/authorizations/new?{parameters}" # Remove the extra whitespace before the URL authorization_url = authorization_url.replace('%22', '') return Response(authorization_url) class ZendeskCallbackView(APIView): def get(self, request): code = request.query_params.get('code') print(f"Authorization code: {code}") if not code: return Response({"error": "Missing authorization code."}) try: token_response = requests.post( f"https://{settings.ZENDESK_SUBDOMAIN}.zendesk.com/oauth/tokens", data={ "grant_type": "authorization_code", "client_id": settings.ZENDESK_CLIENT_ID, "client_secret": settings.ZENDESK_CLIENT_SECRET, "redirect_uri": unquote(settings.ZENDESK_REDIRECT_URI), "code": code, "scope": "tickets:read users:read organizations:read read", } ) except requests.exceptions.RequestException as e: print(e) return Response({"error": "An error occurred while retrieving the access token.",code:"code"}) access_token = token_response.json().get("access_token") if access_token: return Response({'access_token': access_token}) else: return Response({"error": "Failed to retrieve access token."}) # Add a default response if none of the conditions above are met return Response({"error": "Unexpected error occurred."})` I have verified that the authorization code is being received correctly in the callback view, but when I make a POST request to the Zendesk API to exchange the authorization … -
How to handle cors headers between a django backend and react js frontend
I am running my react js on frontend.domain.com and backend on backend.domain.com. I am trying to fetch the data from backend django api using the backend.domain.com url. But I am getting this error: Access to fetch at 'https://backend.domain.com/login/' from origin 'https://frontend.domain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. What settings should set in my django backend api like in settings.py or any other. Or in the frontend react js ? What changes should I do to access the resources of the django using frontend react js! How to handle that error and what changes should i make in backend to make access the frontend react js -
How to solve => NameError: name '_mysql' is not defined
I started a django project I made some models and migrations with sqlite3 but now want to use mysql and workbench to work with and after all installations when runing python manage.py migrate or python manage.py runserver I have that error, please help... I have properly installed mysql, mysqlclient and workbench and also this is the code on my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'storedb', 'USER': 'root', 'PASSWORD': '2E71Blue.8', 'PORT': 3306, 'HOST': '127.0.0.1', } } this is the traceback of the error Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 2): Symbol not found: _mysql_affected_rows Referenced from: /Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so Expected in: flat namespace in /Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/cecibenitez/.local/share/virtualenvs/storebackend-1ILPqCOa/lib/python3.10/site-packages/django/__init__.py", line 24, in setup … -
I edited css code in my django project and it did not change anyway if I dalete all my css code it is still working
I sited from my django project and it did not change and it remains same as when it has not edited css code. I do not understand why this is happening?? Then I deleted all css files to find out what is happening but I could not figure it out. -
How to get Category from Product? Django
I'm trying to create a search bar where user can choose Category and write product name. So I can display all products in that category where the name of product matches with what he wrote in text input. The problem is in subcategory. So I have Category -> Subcategory -> Product. Is there any way to get Category object from Product model?(I don't have field for category in product model) Here is my models.py file: # models.py class Category(models.Model): name = models.CharField(max_length=100, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Subcategory(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='subcategories') name = models.CharField(max_length=200, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) top5 = models.BooleanField(default=False, null=True, blank=True) featured = models.BooleanField(default=False, null=True, blank=True) class Meta: verbose_name_plural = 'Subcategories' def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=200, null=True, blank=True) subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name='products') image = models.ImageField(null=True, blank=True, upload_to='products/') price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True) price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True) description = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name # @property # def category(self): # return self.subcategory.category Here as you can see I tried to create a property to get the category, but now I'm struggling to filter … -
Django and React implementation
I'm trying to make django with react run in a single server, but i got a eror: terminal messaege browser error I don't know whats heppeing. this is my setting.py: from pathlib import Path from datetime import timedelta import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-@*5zxov(m66vfs_l)9pxk8ueq5jhq2cns0g^95(az+1l$!vo9%' DEBUG = False ALLOWED_HOSTS = ['127.0.0.1','localhost'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main.apps.MainConfig', 'rest_framework', "corsheaders", 'django_password_validators', 'django_password_validators.password_history', "phonenumber_field", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(days=1), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", } CORS_ALLOWED_ORIGINS = ['http://127.0.0.1','http://localhost:3000'] CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1','http://localhost:3000'] ROOT_URLCONF = 'backend.urls' BACKEND_DIR = BASE_DIR FRONTEND_DIR = BASE_DIR.parent / 'frontend' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR,'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', 'django.template.context_processors.request', ], }, }, ] WSGI_APPLICATION = 'backend.wsgi.application' DATABASES = { … -
Can I configure both ElasticSearch and ChromaDB in a single django application?
I have read the documenations https://docs.djangoproject.com/en/4.2/topics/db/multi-db/ but this page https://django-elasticsearch-dsl.readthedocs.io/en/latest/ describes how to use ElasticSearch. That doesn't seem to allow multi db with elastic search. I was also not able to find the settings for ChromaDB. I am trying to build an application that can use LLM via langchain and chroma db, but I have a data source in JSON that I want to store in elastic search. I am hoping to find a solution to use both elastic search for some models and chromadb for other models and potentially mysql for other models. Currently I am thinking two or three instances of Django applications with a shared vue application accessing the REST interfaces corresponding to the models. I would have one instance of django to handle user login and management and SSO for the other(s) -
Function of JavaScriput running on django doesn't work
I am trying to do a assignment that is provided CS50W. According to CS50W website, What I need to fix is only inbox.js file. Though I confirmed inbox.js file, I couldn't find a problem. A thing I want to do I tried to implement "send_email" function. But, the function doesn't work properly. Although accessing API Route "emails" (which is defined views.compose in urls.py) through fetchAPI, "send_email" function didn't work. The errors I got on Chrome are followings: POST http://127.0.0.1:8000/emails 500 (Internal Server Error) send_email @ inbox.js:142 VM297:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Promise.then (async) send_email @ inbox.js:151 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON Promise.then (async) send_email @ inbox.js:151 This is a result trying following debugging method result {"error": "POST request required."} debugging method I tried Inspect the network response: In Chrome Developer Tools, go to the "Network" tab, perform the action that triggers the fetch request, and look for the corresponding request in the list. Click on the request to view its details, including the response. Check the response content, headers, and status code to identify any issues. The unexpected < character in the response … -
HTML radio button and JAVASCRIPT API
I'm trying to make an API call using the input from the user using HTML radio's. While all the other imput fields are working, the radio field is giving me some trouble. This is the Javascript <script> function get_details() { let passenger_no = document.getElementById('passengers').value; let distance = document.getElementById('distance').value; let active = document.getElementById('activity_id').value; fetch('https://beta4.api.climatiq.io/estimate', { method: 'POST', headers: { 'Authorization': 'Bearer 7SFFXXXXSRJ63T8WZ2NADN0A', 'Content-Type': 'application/x-www-form-urlencoded' }, body: `{\n\t"emission_factor": {\n\t\t"activity_id": ${active},\n\t\t"data_version": "^1"\n\t},\n\t"parameters": {\n\t\t"passengers": ${passenger_no},\n\t\t"distance": ${distance},\n\t\t"distance_unit": "km"\n\t}\n}` }) .then(response => response.json()) .then(data => { console.log(data); }); } </script> And this is the html <h2>Calculate Emissions</h2> <p></p> <div class="inputBox"> <input type="number" id="passengers"> <label>Enter Number of Passengers:</label> </div> <div class="inputBox"> <input type="number" id="distance"> <label>Enter Distancs in km:</label> </div> {%for i in q %} <div class="form-check"> <input class="form-check-input" type="radio" id="activity_id" value="{{i.attributes}}"> <label class="form-check-label" for="inlineRadio1" style="color: whitesmoke;">{{i.name}}</label> </div> {%endfor%} <p></p> <button type="submit" onclick="get_details()" class="btn btn-success">Estimate</button> I'm getting the following error 'Error parsing the request body. Your JSON syntax is invalid: expected value at line 3 column 18' Can someone help me? -
Exception handling in Django/DRF
I want to check for correctness of request.data whenever there would be a POST request to 127.0.0.1:8000/api/v1/events/ Currently, I do have Event model class Event(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=250) price = models.IntegerField(default=0) created_by = models.ForeignKey(User, related_name='created_events', on_delete=models.CASCADE) guests = models.ManyToManyField(User, default=None, blank=True) categories = models.ManyToManyField('Category', default=None) event_type = models.CharField(choices=EventType.choices, max_length=10) created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) start_time = models.DateTimeField(auto_now=True) seats = models.IntegerField(default=0) I want to check if the user is submitted the required fields in the right format. Also, whenever there would be a PATCH request 127.0.0.1:8000/api/v1/events/{pk}. Then, updated_time, event_type should not be in the request.data (meaning that they should not be updated). How can I make sure that everything is correct in the request.data? It can be done by checking request_keys = request.data.keys() actual_keys = self.serializer_class().get_fields().keys() result = [x for x in request_keys if x not in actual_keys] if result: return Response({'error': 'Invalid data'}, status=400) But the problem is that, I do need to check for different fields whenever the request.method is different, like, POST and PATCH, .get_fields() will return just all the fields in serializer. However, for PATCH I should not have updated_time, event_type fields. Also, I need to make sure that all the request.data fields … -
How to translate url in Django?
This is my django-project below to translate from English to French. *I use Django 4.2.1: django-project |-core | |-settings.py | └-urls.py |-my_app1 | |-views.py | └-urls.py |-my_app2 └-locale └-fr └-LC_MESSAGES |-django.po └-django.mo And, this is core/settings.py below: # "core/settings.py" MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True from django.utils.translation import gettext_lazy as _ LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) And, gettext() is used to translate Test to Examen in my_app1/views.py as shown below: # "my_app1/views.py" from django.shortcuts import render from django.utils.translation import gettext as _ def test(request): # ↓ Here ↓ return HttpResponse(_("Test")) And, hello/world/ path for test() is set to urlpatterns in my_app1/urls.py as shown below: # "my_app1/urls.py" from django.urls import path from . import views app_name = "my_app1" urlpatterns = [ # ↓ ↓ Here ↓ ↓ path("hello/world/", views.test, name="test") ] And, my_app1/ path for my_app1 is set to urlpatterns with i18n_patterns() as shown below: # "core/urls.py" from django.urls import path, include from django.conf.urls.i18n import i18n_patterns urlpatterns = i18n_patterns( # ↓ Here ↓ path("my_app1/", include('my_app1.urls')) ) And, "Anglais", "Français" and "Examen" are set for "English", "French" and "Test" respectively in locale/fr/LC_MESSAGES/django.po as shown … -
DJANGO: combobox doesn't print in textarea
I'm new to Django. I have a combobox and a textarea. I would like to achieve that if I click on an item in the combobox, using a condition (if), I get the printout in the textarea. Very simple. But there is something wrong in my code. Problem: The combobox (independent and not attached to a database) correctly browses items from the list, but the condition doesn't apply. When I click the button, nothing happens. How can I execute the condition correctly and print in the textarea when I select the combobox item? Thank you home.html <form method="post"> {% csrf_token %} {{ combobox }} </form> <form method="post"> {% csrf_token %} {{ textarea }} <button type="submit">submit</button> </form> views.py colours = ["Red", "Blue", "Black", "Orange"] @login_required def home(request): #Combobox if request.method == "POST": combobox = SimpleCombobox(request.POST) if combobox.is_valid(): print(combobox.cleaned_data) return redirect("home") else: combobox = SimpleCombobox() #TextArea if request.method == "POST": textarea = SimpleTextbox(request.POST) if textarea.is_valid(): print(textarea.cleaned_data) return redirect("home") else: textarea = SimpleTextbox() message = "" picked = "" if request.method == 'POST': picked = request.form['colours'] if picked == 'Red': message = "<<< You chose red" elif picked == 'Blue': message = "<<< You chose blue" elif picked == 'Black': message = "<<< … -
djnago project showing source code instead of products
`When i am trying to diplay product via clicking on list instead of showing products it shows source code. This is following view.py which is i wrote but it is not working. but i think this code is perfect even i watch a tutorial and this code is from him but it is inch to inch copied from other guy but it is not working from me.... even im frustrated. View product = Product.objects.filter(title=val) title = Product.objects.filter(category=product[0].category).values('title') return render(request, 'app/category.html', context, locals()) This is url page even this url is just fine i checked all of item . URL path('category_title/<val>', category_title, name="category_title"), html {% block start %} <div class="container my-5"> <div class="row"> <div class="col-sm-3"> <div class="list-group"> {% for val in title %} <a href="{% url 'category_title' val.title %}" class="list-group-item list-group-item-action" aria-current="true">{{val.title}}</a> {% endfor %} </div> </div> <div class="col-sm-9"> <div class="row"> {% for prod in product %} <div class="col text-center mb-4"> <a href="{% url 'product_detail' prod.id %}" class="btn"> <div> <img src="{{prod.product_image.url}}" width="300px" height="200px"> <div class="fw-bold">{{prod.title}}</div> <div class="fw-bold text-danger"> RS. {{prod.discounted_price}}/- <small class="fw-light text-decoration-line-through">{{prod.selling_price}}</small> </div> </div> </a> </div> {% endfor %} </div> </div> </div> </div> {% endblock %}```` -
SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'localhost'. (_ssl.c:997)
Exception Location: /usr/lib/python3.10/ssl.py, line 1342, in do_handshake I am new webi. I get this error when sending email from my django website. I have two domains on the host and am using postfix to send emails i have checked ssl certificates and are working properly. can anyone help please i tried to pip install -upgrade certifi to update the certificates. renewed the certificates with sudo certbot renew --dry-run the site is also active with https -
While testing routes of my django prodject, i got Type error: expected sting or bites like object. How i can fix this error?
The page of the published news on my blog, is available to any user. I use pytest to check if the page is accessible to an anonymous user. Url is formed by using the id of the news, which I pass in the address parameters (as a tuple). In the result I got this Type error. test_pages_availability[news:detail-news] - TypeError: expected string or bytes-like object I had tried to format args to str, puted a coma after arg for tuple format, it didn't helped code of test @pytest.mark.django_db @pytest.mark.parametrize( 'name, args', ( ('news:detail', pytest.lazy_fixture('news')), ('news:home', None), ('users:login', None), ('users:logout', None), ('users:signup', None), ) ) def test_pages_availability(client, name, args): if args is not None: url = reverse(name, args=(news.id,)) else: url = reverse(name) response = client.get(url) assert response.status_code == HTTPStatus.OK ` fixture @pytest.fixture def news(): news = News.objects.create( title='Новость', text='Невероятное событие', date=datetime.today, ) return news class NewsDetail(generic.DetailView): model = News template_name = 'news/detail.html' def get_object(self, queryset=None): obj = get_object_or_404( self.model.objects.prefetch_related('comment_set__author'), pk=self.kwargs['pk'] ) return obj def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if self.request.user.is_authenticated: context['form'] = CommentForm() return context Traceback: request = <FixtureRequest for <Function test_pages_availability[news:detail-news]>> def fill(request): item = request._pyfuncitem fixturenames = getattr(item, "fixturenames", None) if fixturenames is None: fixturenames = request.fixturenames if hasattr(item, … -
Upgrading Redis on Heroku causing SSL errors in Celery
I've recently upgraded our Heroku Redis from version 5.0 to 7.0.11 and I'm now receiving the following error when running Celery Traceback (most recent call last): File "/app/.heroku/python/bin/celery", line 8, in <module> sys.exit(main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/celery.py", line 235, in main return celery(auto_envvar_prefix="CELERY") File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1055, in main rv = self.invoke(ctx) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "/app/.heroku/python/lib/python3.8/site-packages/click/core.py", line 760, in invoke return __callback(*args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/click/decorators.py", line 26, in new_func return f(get_current_context(), *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/base.py", line 134, in caller return f(ctx, *args, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 98, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/app/.heroku/python/lib/python3.8/site-packages/celery/worker/worker.py", line 119, in setup_instance self._conninfo = self.app.connection_for_read() File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 818, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) File "/app/.heroku/python/lib/python3.8/site-packages/celery/app/base.py", line 877, in _connection return self.amqp.Connection( File "/app/.heroku/python/lib/python3.8/site-packages/kombu/connection.py", line 203, in __init__ url_params = parse_url(hostname) File "/app/.heroku/python/lib/python3.8/site-packages/kombu/utils/url.py", line 50, in parse_url query['ssl'][key] = query[key] TypeError: 'str' object does not support item assignment celery.py from celery import Celery app = Celery('endpoints') # namespace='CELERY' means all celery-related configuration keys should have a …