Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to regroup Django commands in sub directories?
How can I regroup management commands? I tried the following but the 2 commands are not discovered by Django. I also tried with an import in the commands/__init__.py file without success. myapp/ management/ __init__.py commands/ __init__.py user_management/ __init__.py create_user.py delete_user.py -
AttributeError EmailAddressManager object has no attribute is_verified
I get the following error while attempting to a register a user with the help of DRF, dj-rest-auth and django-allauth: AttributeError at /api/v1/dj-rest-auth/registration/ 'EmailAddressManager' object has no attribute 'is_verified' Here is a part of settings.py file: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', "django.template.context_processors.request", ], }, }, ] EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" SITE_ID = 1 and project level urls.py file: urlpatterns = [ path('admin/', admin.site.urls), path('', include('apps.pages.front.urls')), path('api/v1/', include("apps.contacts.api.urls")), path('api-auth/', include("rest_framework.urls")), path("api/v1/dj-rest-auth/", include("dj_rest_auth.urls")), path("api/v1/dj-rest-auth/registration/", include("dj_rest_auth.registration.urls")), ] (i'm keeping my apps in a dedicated apps folder. and have created a custom user model) Leaving the email field empty will successfully register a new user, but it won't work if i add an email. -
How to pass a dictionary through to a template in Django
I am watching a django tutorial (Corey Schafer on how to build a webapp, however I had to use a different method of getting the template to appear. That is all working well. The function he uses has an argument where I don't, that allows the dictionary to appear on the site. Any ideas on how to fix this? (sorry if this is a rookie question, I'm very new) from django.shortcuts import render from django.http import HttpResponse from django.template import loader def home(request): context = { 'news': news } template = loader.get_template('home.html') return HttpResponse(template.render()) I tried to pass it through alongside template.render() and it made all of the raw HTML code come up on screen. -
Django Admin is not Showing
What is the problem below and how to solve it? After runserver I didn't see the admin panel. `Page not found (404) “E:\Masud Ahmad\Pyhood\MyBlogs\blogone\admin” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/admin Raised by: django.views.static.serve Using the URLconf defined in blogone.urls, Django tried these URL patterns, in this order: admin/ base/ [name='base'] [name='home'] ^(?P.*)$ The current path, admin, matched the last one.` I tried to fix, I checked the code repeatedly, but couldn't point out the problem. -
Django (rest framework) performance of queryset union versus Q versus other ideas
I am creating a search functionality that searches through multiple models that have relations to my main model. Using Django rest framework I then return a paginated result back on every object of my main model that is related to the search query. As the searches are quite "wildcard" like and search in text fields I want to make this as performant (good performance?) as possible. Currently I have implemented it using queryset unions, thinking at least the querysets are lazy loading. When trying to implement it using Q() I had to go through getting the actual foreign key constraints IDs as value_lists and I think that makes for more computation needed? But I don't have a good sense on what is what in terms of performance. To clarify performance: I want low CPU and memory usage on the host itself (these are EC2 instances in AWS) and am slightly less concerned about DB performance (RDS instance in AWS) but it is of course still important. Current code: def get_queryset(self): search_query = self.request.query_params.get('search_query', None) modelA_used = self.request.query_params.get('modelA', 'not_used') modelB_used = self.request.query_params.get('modelB', 'not_used') modelMain_description = self.request.query_params.get('description', 'not_used') modelMain_subject = self.request.query_params.get('modelMain_subject', 'not_used') modelC_used = self.request.query_params.get('modelC', 'not_used') if search_query: queryset = modelMain.objects.none() if … -
django-select2 with crispy form
Currently, i am building a form. There should be two Multiple Select Box (pillbox), but it is not showing up correctly. What could be the error? I have already done all the necessary installation and included it in my path forms.py: class CreateModuleForm(forms.ModelForm): module_lead = forms.ModelChoiceField(queryset=CustomUser.objects.filter(role_fk__name='professor'), label="Module Lead",widget=Select2Widget(attrs={'data-placeholder': 'Select Module Lead', 'class': 'form-control'})) professors = forms.ModelMultipleChoiceField(queryset=CustomUser.objects.filter(role_fk__name='professor'), required=False, widget=Select2MultipleWidget(attrs={'data-placeholder': 'Select Professors', 'class': 'form-control', 'data-maximum-selection-length': 10})) courses = forms.ModelMultipleChoiceField(queryset=Course.objects.all(), required=False, widget=Select2MultipleWidget(attrs={'data-placeholder': 'Select Courses', 'class': 'form-control', 'data-maximum-selection-length': 10})) class Meta: model = Module fields = ['code', 'name', 'credit', 'start_date', 'end_date', 'enrollment_limit', 'description'] widgets = { 'code': forms.TextInput(attrs={'class': 'form-control'}), 'name': forms.TextInput(attrs={'class': 'form-control'}), 'credit': forms.NumberInput(attrs={'class': 'form-control'}), 'start_date': forms.DateInput(format=('%Y-%m-%d'), attrs={'class': 'form-control', 'type': 'date'}), 'end_date': forms.DateInput(format=('%Y-%m-%d'), attrs={'class': 'form-control', 'type': 'date'}), 'enrollment_limit': forms.NumberInput(attrs={'class': 'form-control'}), 'description': forms.Textarea(attrs={'class': 'form-control'}), } def __init__(self, *args, **kwargs): super(CreateModuleForm, self).__init__(*args, **kwargs) self.fields['module_lead'].empty_label = None template.html: {% extends "admin_lms/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block extrahead %} <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" /> {{ form.media.css }} {% endblock %} {% block content %} <div class="container"> <h2>Create Module</h2> <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Create</button> <a href="{% url 'index' %}" class="btn btn-secondary">Back</a> </form> </div> {% endblock %} {% block extrajs %} <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script> {{ form.media.js }} … -
Auto reload on adding or updating object in django admin
I want to know if there is a way to auto-reload the Django application when adding or updating an object in the Django admin ? Actually, when I add or update an object, I have to reload my application, and I no longer want this behavior, please -
Django rest framework + React JSX app Google Authentication
I'm creating a web application for my university gymnasium. It requires me to add the functionality to let the university members to register using their university google account and any external users to register using their email. They cannot use google login. I can create the external user registration process, but I don't know how to create the Registration with google account part. I tried several times to do this watching youtube videos and several online articles but, I still don't understand how to do this. https://github.com/TKBK531/gym_application This is my github repository for the project. I'm still relatively new to this area and I would love some advice. Thanks. -
Django + Vuejs | Forbidden (403) CSRF verification failed. Request aborted. | Reason given for failure: CSRF cookie not set
i am currently implementing VueJS in my Django application. During it's early development i had no reason to use any frontend framework due to the original scope of the project. but now after many months it has come to my desk the need for a better frontend solution. i choose VueJS for various reason. i have encoutered this problem while trying to log in: my error While implementing the Login / Registration feature i went with this choices: Firstly this is my settings.py: """ Django settings for project project. Generated by 'django-admin startproject' using Django 3.2.19. 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/ """ import os from pathlib import Path from dotenv import load_dotenv import environ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) env = environ.Env( # Definisci i valori di default per le variabili DEBUG=(bool, False) ) env_file = os.path.join(BASE_DIR, '.env.staging') if os.path.isfile(env_file): environ.Env.read_env(env_file) DOMINIO_INVITO_EMAIL = env('DOMINIO_INVITO_EMAIL', default='localhost:8000') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # CSRF_TRUSTED_ORIGINS = ['https://ea7f-84-221-58-53.ngrok-free.app'] … -
Ajax not giving Json response with django data base create thing
Hey I am learning django. I am trying a basic thing with ajax and django. function RegisterEmail() { $.ajax({ type: "POST", url: "/registerBackend", data: { email: $("#email").val(), csrfmiddlewaretoken: $('[name=csrfmiddlewaretoken]').val(), }, success: function () { alert("Success! Check email to start making your portfolio") }, error: function () { alert('error'); } }); } here is the ajax response code def registerBackend(request): email = request.POST.get("email") print("here") return JsonResponse({"status": "success"}) this is working perfectly fine printing here and also giving success alert. def registerBackend(request): email = request.POST.get("email") Pros.objects.create(email=email) print("here") return JsonResponse({"status": "success"}) while this is perfectly creating pros object in table AND ALSO PRINTING HERE but not showing the success alert. I have zero idea why this is working like this. while this is perfectly creating pros object in table AND ALSO PRINTING HERE but not showing the success alert. I have zero idea why this is working like this. -
Different translations for different sites
I am building a directory engine with Django. It will be used on different domains, such as houses.com and games.com etc. There's a button on the header, which is 'Add Item' which redirects to item creation page. It's wrapped with {% trans %} tag. But I want translation of that button to be "Add your house" on houses.com and "Add Your Game" on games.com. What is best practice for doing that? I was expecting to find a solution for that. -
Dependency Conflicts with drf-haystack==1.8.13 and djangorestframework==3.15.0
I recently upgraded my Django version from 4.0 to 4.2, which necessitated an upgrade of djangorestframework to version 3.15.0 due to compatibility issues (Django REST Framework 3.15.0). However, I'm encountering a dependency conflict with drf-haystack. The latest version of drf-haystack (1.8.13) has a requirement for djangorestframework to be <=3.14. Here is the warning I'm receiving: Warning!!! Possibly conflicting dependencies found: * drf-haystack==1.8.13 - djangorestframework [required: >=3.7,<=3.14, installed: 3.15.0] Is there a way to resolve this dependency conflict without downgrading djangorestframework? Would forking drf-haystack and adjusting its dependencies be a viable solution? I tried downgrading djangorestframework to 3.14 but I am skeptical about its compatibility with Django 4.2 as Django's 4.2 version is not mentioned in the requirements of djangorestframework==3.14 https://github.com/encode/django-rest-framework/tree/3.14.0?tab=readme-ov-file#requirements -
rembg_cars: {"error": "[Errno 2] No such file or directory: 'carros.pth'"}
I am trying to remove BG from car using rembg-cars Python package. But here I am facing a problem. {"error": "[Errno 2] No such file or directory: 'carros.pth'"}.. Most likely here have not given the custom model. How effective (rembg-cars) Python package? output_data = remove(input_data , model_name="carros") -
I cant get my token in permissions even though i send it. Django rest framework
I have created simple permission class to protect my view. class StaffOnly(permissions.BasePermission): def has_permission(self, request, view): token = request.META.get('HTTP_TOKEN', False) # Always returns False user = CustomUser.objects.filter(token=token) # Which means no user found if user.exists(): # This line won`t execute user = user.get(token=token) return user.role > 0 else: raise PermissionDenied('No token') View itself: @api_view(["GET"]) @permission_classes([StaffOnly]) def book_list(request): book_list = InfoBook.objects.all() serializer_list = InfoBookSerializer(book_list, many=True) return Response(data=serializer_list.data, status=status.HTTP_200_OK) Then I was trying to send request from the client side. // This is the part of React`s Component`s code. I`m sure that I`m not sending blank token and url is correct fetch(HTTP + DOMAIN + API + VERSION + GETBOOKS, { headers: { "Token" : props.token } }) .then(res=>res.json()) .then(data => setBooks(data)) Unfortunatelly my permission class always denies access because of no token provided. As you can see, Im sending propriate header and I still can`t get access to it for some reason. Because Im sort of newbie I don``tt know the reason why it is happening. I``` ve figured out that I can` ``t get access to my token-header in permission class but I can access it inside of view. # Client`s side request is the same @api_view(["GET"]) # @permission_classes([StaffOnly]) # … -
how to bring the neo4j dashboard to a django webapp?
I am working on a Django webapp that that requires to show the neo4j dashboard to the user, the user should be able to see the nodes and relationships between them like the way it is shown in the neo4j dashboard. I want it to be interactive so that the user can explore the relationships btw each of the nodes, just like they can in the neo-dash app. Is there any way i can achieve this? I thought about bringing the neo4j dashboard as an iframe in the webapp but after searching for a solution for a while , i can't find a good way to do it yet. I currently just query the database for the data and produce graphs with either plotly or chart.js but what i really want to show are the relationships btw the nodes as it is shown in the neo-dash. -
Unable to integrate django_vite
My setup: Django 5.0.6, React 18.2.0, Vite 5.1.6, @vitejs/plugin-react 4.2.1. I have a very minimal setup, trying to to setup django and react together using django_vite but failing to do so. Getting the following issue as soon as I start importing components(function components) into my main.jsx component. Below are the configs. // package.json "dependencies": { "vite": "^5.1.6", "@vitejs/plugin-react": "^4.2.1", "antd": "^5.17.0", "axios": "^1.6.8", "bootstrap": "^5.3.3", "exif-js": "^2.3.0", "exifr": "^7.1.3", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.22.3", "react-toastify": "^10.0.5" }, "devDependencies": { "@types/react": "^18.2.64", "@types/react-dom": "^18.2.21", "eslint": "^8.57.0", "eslint-config-airbnb": "^19.0.4", "eslint-plugin-import": "^2.29.1", "eslint-plugin-jsx-a11y": "^6.8.0", "eslint-plugin-react": "^7.34.1", "eslint-plugin-react-hooks": "^4.6.2", "eslint-plugin-react-refresh": "^0.4.5" } // settings.py STATIC_URL = 'static/' STATIC_ROOT = 'staticfiles/' STATICFILES_DIR = [ BASE_DIR / 'dist' ] DJANGO_VITE = { "default": { "dev_mode": DEBUG } } // vite.config.js export default defineConfig({ base:'/static/', build:{ emptyOutDir:true, manifest:'manifest.json', assetsDir:'', outDir:'./dist', rollupOptions:{ input:{ home:"./frontend/main.jsx" } } }, resolve: { alias: { '@': path.resolve(__dirname, './frontend'), '@styles': path.resolve(__dirname, './frontend/assets/styles'), }, }, plugins: [react()], }); // home.html {% load django_vite %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {% vite_hmr_client %} {% vite_asset './frontend/main.jsx' %} <title>Document</title> </head> <body> <div id="app"> </div> </body> </html> I have tried integrating with django_vite_plugin as well which shows the same error. … -
Why SQLite tables are not created in my Django app? [duplicate]
in the django app i am working on, i often need to rebuild/restructure the whole database because of changes that arise during development. the db backend i am using is sqlite3 and i work under windows 11. the problem is that, once i manually delete the db.sqlite3 and the migrations folder, the newly created database does not contain any table generated by my django models, no matter how many times i execute makemigrations or migrate from the command prompt, even if called in admin mode. what am i doing wrong? -
sqlite3.OperationalError: no such column: user_customuser.fullname
My django app is throwing this error on trying to use the createsuperuser command even after deleting the db file and syncing again: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such column: user_customuser.fullname The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/Henkan/main_store/manage.py", line 22, in <module> main() File "/home/Henkan/main_store/manage.py", line 18, in main execute_from_command_line(sys.argv) models.py from django.contrib.auth.models import AbstractUser from django.db import models from .managers import UserManager from upload.models import Product from django.conf import settings class CustomUser(AbstractUser): previous_orders = models.ManyToManyField(Product,related_name = 'previous_orders') cart = models.ManyToManyField(Product,related_name = 'cart') address = models.TextField(default='Address not provided') fullname = models.CharField(max_length=20,default='Name') email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['fullname'] objects=UserManager() def get_url(self): token = settings.F.encrypt(bytes(self.email,encoding='utf8')) return token managers.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): def create_user(self, email, password = None, **extra_fields): if not email: raise ValueError('Email is required') extra_fields['email'] = self.normalize_email(email) user = self.model(**extra_fields) user.set_password(password) user.save(using=self.db) def create_superuser(self, email, password = None, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) extra_fields.setdefault('is_active',True) return self.create_user(email, password, **extra_fields) The code was working before,but I was trying to switch to fullname instead of username which resluted … -
Python packages for Windows (pywin32, pywinauto) hosted on Linux server
I made Django project for automation on Windows machines (user machines will be also on Windows platform) using pywinauto package. I wanted to deploy it on Linux server but it cannot install pywin32 and pywinauto packages. What is the right way of solving this problem, Dockerizing, using some other alternative packages that is similar to the pywinauto style like -> ( send_to = zoom_app.Zoom.child_window(title_re="Send to.*", control_type="Edit", found_index=0).wrapper_object() ) or something else ? I try to deploy it on Linux and also creating Docker image but I had to write in requirments.txt for these packages that they are for Windows platform... -
NextJS POST requests with fetch or axios are switched to GET in production
I have a project using NextJS and Django as a RESTful API. Locally, when running the project, everything works fine. The POST requests are running well. On production server, Ubuntu, using Nginx as the webserver, pm2 for running NextJS and Gunicorn for running the Django project, I don't know why, for some reason, all the POST requests from the server-side of NextJS are getting transformed to GET (I am logging the API logs, and it shows me GET requests instead of POST) Does anyone know what could be the possible cause? -
Django authentication and redirect in views vs in template include
I'm using django for a web project I wan't to render a page for unauthenticate users and one for authenticated. Is it better to define this directly in my view : def get(self, request, *args, **kwargs): if not request.user.is_authenticated: return render (request, 'unauthenticated.html') else: return render (request, 'authenticated.html') Or use only one view, but root them in my template : def get(self, request, *args, **kwargs): return render (request, 'index.html') <!-- index.html --> {% if not user.is_authenticated %} {% include "unauthenticated.html" %} {% else %} {% include "authenticated.html" %} {% endif%} (My question is about both security and implementation) -
Why my def perform_update() doesn't work in Django rest framwrok?
i want when user update a data of leave request django will send email to supervisor of that user perform_create is work but perform_update don't work Here's my code that's problem def perform_update(self, serializer): with transaction.atomic(): try: leave_request = serializer.instance serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Updated Leave Request") except Exception as e: logger.error(f"Error during leave request update: {str(e)}") raise e Here's CLass class LeaveRequestList(generics.ListCreateAPIView): serializer_class = leave_requestsSerializer def get_queryset(self): queryset = leave_requests.objects.all() location = self.request.query_params.get('location') if location is not None: queryset = queryset.filter(testLocation=location) return queryset def perform_create(self, serializer): with transaction.atomic(): try: leave_request = serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Leave Request") except Exception as e: logger.error(f"Error during leave request creation: {str(e)}") raise e def perform_update(self, serializer): with transaction.atomic(): try: leave_request = serializer.instance serializer.save() supervisor = leave_request.user.supervisor if supervisor and supervisor.email: self.send_leave_request_email(leave_request, supervisor.email, "Updated Leave Request") except Exception as e: logger.error(f"Error during leave request update: {str(e)}") raise e def send_leave_request_email(self, leave_request, supervisor_email, subject): try: datetime_start_formatted = leave_request.datetime_start.strftime("Date: %d %B %Y Time: %I:%M:%S %p") datetime_end_formatted = leave_request.datetime_end.strftime("Date: %d %B %Y Time: %I:%M:%S %p") duration = (leave_request.datetime_end - leave_request.datetime_start) days = duration.days hours, remainder = divmod(duration.seconds, 3600) minutes, _ = divmod(remainder, 60) first_name = … -
pyperclip not working on ubuntu 22.04 server
When I was running my install requirement.txt file I got: Warning Using legacy 'setup.py install' for pipfile, since package 'wheel' is not installed Also Pyperclip could not find a copy/paste mechanism for your system Uninstalled it: pip uninstall pyperclip As suggested here, I tried: https://github.com/dependabot/dependabot-core/issues/5478 pip install pyperclip --use-pep517 And pip install wheel pip install pyperclip Tried both solutions at different times, no more warning Then when using my webapp I was getting this error: Pyperclip could not find a copy/paste mechanism for your system Went to this page https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error Tried sudo apt-get install xsel uninstall sudo apt-get install xclip uninstall pip install PyQt5 and PyQt6 uninstall Tried a combo of sudo apt-get install xsel pip install PyQt5 Nono of them worked This is beyond me, was hoping just by adding this commands it would resolve it but feels like something is missing, like the packages are not communicating. On my template I have a submit input tag. This runs a function on my view that parses the user's table and generates a text, I want to use pyperclip to copy this text to the user's clipboard. As a good noob I want to say, 'It runs on my machine', … -
Optimizing Django app for large users requests and dataset in Elastic beanstalk
i have a web app which is hosted in EB and working perfectly but i notice that whenever the users on the website are getting larger or the requests are getting larger the websites slows and even run to Gateway Timeout in fron-end and also Target.Timeout in the instance heath but when the requests on the website or the users on the website get low againn the website will load faster. i have change my Database instance type to db.t3.medium but stiill use to have more upto 99% usage when the website is slow. the EC2 on the EB is running on t3.micro and i have make the auto scaling to have upto 10 instance but sometimes it create upto 8 EC2 instance. Please i am looking for the best way to know what eexactly and why the website laoding slow so i can know what to do next. If you need any other information kindly ask and it will be providded Thanks -
django not showing correct page with url
here is my url code: from django.urls import path from .views import index urlpatterns = [ path('', index), path('join', index), path('create', index), path('join/1', index) ] here is the react code: import React, { Component } from 'react'; import RoomJoinPage from './RoomJoinPage'; import CreateRoomPage from './CreateRoomPage'; import { BrowserRouter as Router, Routes, Route, Link, Redirect } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Routes> <Route exact path='/' element={<p>This is the Home Page</p>} /> <Route path='/join' element={ <RoomJoinPage /> } /> <Route path='/create' element={ <CreateRoomPage /> } /> </Routes> </Router> ); } } and to sum up my issue, I am not seeing the react component "RoomJoinPage" when navigating to /join/1.