Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How can I load SECRET_KEY from .env file in Django?
This is how my settings.py looks like: import os import dotenv dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # UPDATE secret key SECRET_KEY = os.environ['SECRET_KEY'] This is how my .env file looks like: SECRET_KEY="TOPSECRETKEY" When running python manage.py migrate, it returns KeyError: 'SECRET_KEY' -
Template is not saving Image to database
I am developing a website that allows users to upload projects with various details such as name, description, image, and deadline. However, I am facing an issue where, upon clicking the "Save Project" button, i get redirected to the homepage, but the image does not get saved in the database while everything else does. No error message is displayed. The problem may lie in the form and script sections since it has been able to save image, but after making adjustments to the form and adding script code, to make it look nicer, it stopped working. Screenshot of input form: (https://i.stack.imgur.com/ZUVrC.png) Screenshot of homepage after saving a project: (https://i.stack.imgur.com/wrb0o.png) Here is my code: form that was able to save images: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <label for="{{ project_form.project_name.id_for_label }}">Project name:</label> {{ project_form.project_name }} <br> <label for="{{ project_form.project_description.id_for_label }}">Project description:</label> {{ project_form.project_description }} <br> {{ formset.management_form }} {% for form in formset %} <div class="formset-row"> {{ form.id }} {{ form.image }} </div> {% endfor %} <br> <label for="{{ project_form.deadline.id_for_label }}">Deadline:</label> {{ project_form.deadline }} <br> <button type="submit">Save Project</button> </form> In models.py: from django.db import models class Project(models.Model): project_name = models.CharField(max_length=100) project_description = models.CharField(max_length=2000) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True,) deadline = models.DateTimeField(null=True, … -
How to show/hide a django form field based on the stored value while editing?
models.py: cv_choices = ( ('One Time', 'One Time'), ('Renewal', 'Renewal'), ) class Certification(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE, null=True) certName = models.CharField(_('Certification Name'), max_length=100, null=True) certId = models.CharField(_('Certification ID'), max_length=100, null=True) certUrl = models.URLField(_('Certification URL'), max_length=500, null=True) certStartDate = models.DateField(_('Certification Start Date'), null=True) certEndDate = models.DateField(_('Certification End Date'), null=True, blank=True) certValidity = models.CharField(_('Certification Validity'), max_length=10, choices=cv_choices, default='Renewal', null=True) createdDate = models.DateTimeField(_('Created Date'), auto_now_add=True, editable=False) modifiedDate = models.DateTimeField(_('Modified Date'), auto_now=True, editable=False) def __str__(self): return self.certName forms.py: class CertificationForm(forms.ModelForm): certValidity = forms.ChoiceField(choices=[('One Time', 'One Time'),('Renewal', 'Renewal')]) class Meta: model = empCertification fields = ('user', 'certName', 'certId', 'certUrl', 'certStartDate', 'certEndDate', 'certValidity') def __init__(self, *args, **kwargs): super(empCertificationForm, self).__init__(*args, **kwargs) self.fields['user'].widget.attrs['class'] = 'form-select' self.fields['certName'].widget.attrs['class'] = 'form-control' self.fields['certId'].widget.attrs['class'] = 'form-control' self.fields['certUrl'].widget.attrs['class'] = 'form-control' self.fields['certStartDate'].widget.attrs['class'] = 'form-control' self.fields['certEndDate'].widget.attrs['class'] = 'form-control' self.fields['certValidity'].widget.attrs['class'] = 'form-select' for field in self.fields: self.fields[field].widget.attrs['placeholder'] = 'Provide Details' Edit Template File: <form action="{% url 'certificationEdit' certification.pk %}" method="post" class="form" enctype="multipart/form-data" novalidate> {% csrf_token %} <div class="card-body border-top p-9"> {% if certificaitonForm.errors %} {% for field in certificaitonForm %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{field.name|title}} - {{error|escape}}</strong> </div> {% endfor %} {% endfor %} {% for error in certificaitonForm.non_field_errors %} <div class="alert alert-danger"> <strong>{{error|escape}}</strong> </div> {% endfor %} {% endif %} <div … -
Django: Problem with urlpatterns for a page after login
After login, i can't access the redirect page (home.html). The page is not found, because I misspelled the urlpatterns of the home page. I'm new to Django. In urlpatterns work fine correctly: index page, login page and logout page. But the home page doesn't. I believe the problem is the urlpatterns of the home. The page is located at templates/app1/home.html Project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('app1.urls')) App/urls.py from django.urls import path, include from . import views from app1.views import index from app1 import views urlpatterns = [ path('', index, name='index'), path('login/', views.sign_in, name='login'), path('logout/', views.sign_out, name='logout'), path('home/', views, name='home'), #ERROR HERE??? ] In views.py I don't have any home related functions. I only have the login/logout functions working correctly. How can I display the home correctly?