Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get category id for item from Django url
It looks like something simple and common, but I can't find what's wrong in my implementation. I create a simple item add/edit form in my Django project for items by categories. The form will be located at /<category_id>/add. After filling data on form, it can just get category from category_id. I try to fill this data in form_valid method of FormView, but all I got is error: IntegrityError at /1/add NOT NULL constraint failed: megashop_item.category_id I've tried print("boo") in my form_valid method - nothing is printed, looks like a validation throws exception before. Looks like it's ItemCreateView validation, but how to fix it? How to fix it? All examples are about using functions, not views. models.py class Category(models.Model): title = models.CharField(max_length=200) class Item (models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=200) forms.py class ItemForm(forms.ModelForm): class Meta: model = Story fields = ["title", "category"] urls.py urlpatterns = [ path("<int:category_id>/add", ItemCreateView.as_view(), name="item-add"), ] views.py class ItemCreateView(LoginRequiredMixin, CreateView): model = Category form_class = CategoryForm class ItemFormView(LoginRequiredMixin, FormView): template_name = "megashop/item_form.html" form_class = ItemForm success_url = reverse_lazy("catalog:index") def form_valid(self, form): instance = form.save(commit=False) instance.contest = Category.objects.get(pk=self.kwargs.get('category_id')) form.save() return HttpResponseRedirect(self.get_success_url()) -
DjangoModelPermissionsOrAnonReadOnly still needs authentication
I encountered this issue even though I didn't set authentication requirements in my settings.py. When I view the /products/ endpoint as anonymous user it still asks for authentication but when I view the endpoint as authenticated user it behaves as expected here's my viewset where I'm using the permission class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_class = ProductFilter pagination_class = DefaultPagination permission_classes = [DjangoModelPermissionsOrAnonReadOnly] search_fields = ["title", "description"] ordering_fields = ["unit_price", "last_update"] def destroy(self, request, *args, **kwargs): if OrderItem.objects.filter(product_id=kwargs["pk"]).count() > 0: return Response( { "error": "Product cannot be deleted because it is associated with an order item." }, status=status.HTTP_405_METHOD_NOT_ALLOWED, ) return super().destroy(request, *args, **kwargs) here's my settings.py file """ Django settings for storefront project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path from datetime import timedelta # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-hs6j037urx6iav+7#10%-vu4l4f5@@-1_zo)oft4g7$vf2$jmp" # SECURITY WARNING: don't run … -
Why is username required when I set email as username
I am. trying to create Django backend for my application. For authentication I am using django authentication where I needed to create CustomUser model for my specific use case. After trying to insert new user I am encountering this error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. I will add full traceback below. I have also included this line in settings.py AUTH_USER_MODEL = "users.CustomUser" This is my function that I use for creating new user: from .models import CustomUser from .dto import UserRegistrationDto, JWTDto def create_user_in_database(data: UserRegistrationDto) -> JWTDto: user = CustomUser.objects.create(first_name=data.first_name, last_name=data.last_name,birthdate=data.birthdate, email=data.email) user.save() user.set_password(data.password) return user My CustomUser model definition: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): birthdate = models.DateField(null=True, blank=True) email = models.EmailField(unique=True) key = models.PositiveBigIntegerField(default=1,null=False) tier = models.IntegerField(default=1,null=False) used_capacity = models.FloatField(default=0.0,null=False) USERNAME_FIELD = "email" REQUIRED_FIELDS = ["birthdate","first_name","last_name"] My DTO class: class UserRegistrationDto(ModelSchema): class Meta: model = CustomUser fields = ["first_name","last_name","birthdate","email","password"] Full traceback: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. Traceback (most recent call last): File "//Caches/pypoetry/virtualenvs/backend-y-HyWMBZ-py3.11/lib/python3.11/site-packages/django/db/backends/utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "users_customuser_username_key" DETAIL: Key (username)=() already exists. The above exception was the … -
Getting wrong SSE response from the server
Developing the project with Django. DRF installed. Some processin the backend generating a log file. I am looking at the end of the file for target strings. When target string was caught, it has to be shown on HTML user page. Everything happens in dynamics. urls.py path('api/log-stream/', LogStreamAPIView.as_view(), name='log_stream'), LogStreamAPIView class LogStreamAPIView(APIView): def get(self, request): def stream_log(): f = subprocess.Popen(['tail', '-F', rcvenot_log], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p = select.poll() p.register(f.stdout) while TEST_IN_PROGRESS: if p.poll(0.1): new_line_log = f.stdout.readline().decode('utf-8').strip() for target_line in RCV_SCENARIO: if target_line in new_line_log: yield f"event: {new_line_log}\n\n" return StreamingHttpResponse(stream_log(), content_type='text/event-stream') Script on the user HTML page <div style="width: 200px; height: 200px; overflow-y: scroll;"> <ul id="logList"></ul> </div> <script> document.addEventListener("DOMContentLoaded", function() { var logList = document.getElementById('logList'); function updateLog(newLine) { var listItem = document.createElement('li'); listItem.textContent = newLine; logList.appendChild(listItem); } var source = new EventSource('/api/log-stream/'); source.onmessage = function(event) { updateLog(event.data); }; }); </script> I see the strigns via API mysite.ru/api/log-stream/. Some strings event: 2024.03.22 16:16:13:016[INFO ][Thread-0] ************************* - 2 But I don't see them on HTML page. In browser console I see the response code 406: GET 127.0.0.1:8000/api/log-stream 406 (Not Acceptable) In Response see {"detail":"The \"Accept\" request header could not be satisfied."} I have tried throw data in different formats f"event: {new_line_log}\n\n" or f"data: {new_line_log}\n\n". … -
How to ensuring Source Code secure for Python Applications on Client Systems
I’m developing python django web application based on the client requirement and configuration. I was to prevent the client from accessing to my source code and tampering with my code. I tried encoding my source code into machine code but issue is that it can be decoded to normal code Would appreciate it if anyone can provide me advice and guidance on how to achieve my goal is securing source code -
Django / UploadFileForm only provides No valid form?
i try to create a simple file-upload funcionality with Django using the following code / files - Its more or less taken from this example: https://docs.djangoproject.com/en/5.0/topics/http/file-uploads/ forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) file = forms.FileField() views.py: from django.http import HttpResponseRedirect from django.shortcuts import render from .forms import UploadFileForm import os import sys def handle_uploaded_file(f): path = os.path.abspath(os.path.dirname(sys.argv[0])) fnFile = os.path.join(path, "gpp", "FILES", "QUESTIONS", "someFile.xyz") print(fnFile) with open(fnFile, 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) def home(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) print(request.POST) print(request.FILES) if form.is_valid(): print(f"Valid form") handle_uploaded_file(request.FILES['file']) return HttpResponseRedirect('/success/url/') else: print("No valid form") else: form = UploadFileForm() return render(request, 'home.html', {'form': form}) Generally the form looks fine and i can choose the file: But when i enter something it doesn´t work seeing the following in the log: [23/Mar/2024 10:02:35] "GET / HTTP/1.1" 200 1777 <QueryDict: {'csrfmiddlewaretoken': ['HWaddf1sBsKJc1k4CY9LiijIv1VAlxjWkRoFRixEP12rNDYyIx6zRYFC2MvPKIFm'], 'title': ['Test'], 'file': ['gpt.zip'], 'save': ['']}> <MultiValueDict: {}> No valid form [23/Mar/2024 10:04:33] "POST / HTTP/1.1" 200 1869 So it seems that request.FILES is for whatever reason empty? Why is this not working as intended? -
AlpineJS not initializing in dynamically loaded content
I am creating a custom searchable select widget in my django application. When returning the template normally all is well, however Alpine is not initializing when I render this field dynamically inside a modal. I use HTMX to make the ajax request; Django responds with a template and the template gets inserted into the DOM/modal. Things I've tried Adding my Alpine.data's data directly into the x-data. This works but there is quite a lot a would like to avoid it if possible Hacky ways to try initialize Alpine but does not work (maybe I've missed something) Hooking into HTMX beforeSwap event to try load the JS before the template (no dice) If anyone knows how to remedy this it would be greatly appreciated Template <div x-data="autocomplete" x-init="init('{{ widget.value }}')" class="relative"> # template stuff... </div> Script document.addEventListener('alpine:init', () => { Alpine.data('autocomplete', () => ({ open: false, selectedValue: '', init(value) { if (!['None'].includes(value)) { this.selectedValue = value; } }, # functions used inside the template... })); }); -
Django Payment Module Error Not successfully accepting payment
This is my razorpayDemo.html file i cannot be able to successfully do the payment as it is not process and after clicking on the success the button it show the page error and not the message of order successfully placed. Also in my razorpay options UPI QR option is not showing too in testing mode of it? -
Problems with deploying my first Django app on Azure
I have tried different approaches, but none of them works. I still get the: ERROR: No matching distribution found for Python==3.9.18 Or other version I have been trying to use. I tried: Installing the version defined in requirements.txt with Set up Python process: - name: Set up Python uses: actions/setup-python@v3 with: python-version: '3.11.3' (the base version for this app was 3.11.3), changing the requirements.txt to match the version that I found from the Action logs in GitHub: Python Version: /opt/python/3.9.18/bin/python3.9 And then checking which version I have installed locally and trying that one (it's 3.10.1). Each time I get the same error but with different version. Please help. You can browse the full approach here: https://github.com/JJDabrowski/Portfolio -
The media files are not being served in the dockerized django-react-postgresql portfolio from the database
I am building a dockerized personal portfolio using Django, React and PostgreSQL. The issue is, the images I am using are not found by the server in the deployed environment. I am using digitalocean to deploy my portfolio by creating a droplet. I have already uploaded the images in django admin and I am fetching those via API in the react-frontend. This is working fine in the local environment, but the files are not found by the server in the deployed environment. I have tried using NginX for this as well but the issue persists. When I tried to locate that image via django admin panel again, status code 404 is there. Not Found The requested resource was not found on this server. By this, at least I understood that the images I uploading to django admin are not being done successfully. However, when I check the media/images folder, inside the linux server, I can see all uploaded images. stored media files. I am using media_url in settings.py like this: BASE_DIR = Path(__file__).resolve().parent.parent # For the media files MEDIA_URL = 'media/' MEDIA_ROOT = BASE_DIR / 'media' I have tried to use NginX by installing it in the droplet and the … -
after using login(request) to create a session in my login view, the session is lost when i access another view in Django
I'm trying to create an API client server model in Django, but every time i log into a user in my login view. When i need to use the information and session from the login, for some reason it gets reset to AnonymousUser in my stories view. And if i use @login required it just redirects me to the login page as if i didn't just authorize and create a session with the user moments ago. Here is my views.py: @csrf_exempt def login_view(request): if request.method == 'POST': payload = request.POST # Validate payload keys if 'Username' not in payload or 'Password' not in payload: return JsonResponse({'message': 'Username or password missing'}, status=400) username = payload['Username'] password = payload['Password'] user = authenticate(request, username=username, password=password) if user is not None: # Log the user in and store session data login(request, user) return JsonResponse({'message': 'Login successful', 'user_id':user.id}, status=200) else: # Incorrect username or password return JsonResponse({'message': 'Incorrect username or password'}, status=401) @csrf_exempt @login_required def stories(request): if request.method == 'POST': if request.user.is_authenticated: print(request.user.username) # Retrieve data from the POST request headline = request.POST.get('Headline') category = request.POST.get('Category') region = request.POST.get('Region') details = request.POST.get('Details') # Get the current user's author object author = Author.objects.get(user=request.user.id) author_name = author.name … -
Getting Forbidden You don't have permission to access this resource error while depolye django project with apache and mod_wsgi
Here is my error from error_log [Fri Mar 22 16:00:09.035343 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has died, deregister and restart it. [Fri Mar 22 16:00:09.035428 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' terminated by signal 1 [Fri Mar 22 16:00:09.035443 2024] [wsgi:info] [pid 63294:tid 63294] mod_wsgi (pid=63896): Process 'swpdoc' has been deregistered and will no longer be monitored. [Fri Mar 22 16:00:09.036602 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Starting process 'swpdoc' with uid=48, gid=48 and threads=15. [Fri Mar 22 16:00:09.039512 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Python home /opt/Production/swpdoc/venv311. [Fri Mar 22 16:00:09.039593 2024] [wsgi:info] [pid 63897:tid 63897] mod_wsgi (pid=63897): Initializing Python. Python path configuration: `` ` ``` `PYTHONHOME = '/opt/Production/swpdoc/venv311' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = '/opt/Production/swpdoc/venv311/lib64/python3.11' sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/opt/Production/swpdoc/venv311' sys.base_exec_prefix = '/opt/Production/swpdoc/venv311' sys.platlibdir = 'lib64' sys.executable = '/usr/bin/python3' sys.prefix = '/opt/Production/swpdoc/venv311' sys.exec_prefix = '/opt/Production/swpdoc/venv311' sys.path = [ '/opt/Production/swpdoc/venv311/lib64/python311.zip', '/opt/Production/swpdoc/venv311/lib64/python3.11', '/opt/Production/swpdoc/venv311/lib64/python3.11/lib-dynload', ]``` Here is my httpd.conf ` WSGIScriptAlias / /opt/Production/swpdoc/techdocsweb/swpdoc/wsgi.py WSGIApplicationGroup %{GLOBAL} <Directory /opt/Production/swpdoc/techdocsweb/swpdoc> <Files wsgi.py> Require all granted </Files> … -
Python 3.12 pip install mod_wsgi fails
I am trying to deploy Django rest framework on my Debian 10 server. I am using Apache2 but he keeps crashing because its not using the right python version. I am using python3.12 version for my project : python --version Python 3.12.2 But Apache2 is running with python3.7 so its crashing because it cant find Django Module Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured I tried to install mod_wsgi with pip but I keep getting this error : /usr/bin/ld: final link failed: nonrepresentable section on output collect2: error: ld returned 1 exit status error: command '/usr/bin/gcc' failed with exit code 1 [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for mod_wsgi Failed to build mod_wsgi ERROR: Could not build wheels for mod_wsgi, which is required to install pyproject.toml-based projects Thanks to everyone fo your time ! I tried everything I found on existing topics. I am expecting a solution to be able to install mod_wsgi and use the right python version on my apache2 server -
cimpl.KafkaException: KafkaError{code=_INVALID_ARG,val=-186,str="Failed to create consumer: sasl.username and sasl.password must be set"}
I'm trying to build this Microservices project But get this error on consumer.py and also vsc says its unable to import confluent_ Here´s the code for consumer.py: import os import json import django from confluent_kafka import Consumer from rest_framework.exceptions import ValidationError os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") django.setup() consumer = Consumer({ 'bootstrap.servers': os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol': os.environ.get('KAFKA_SECURITY_PROTOCOL'), 'sasl.mechanism': 'PLAIN', 'sasl.username': os.environ.get('KAFKA_USERNAME'), 'sasl.password': os.environ.get('KAFKA_PASSWORD'), 'group.id': os.environ.get('KAFKA_GROUP'), 'auto.offset.reset': 'earliest' }) consumer.subscribe([os.environ.get('KAFKA_TOPIC')]) while True: msg = consumer.poll(1.0) if msg is None: continue if msg.error(): print(f"Consumer error: {msg.error()}") continue if msg is not None and not msg.error(): topic = msg.topic() value = msg.value() data = json.loads(value) print(f'Got this message with Topic: {topic} and value: {value}, with Data: {data}') if topic == os.environ.get('KAFKA_TOPIC'): if msg.key() == b'create_user': try: print(f"Order created successfully for user {data['userID']}") except ValidationError as e: print(f"Failed to create order for user {data['userID']}: {str(e)}") consumer.close() Here's producer.py: from confluent_kafka import Producer import os producer= Producer({ 'bootstrap.servers':os.environ.get('KAFKA_BOOTSTRAP_SERVER'), 'security.protocol':'SASL_SSL', 'sasl.mechanism': 'PLAIN', 'sasl.username':os.environ.get('KAFKA_USERNAME'), 'sasl.password':os.environ.get('KAFKA_PASSWORD'), }) I have tried downgrading my Python image from 3.12 to 3.10 but still doesnt work tried changing this FROM python:3.10 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app/ CMD python manage.py runserver 0.0.0.0:8000 -
Why do I receive 403 error while sending a post request using axios in my react file? And how should I code a sign up page from scratch?
I'm trying to code a sign up page in my django project. I have two apps named "api" and "frontend". I really am not sure if I'm doing it correctly but my main idea is to have a registeration form in http://127.0.0.1:8000/sign-up so that when the user presses the submit button, it would send a post request and my CreateUserView class in api/views.py would get that and the new user would be registered. frontend/urls.py: from django.urls import path from .views import index from api.views import RegisterView urlpatterns = [ path('sign-up', index), path('register', RegisterView.main), ] frontend/views.py: from django.shortcuts import render def index(request, *args, **kwargs): return render(request, 'frontend/index.html') frontend/src/components/App.js: import SignUp from "./SignUp"; import { BrowserRouter, Routes, Route } from "react-router-dom"; import { render } from "react-dom"; function App() { return ( <div> <BrowserRouter> <Routes> <Route path="/sign-up" element={<SignUp />} /> </Routes> </BrowserRouter> </div> ); } export default App; const appDiv = document.getElementById("app"); render(<App />, appDiv); frontend/src/components/SignUp.js: import React, { Component, Fragment, useState } from "react"; import axios from "axios"; function SignUp() { const [gmailAdress, setGmailAdress] = useState(""); const [username, setUsername] = useState(""); const [password, setPassword] = useState(""); return( <Fragment> <div> <button onClick={() => axios.post("/sign-up", { method: "POST", headers: { "Content-Type": "application/json" }, … -
Is there a way to optimize Large data set to load fast in Django
I have a model with over 6 millions object and anytime I am accessing the object page in my admin page its load very slow it even runs to time out sometimes and also the same thing to my view so I would like to get help if there is any recommendations method I can use for the issue. The project is hosted in AWS elastic beanstalk. The database configuration is attached to the Post Thanks in advance 🙂 Database configuration The database object I have increased the database resources but still the same. From db.t2.medium To db.t3.medium -
Swagger/drf_yasg: either schema or type are required for Parameter object (not both)
I have the following path: path('path/<int:object_id>', function, name='function'), The way it is, drf_yasg is generating the documentation for object_id as if it as a string: So I decided to manually input the information in the swagger_auto_schema decorator: @swagger_auto_schema( method='PATCH', manual_parameters=[ openapi.Parameter('object_id', openapi.IN_PATH, required=True, description='Object ID'), # query parameters ], # operation_description, responses, etc ) @api_view(['PATCH']) @permission_classes([IsAuthenticated]) def function(request, object_id) However, by doing this, drf_yasg raises the error either schema or type are required for Parameter object (not both)!, and I can't fix this unless I remove the object_id path parameter form the decorator Anyway, I'm interested in being able to explicitly descibe my path parameter in the decorator instead of letting drf_yasg doing this by myself How can I fix this? -
Getting error django with rabbitmq ImproperlyConfigured: Requested setting REST_FRAMEWORK
Hi Guys I'm newbie in django i try to integrate microservices django with rabbitmq but i got the error like this django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. can someone help me this is for my file manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys from MicroserviceImage.listenerRabbitMq import Command import threading def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) def start_consuming(service_name): Command().handle() if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MicroserviceImage.settings') # Start the consumer threads consumer_threads = [] for i in range(1): thread = threading.Thread(target=start_consuming, args=('crawler{}-service'.format(i),)) consumer_threads.append(thread) # Start all the threads for thread in consumer_threads: thread.start() # Run the Django management command main() and this is for setting.py """ Django settings for MicroserviceImage project. Generated by 'django-admin startproject' using Django 4.1.13. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ … -
Trying to consume API data from Django backend to React
I am trying to consume the Bing web search api. I have my view setup in Django backend. I was able to retrieve the search result data in terminal. But I am getting an error when fetching the data in React. If you could please help with a detailed response it would be much appreciated! Thanks in advance. Django runserver terminal when refreshing React page: 'name': 'iPhone 13 review | Tom&#39;s Guide', 'noCache': False, 'primaryImageOfPage': {'height': 80, 'imageId': 'OIP.63KzaXCF-d8nPkQdmM6bWgHaDL', 'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1', 'width': 80}, 'snippet': 'The<b> iPhone 13</b> is a great ' 'budget-friendly flagship phone with a ' 'brighter display, longer battery life and ' 'powerful cameras. Read our in-depth ' 'review to find out its strengths and ' 'weaknesses, and how it compares to the ' 'iPhone 14 and other models.', 'thumbnailUrl': 'https://www.bing.com/th?id=OIP.63KzaXCF-d8nPkQdmM6bWgHaDL&w=80&h=80&c=1&pid=5.1', 'url': 'https://www.tomsguide.com/reviews/iphone-13'}], 'webSearchUrl': 'https://www.bing.com/search?q=iphone+13'}} Internal Server Error: /home/ Traceback (most recent call last): File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\storm\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: AttributeError: 'list' object has no attribute 'get' [22/Mar/2024 14:15:37] "GET /home/ HTTP/1.1" 500 72597 SearchResults.js React file: import React, { useState, useEffect } from … -
Favicon Not loading in Django development as well as production
I have already tried all the solutions available as u can see in the code but No help. I can browse the favicon in my browser but not on webpage favicon U can see the no. of attempts base.html <link rel="shortcut icon" type="image/png" href="iitiansedu/static/image/favicon.png"> <link rel="shortcut icon" href="{% static 'iitiansedu/static/images/favicon.ico' %}"/> <link rel="icon" href="{% static 'iitiansedu/images/favicon.png' %}" type="image/x-icon"> <link rel="icon" href="{% static 'iitiansedu/images/favicon.ico' %}"> <link rel="icon" href="{% static 'images/favicon.png' %}"> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'images/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'images/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'images/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'images/site.webmanifest' %}"> <link rel="mask-icon" href="{% static 'images/safari-pinned-tab.svg' %}" color="#5bbad5"> url.py from django.contrib import admin from django.urls import path, include from . import views from django.conf import settings from .views import SearchView from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import include, path from django.views.generic.base import RedirectView from .views import * from django.templatetags.static import static from django.conf import settings from django.conf.urls.static import static from django.urls import path from django.contrib import admin from carousel import views as carousel_views favicon_view = RedirectView.as_view(url='/static/favicon.ico', permanent=True) urlpatterns = [ path('admin/', admin.site.urls), path('', views.HomePage.as_view(), name='home'), # path('favicon.ico', RedirectView.as_view(url='static/favicon.ico')), path('favicon.ico', RedirectView.as_view(url=static('favicon.ico'))), /etc/nginx/sites-enabled location = /favicon.ico { access_log off; log_not_found off; } location /static/ … -
Problems deploying Wagtail 6
I'm upgrading from Wagtail 4.2.4 to 6.0.1 and I made a lot of changes taking into consideration all the deprecated libraries. Everything works localy but when I try to deploy to my development site the GitHub Action runner fails with the following Error: remote: ModuleNotFoundError: No module named 'wagtail.contrib.modeladmin' remote: ! Error while running '$ python manage.py collectstatic --noinput'. I checked and the wagtail-robots library still uses the deprecated contrib.modeladmin. Any ideas? -
AUTH_USER_MODEL refers to model 'Socialmedia.User' that has not been installed
I created my custom user model and I have a function which allows users to sign in . I think my custom user model is incompatible with my function because it wouldn't allow me to do User.objects.get(username=username) . How can I fix this so I can use the db? AUTH_USER_MODEL refers to model 'Socialmedia.User' that has not been installed my views.py: def sign_up(request): if request.method == 'POST': username = request.POST.get("username").lower() password = request.POST.get("password") email = request.POST.get("email") password2 = request.POST.get("password2") users = User.objects.get(username=username) if users is not None: messages.error("The user already exists, please select a different username") else: user = User.objects.create_user(username=username, password=password, email=email) user.save() return render(request, 'usermgm/costume_register.html') models.py: in models i created imports: from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager models.py: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', 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_superuser') is not True: raise ValueError('Superuser must have is_superuser=True') return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_staff = … -
Change Windows Logon
I was researching how I could change Windows credentials to personalized ones, I saw that in old versions of Windows they used Gina, but now with Windows 10 we have to use the Credential providers, and I'm not a good understander of Windows, but the company where I'm interning told me to create a Windows login with facial recognition, can you tell me if this is possible and if it's possible what to use? Thank you very much I already have a project in Django with facial recognition for web attendance with anti-spoofing with connection to the Postgre database, I don't know if I can, for example, use a web view I already tried to create something with Gina, but I didn't get the expected result. -
django ActiveSession MultipleObjectsReturned
Every now and then I get complaints from users that they are unable to login. I see the following exception in debug.log. The database table authentication_activeSession has two entries for the user's session. The offending line of code is session = ActiveSession.objects.get(user=user) How should this be countered? File "/home/admin/site/django-api/api/submissions/viewsets/sitesubmissions.py", line 19, in create session = ActiveSession.objects.get(user=user) File "/home/siteadmin/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/siteadmin/.local/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.MultipleObjectsReturned( api.authentication.models.active_session.ActiveSession.MultipleObjectsReturned: get() returned more than one ActiveSession -- it returned 2! -
Django: "Cannot assign must be a "X" instance", don't want to fetch the object
I have the following view on my Django app and I need to update one object status_id is a ForeignKey field and it has some default values loaded via fixtures def stopObject(request, id_object): object = Object.objects.get(id=id_object) object.status_id = 1 object.save() I'm getting the classical error where I need to assign the object, not its Id. There are countless questions on SO about this problem, but I came looking for an answer I didn't found I know very well I can just perform a fetch from the database and assign to status, but I want to explore other possibilities, even though they may not be the best practices