Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ORM calculate score and win from tables. Please click on description links to see model screenshots
I am new bie to django ORM and struggling to use ORM. Please help me. I have 3 tables in django model and i want to write some getter methods under model classI need help to create methods, I am not able to understand how to calculate values using ORM Create a method on the Team model that returns the total number of matches played by the team Create a method on the Team model that returns the total number of matches won by the team Create a method on the Team model that returns the total number of matches lost by the team Your help is really meaningful to me. Thank you. -
Creating a service layer with Django Rest Framework
I am fairly new to web-development and just studing design patterns and code architecture. Now, I am developing service layer for business logic. And here I have a dillema. One approach is to use command design pattern. Where I have a class which implements user creation and related processes (e.g. sending email, writting logs etc), also this class has one public method (entry point) and private methods, called inside the entry point. Here is the example of what I mean. class CreateUser: def _create_user(self, **data) -> User: # here perform creation of user itself, requesting repository layer ... def _send_email(self, **data) -> None: # here I send email def _write_logs(self, **data) -> None: # writing logs to a file def execute(**data): self._create_user(**data) self._send_email(**data) self._write_logs(**data) On the other hand, there is a approach where I create a common service as a class, that handles user authentication and registration and for each user action has one method: class UserService: def create_user(self, **data) -> User: # call to repository # send email # write logs def update_user(self, **data) -> User: # call to repository # write logs I don't really know what solution I should choose. I suppose that the command pattern is … -
PermissionError: [Errno 13] Permission denied: '/app/static/admin/fonts/README.txt'
I am trying to deploy a django app for the first time on a EC2 Ubuntu 22.04 instance. I have everything set up in a docker-compose file and working on my Windows 11 machine, but I am running into issues with permissions. The instance's user is ubuntu and I can read, write and execute within the folder. I have tried adding it to the dockerfile but that does not seem to have any effect. Dockerfile: ARG PYTHON_VERSION=3.9-slim-bullseye FROM python:${PYTHON_VERSION} as python # Stage1: Create Wheels FROM python as python-build-stage ARG BUILD_ENVIRONMENT=production # required for make and setup for postgres RUN apt-get update && apt-get install --no-install-recommends -y \ build-essential \ libpq-dev COPY Backend/requirements . RUN pip wheel --wheel-dir /usr/src/app/wheels \ -r ${BUILD_ENVIRONMENT}.txt # Stage 2: Setup Django FROM python as python-run-stage ARG BUILD_ENVIRONMENT=production ARG APP_HOME=/app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV BUILD_ENV ${BUILD_ENVIRONMENT} WORKDIR ${APP_HOME} RUN addgroup --system django \ && adduser --system --ingroup django django RUN apt-get update && apt-get install --no-install-recommends -y \ libpq-dev \ netcat \ && apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \ && rm -rf /var/lib/apt/lists/* COPY --from=python-build-stage /usr/src/app/wheels /wheels/ RUN pip install --no-cache-dir --no-index --find-links=/wheels/ /wheels/* \ && rm -rf /wheels/ # django … -
Display contents of the database table selected by user in Django
As per user selection I want to display course details. I do not want to create multiple pages for each course detail. So, at course-detail.html I am passing a course-code as hidden value in html form which is table name in my database project. When a user submits the query for course, I pass the course-code value by POST method into my views.py file. But there I am not able to use post method string as a model name. courses.html {% for courses in english_courses %} <form action="{% url "course-detail" %}" method="POST"> {% csrf_token %} <input type="hidden" name="course-code" value="{{courses.course_code}}"> <button class="btn-lg btn-primary d-inline-flex align-items-center" type="submit" onclick="document.location.href='{% url "course-detail" %}';"> {{course.name}} </button> &nbsp; {% endfor %}</form> views.py def course_detail(request): if request.method == "POST": course_request = request.POST['course-code'] course_request = course_request.capitalize() course_details = course_request.objects.all() return render(request, 'course-detail.html', {'course': course_details}) else: messages.warning(request, "Link seems to be broken. Please contact admin.") return render(request, 'course-detail.html') this throws an error: AttributeError at /english/course-detail 'str' object has no attribute 'objects' -
data = json.loads(request.body.decode('utf-8')) error no se por que :(
Me da este error "data = json.loads(request.body.decode('utf-8'))" al querer cargar un json traido de un js con django. Es para un proyecto escolar :( El codigo recibe una foto tomada por el navegador y la guarda y el error aparece al recibir el post por parte del html Aqui el codigo del view del proyecto. from django.shortcuts import render from django.http import JsonResponse import json import base64 import os import logging from random import randint logging.basicConfig(level=logging.DEBUG) def Inicio(request): if request.method == 'POST': data = json.loads(request.body.decode('utf-8')) image_url = data.get('image_url', '') # Guarda la imagen físicamente en la carpeta de medios guardar_imagen_fisicamente(image_url) return JsonResponse({'message': 'Imagen recibida y guardada con éxito.'}) return render(request, 'plantilla1.html') def guardar_imagen_fisicamente(image_url): # Decodifica la imagen base64 image_data = image_url.split(",")[1] image_binary = base64.b64decode(image_data) # Guarda la imagen en la carpeta de medios ruta_carpeta = 'capturas' ruta_completa = os.path.join('media', ruta_carpeta, generar_nombre_imagen()) ruta_completa = os.path.join("C:/myproject/myproject/", ruta_completa) with open(ruta_completa, 'wb') as f: f.write(image_binary) def generar_nombre_imagen(): n = randint(0,999999999) nombre_imagen = f"imagen_{n}.png" return nombre_imagen Cosas como url y settings estan bien, ya esta revisado pero me da error en cuando quiero obtener la data, y es que me explota enter image description here Inexperadamente si me toma la foto, es decir si hace … -
How to check if a Django CharField is empty
I've been working on a Django database project and I need to return a value only if a CharField is not empty. class author(models.Model): name = models.CharField(max_length=255, unique=True, help_text='Article author') pronouns = models.CharField(max_length=255, help_text='Enter pronouns (optional)', blank=True, verbose_name='Pronouns (optional)') if pronouns != '': def __str__(self): return f'{self.name} ({self.pronouns})' else: def __str__(self): return self.name Despite me not entering anything in the pronouns field when testing, it still acts as if it has a value and returns Name () with nothing in those parentheses. I have tried, checking if it is None or '' and setting default='' and then checking if it is not equal to the default. None of those have worked. How do I fix this? -
DRF serializer validation of inputs across multiple nested fields
I'm using DRF serializers for models with measurements with units. Here's my model: class Cargo(models.Model): length = models.FloatField() height = models.FloatField() weight = models.FloatField() input_length_unit = models.IntegerField(choices=LengthUnits.choices) input_weight_unit = models.IntegerField(choices=WeightUnits.choices) I have the following serializers to convert data like {"length": {"value": 10, "unit": 1}, ...} to my model schema: class FloatWithUnitSerializer(serializers.Serializer): value = serializers.FloatField() unit = serializers.IntegerField() def __init__(self, unit_type, field_name, *args, **kwargs): super().__init__(*args, **kwargs) self.unit_type = unit_type self.field_name = field_name def to_representation(self, instance): value = getattr(instance, self.field_name) unit = getattr(instance, f"input_{self.unit_type}_unit") # convert from database unit to input unit value = value * UNITS[self.unit_type][unit] return {"value": value, "unit": unit} def to_internal_value(self, data): # convert from input unit to database unit value = data["value"] / UNITS[self.unit_type][data["unit"]] return {self.field_name: value, f"input_{self.unit_type}_unit": data["unit"]} class CargoSerializer(serializers.ModelSerializer): length = FloatWithUnitSerializer("length", "length", required=False, source="*") height = FloatWithUnitSerializer("length", "height", required=False, source="*") weight = FloatWithUnitSerializer("weight", "weight", required=False, source="*") class Meta: model = models.Cargo fields = ["length", "height", "weight", "input_length_unit", "input_weight_unit"] This works, but now I want to prevent unit-mixing. For example given the unit type "length", which includes the "length" and "height" fields (units are meters, feet, etc), they need to post the same unit for both, e.g. {"length": {"value": 10, "unit": 1}, "height": {"value:15", "unit": 1}}. … -
django-otp and dj-stripe conflict
i'm searching a way to implement django-otp and dj-stripe in a web project but i think there is a conflict because django-otp uses custom admin_site.register() to register models while dj-stripe uses admin.site.register(). i'm triyng with the following code but not works because all stripe model are registered not following list_display field customizations as in admin.py on github repository. #urls.py from django.contrib import admin from django.urls import path, include from account.admin import admin_site urlpatterns = [ path("realadmin/", admin_site.urls), path("stripe/", include("djstripe.urls", namespace="djstripe")), ] #admin.py from django_otp.admin import OTPAdminSite from django_otp.plugins.otp_totp.models import TOTPDevice from django_otp.plugins.otp_totp.admin import TOTPDeviceAdmin # Stripe modules from djstripe import models class OTPAdmin(OTPAdminSite): pass admin_site = OTPAdmin(name='OTPAdmin') # Script to register all models modelsarray = django.apps.apps.get_models() # Register other django-otp models with the custom admin site (admin_site) for model in modelsarray: try: if model.__module__.startswith("dj-stripe"): # Register with the default admin.site for dj-stripe models admin.site.register(model) elif model == Customer: admin_site.register(model, CustomerAdmin) else: # Register with the custom admin site for other models (e.g., django-otp) admin_site.register(model) except admin.sites.AlreadyRegistered: pass so, i want to register stripe's models using admin.site.register because in this way i can use admin.py code of github repository but i need also to use admin_site.register for otp secutiry tool. can … -
How to get value from select2 in Django
I am trying to add a new constraint, but according to the data, the code takes all values except acc_id4 and c_center, and the result is always something like Row 1: acc_id4=None, description=salary 10/2023, doc=1023, d_date=2023-11-25, debit=1000, credit=0.00, c_center=None I don't know why it's always nothing Is the problem in the template or in the Django code? And how do I solve this problem? Note: The JavaScript code creates a new row and makes the old row read-only. It also copies the values except for the acc_id4 and c_center values. It also makes the generated name add a number after the _ sign. html {%load static%} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Acc Entry</title> <link rel="shortcut icon" href="{% static 'image/daleel.ico'%}" > <link rel="stylesheet" href="{% static 'css\Entry.css'%}"> <!-- Font Awesome --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" integrity="sha512-1ycn6IcaQQ40/MKBW2W4Rhis/DbILU74C1vSrLJxCq57o941Ym01SwNsOMqvEBFlcgUa6xLiPY/NS5R+E6ztJQ==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="{% static 'plugins/fontawesome-free/css/all.css'%}"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600&display=swap" > <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> </head> <body> <div class="radio"> <div class="btn-group" role="group" aria-label="Basic radio toggle button group"> <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" > <label class="btn btn-outline-primary" for="btnradio1">New</label> <input type="radio" class="btn-check" name="btnradio" id="btnradio2" value="save" autocomplete="off"> <label class="btn btn-outline-primary" for="btnradio2">Save</label> <input type="radio" class="btn-check" … -
Running sphinx-build -b html docs_source/ docs/ leads to AttributeError: 'Values' object has no attribute 'link_base'
I have a Django 4.2 project and wish to run the Sphinx to generate the docs. When I run: sphinx-build -b html docs_source/ docs/ I got the following error: Exception occurred: File "C:\ProgramData\Anaconda3\envs\django_3_8\Lib\site-packages\django\contrib\admindocs\utils.py", line 116, in _role inliner.document.settings.link_base, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'Values' object has no attribute 'link_base' The full traceback has been saved in C:\Users\user\AppData\Local\Temp\sphinx-err-r_cbc4k5.log, if you want to report the issue to the developers. The list of the installed packages is as follows: Package Version alabaster 0.7.13 amqp 5.1.1 anyio 3.5.0 argon2-cffi 21.3.0 argon2-cffi-bindings 21.2.0 asgiref 3.7.2 asttokens 2.0.5 attrs 22.1.0 autopep8 1.6.0 Babel 2.13.1 backcall 0.2.0 beautifulsoup4 4.12.2 billiard 3.6.4.0 bleach 4.1.0 celery 5.1.2 certifi 2022.12.7 cffi 1.15.1 charset-normalizer 3.3.2 click 7.1.2 click-didyoumean 0.0.3 click-plugins 1.1.1 click-repl 0.2.0 colorama 0.4.6 comm 0.1.2 coverage 7.2.2 cryptography 39.0.1 debugpy 1.5.1 decorator 5.1.1 defusedxml 0.7.1 diagrams 0.23.3 Django 4.2.7 django-debug-toolbar 4.0.0 django-nose 1.4.6 django-postgres-extra 2.0.8 djangorestframework 3.14.0 djangorestframework-simplejwt 4.4.0 docutils 0.20.1 drf-extra-fields 3.5.0 drf-spectacular 0.26.2 entrypoints 0.4 et-xmlfile 1.1.0 executing 0.8.3 fastjsonschema 2.16.2 filetype 1.2.0 graphviz 0.20.1 idna 3.4 imagesize 1.4.1 inflection 0.5.1 ipykernel 6.19.2 ipython 8.18.0 ipython-genutils 0.2.0 jedi 0.18.1 Jinja2 3.1.2 jsonschema 4.17.3 jupyter_client 8.1.0 jupyter_core 5.3.0 jupyter-server 1.23.4 jupyterlab-pygments 0.1.2 kombu 5.3.1 lxml 4.9.2 Mako 1.3.0 Markdown 3.5.1 MarkupSafe … -
Django-Meta Package for other Language
I have several questions about Meta package (for Meta tags in templates) of Django and those are : 1.Does this package can support other languages like Persian? 2.If it can support, I just need to change my Language_Code to "fa-IR", or should I consider this answer too? Thanks for your attention. -
Django Forms widget tweaks allow only alphatbet letters in text field
I am trying to restrict input in text fields to only alpha letters also via client side I have tried this, but this doesn't work. the script: <script type="text/javascript"> function Validate(e) { var keyCode = e.keyCode || e.which; var regex = /^[A-Za-z]+$/; var isValid = regex.test(String.fromCharCode(keyCode)); return isValid; } </script> Then the call: {% render_field form_built_properties.building_material|attr:"onkeypress(Validate)" class="form-control" %} I tried this alone, doesn't work either: {% render_field form_built_properties.building_material|attr:'onkeydown="return /[a-z]/i.test(event.key)"' Ideally there should be a function that on clicking the submit button checks that building_material text field (and others) have been correctly filled before submitting all data. -
CSS not connecting in Django
Page not found (404) 'css\static.css' could not be found Request Method: GET Request URL: http://127.0.0.1:8000/static/css/static.css Raised by: django.views.static.serve urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py: """ from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'pushkin.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(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', ], }, }, ] WSGI_APPLICATION = 'pushkin.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = '/static/' STATIC_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/css'), ] STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' base.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> … -
unable to prepare context: path "/Users/ahmetcankoca/Desktop/learning Django/resume/nginx" not found
I created an ngnix folder in the project to run it in docker and get my site up, but it doesn't work, it says ngnix not found and shows the absolute path. I'm trying to get my site up and running, it's not something I know very well about, I'm looking forward to your help. -
400 Bad Request: Djoser built-in create user using django Signals
I have 3 models (including Custom User) structured: accounts.models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models #type: ignore from django.utils.translation import gettext_lazy as _ from django.utils import timezone from phonenumber_field.modelfields import PhoneNumberField #type: ignore # Create your models here. class UserAccountManager(BaseUserManager): def create_user(self, email, user_role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address.") if not user_role: raise ValueError("Users must have a user role.") email = self.normalize_email(email) user = self.model(email=email, user_role=user_role, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, user_role="admin", password=None, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_admin", True) extra_fields.setdefault("is_active", True) extra_fields.setdefault("is_superuser", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_admin") is not True: raise ValueError(_("Superuser must have is_admin=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) return self.create_user(email, user_role, password, **extra_fields) class UserAccount(AbstractBaseUser, PermissionsMixin): USER_ROLES = ( ("resident", "Resident"), ("healthworker", "Health Worker"), ("admin", "Admin") ) email = models.EmailField(_("email address"), unique=True) user_role = models.CharField(max_length=100, choices=USER_ROLES) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["user_role",] objects = UserAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True def save(self, *args, **kwargs): if self.user_role == "admin": self.is_staff = … -
Mismatch between column type in MySQL and Django model value
I have a model class defined as follows: class Person(models.Model): # ... spending = models.BigIntegerField(blank=True, null=True) # ... And populate it like so: p = Person( # ... spending = str(row['spending']) # ... ) p.save() In which row is a pandas DataFrame row. What will the type of the field be in the database? What if the field is defined as TextField and what I insert is int(row['spending')? Looking at the type in MySQL I can guess the defined field type is enforced. Will it still be the case if the column contains null values? For example, the field is of type numeric and we insert null values will it remain numeric or it will change to Text to accomodate the nulls? -
How do I stop http automatically going to https?
When redirecting from a home page to another page I continuously get "You're accessing the development server over HTTPS, but it only supports HTTP." Out of the two buttons that redirect only one provides this issue, and the other redirects fine. Code in vscode Browser error I've tried setting SECURE_SSL_REDIRECT to false in settings.py however I still get this error. -
Slow Loading and 500 Errors with Django Project on Apache Server
Hello Stack Overflow community, I'm encountering performance issues with my Django project hosted on an Apache server. When accessing the site through Apache, it either takes a very long time to load or returns a 500 error. However, when I use Django's runserver command and access the site through a tunnel, it loads fine without any issues. Could someone help me understand why my Django project is slow or failing when hosted on Apache, but works well with runserver? (it's my first time tried to hosted an project) here's my configfile: <VirtualHost *:80> ServerAdmin admin@taicles.com ServerName taicles.com ServerAlias www.taicles.com Alias /static /home/sami/SerurierProject/static <Directory /home/sami/SerurierProject/static> Require all granted </Directory> <Directory /home/sami/SerurierProject/SerurierProject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess SerurierProject python-path=/home/sami/SerurierProject:/home/sami/venv/lib/python3.10/site-packages WSGIProcessGroup SerurierProject WSGIScriptAlias / /home/sami/SerurierProject/SerurierProject/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> -
Celery Emails and Accessing Mailbox
I'm in the process of moving my emails over to Celery tasks to run asychronously. Porting over my existing tests I'm struggling with an AssertionError when I attempt to access the mail.outbox. I assume this is due to the mailbox being created within the Celery thread rather than within the scope of the test. Is there any way around this to test the email has succesfully sent? I've pretty much ran out of ideas on the best way to approach this. Task from celery import shared_task from django.template.loader import render_to_string from django.core.mail import EmailMultiAlternatives from django.conf import settings from smtplib import SMTPException CONFIRMATION_MESSAGE = 'Thank you! Your enquiry has been received and one of our team will be in touch shortly.' @shared_task def send_contact_email(recipient, subject): try: #send a confirmation email email_content = render_to_string('base_email.html', {'message': 'message'}) # Create an EmailMultiAlternatives object email = EmailMultiAlternatives( subject=subject, body=CONFIRMATION_MESSAGE, from_email=settings.DEFAULT_FROM_EMAIL, to=[recipient] ) # Attach the HTML content to the email email.attach_alternative(email_content, "text/html") # Send the email email.send() except SMTPException as e: # Handle any SMTP exceptions print(f"SMTPException occurred: {str(e)}") except Exception as e: # Handle any other exceptions print(f"Exception occurred: {str(e)}") Test from django.conf import settings from django.test import TestCase, override_settings from django.core import … -
hyperlink leads to 404 error message, No Post matches the given query, Expecting to lead to `views.PostList.as_view()`
Expecting hyperlink in index.html to lead to views.PostList.as_view() hyperlink located in templates/base.html line 46: <a class="nav-link" href="{% url 'questions' %}">Top Questions</a> Leads to http://localhost:8000/questions/ as expected but with this error message: Page not found (404) No Post matches the given query. Request Method: GET Request URL: http://localhost:8000/questions/ Raised by: blog.views.PostDetail Using the URLconf defined in classroommatrix.urls, Django tried these URL patterns, in this order: admin/ index/ [name='index'] <slug:slug>/ [name='post_detail'] The current path, questions/, matched the last one. debugging steps taken So far I've reviewed urlpatterns and views.py as indicated by the error message. 1: review urlpatterns The problem seems to arise in the urlpatterns in blog/urls.py. The error message indicates that views.PostDetail.as_view() is problematic: # blog/urls.py (called through classroommatrix/urls.py) from . import views from django.urls import path urlpatterns = [ # url patterns for the blog app here. path('index/', views.PostList.as_view(), name='index'), # home page path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), # post detail page - !!The error message indicates that PostDetail is problematic: path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), # post like path('questions/', views.PostList.as_view(), name='questions'), # questions page ] 2: review PostDetail Seems a less likely problem area as there is no mention of 'questions/' in `PostDetail class. # blog/views.py from django.shortcuts import render, get_object_or_404, reverse … -
what is the solution to this pip ERROR: Could not install packages due to an OSError: Could not find a suitable TLS CA certificate bundle
So I was trying my hand on a django project that has to do with authentication, on trying to install django-ses for aws email service, I have this error ERROR: Could not install packages due to an OSError: Could not find a suitable TLS CA certificate bundle, invalid path: C:\Program Files\PostgreSQL\16\ssl\certs\ca-bundle.crt and since I had installed postgressql 16/pgadmin for database. And now I discovered that it has affected my pip, I can't install any package, the error keeps popping up, please I need solutions to this, since I got a project deadline. I have tried various suggesions from this links: text text and various others, none is working, even youtube is not giving a solution. I need solution, any help will be appreciated. -
i am getting an error on fetching data from api in json format
enter image description here above image contains the django code as above code is providing 403 error ,i have used this api https://data.sec.gov/api/xbrl/companyfacts/CIK0001544522.json to fetch the data in json format but my django server is providing an 403 error ,kindly go through the image to see the code here is the postman response enter image description here -
Are ENV Variables also passed as a part of HTTP request?
I was experimenting with Django middlewares. And I happened to randomly print out request.META, I saw that my Environment variables are also passed on to the django server. My middleware.py class AnalyticsMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): for key in request.META: print(key, ": ", request.META[key]) return None Can someone explain what is happening? -
Django NoReverseMatch Error for 'questions' View After Google OAuth Sign-In
I'm working on a Django project with Google OAuth implemented. The homepage (index.html) loads correctly, and the Google OAuth sign-in functions as expected. However, I'm encountering a NoReverseMatch error when trying to redirect to the questions view after sign-in. Error Message: NoReverseMatch at / Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. ... NoReverseMatch at / Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. Request Method: GET Request URL: http://8000-lmcrean-classroommatrix-zp6cz7sdhxw.ws-eu106.gitpod.io/ Django Version: 3.2.23 Exception Type: NoReverseMatch Exception Value: Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. Exception Location: /workspace/.pip-modules/lib/python3.9/site-packages/django/urls/resolvers.py, line 698, in _reverse_with_prefix Python Executable: /home/gitpod/.pyenv/versions/3.9.17/bin/python3 Python Version: 3.9.17 [...] Error during template rendering In template /workspace/Classroom-Matrix/templates/base.html, error at line 45 Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name. [...] 45 <a class="nav-link" href="{% url 'questions' %}">Top Questions</a> debugging steps below I have reviewed the problem areas and tried solving adjustments. templates/base.html same error message appears when changing 'questions' to 'index' in line 45. to Top Questions - leads to " 'index' is not a valid view function or pattern name." does … -
Passing data to modal from button
I want to make a post request to my django view with query params. The query params are coming from the html template. On accept button in template, a modal opens. And there is an accept button in the modal. I want to pass the data from button to the modal and then onclick of modal button, it will make an ajax call to the view. But I am not able to pass the values from button to the modal. Here is my code: Button part of the template:(The values {{ supervisor.supervisor.user.id }} and {{ supervisor.supervisor.user.id }} are accessible here.) {% for supervisor in proposal.supervisors %} <tr> <td> {% if supervisor.committee_status == 0 %} <span class="badge badge-warning text-dark">Pending</span> {% elif supervisor.committee_status == 1 %} <span class="badge badge-success text-success">Accepted</span> {% elif supervisor.committee_status == 2 %} <span class="badge badge-danger text-danger">Rejected</span> {% elif supervisor.committee_status == 3 %} <a href = "{% url 'proposal_modification' proposal.proposal.id supervisor.supervisor.user.id%}"> <span class="badge badge-info text-info " style="text-decoration: underline;"> Modifications</span> {% endif %} <div class="btn-group" role="group"> <button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#acceptModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Accept</button> <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#rejectModal" data-supervisor-id="{{ supervisor.supervisor.user.id }}" data-proposal-id="{{ proposal.proposal.id }}">Reject</button> </div> </td> </tr> {% endfor %} Modal : …