Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I upload data to html from a database?
I have a home project, DRF is deployed in it, the database itself is on postgresql and I learned how to create a page template, BUT without data from the database. That's how I did it.: $ mkdir static $ vim Project1/settings.py $ cat Project1/settings.py ... from pathlib import Path import os ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'portfolio', 'ckeditor', 'ckeditor_uploader', ] ... TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'Project2')], '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', ], }, }, ] ... # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / "media/" ... $ mv Project2/css static/ $ ls static/ css $ vim Project2/index.html $ cat Project2/index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" href="{% static 'css/style.css' %}"> <title>Project2</title> </head> <body> <!--SECTIONS--> <!--CARDS--> <section> <div class="container"> <div class="cards"> <div class="card__content" id=""> <h2 class="card_hidden" onclick="card__hidden(this)">Опыт работы</h2> <div style="text-align: left;"> <ul> <li><strong> ' . $row['begin'] . ' - ' . $row['finish'] . ':</strong> ' . … -
Django google oauth2.0, i want to implement profile creation for my web app using build in google ouath2
i want to implement profile creation for my web app using build in google ouath2, i try to override auth.user model and inheritence from there info and create my own columns.But smth i do wrong, can someone help me.I need inheritence auth data from auth.user for CustomUser how to do this. models.py from django.contrib.auth.models import AbstractUser from .choices import STATUS_CHOICES, HOBBY_CHOICES, GENDER_CHOICES from django.db import models class CustomUser(AbstractUser): email = models.EmailField(unique=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='regular') hobby = models.CharField(max_length=200, choices=HOBBY_CHOICES) photo = models.ImageField(upload_to='profile_pics/', blank=True, null=True) city = models.CharField(max_length=100, blank=True) age = models.PositiveIntegerField(blank=True, null=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True) description = models.TextField(blank=True) groups = models.ManyToManyField( 'auth.Group', related_name='custom_user_groups', blank=True, verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', ) user_permissions = models.ManyToManyField( 'auth.Permission', related_name='custom_user_permissions', blank=True, verbose_name='user permissions', help_text='Specific permissions for this user.', ) def __str__(self): return self.username CustomUserCreationModel.py from django import forms from django.core.exceptions import ValidationError from .models import CustomUser from .choices import HOBBY_CHOICES, GENDER_CHOICES class CustomUserCreationForm(forms.ModelForm): hobby = forms.ChoiceField( choices=HOBBY_CHOICES, widget=forms.Select(attrs={'class': 'custom-dropdown form-control', 'id': 'Hobby'}) ) photo = forms.ImageField(widget=forms.FileInput(attrs={'class': 'custom-file-input'})) city = forms.CharField(widget=forms.TextInput(attrs={'class': 'custom-input'})) age = forms.IntegerField(widget=forms.NumberInput(attrs={'class': 'custom-input'})) gender = forms.ChoiceField( choices=GENDER_CHOICES, widget=forms.RadioSelect(attrs={'class': 'custom-radio'}) ) description = forms.CharField( widget=forms.Textarea(attrs={'class': 'custom-textarea'}) ) … -
django react project createAction not working
This is my actions.jsx: import { redirect } from "react-router-dom"; const URL = import.meta.env.VITE_BASE_URL; //Create Action export const createAction = async ({ request }) => { const formData = await request.formData(); const newBlog = { subject: formData.get("subject"), details: formData.get("details"), image_url: formData.get("image_url") } await fetch(`${URL}`,{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(newBlog) }); return redirect("/"); } export async function updateAction({ request, params }) { const formData = await request.formData(); const id = params.id; const updatedBlog = { subject: formData.get("subject"), details: formData.get("details"), image: formData.get("image_url") } await fetch(`${URL}${id}/`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(updatedBlog) }); return redirect(`./`); } //Delete Action export const deleteAction = async ({params}) => { const id = params.id; await fetch(`${URL}${id}/`, { method: "DELETE" }); return redirect("/"); } This is my Index.jsx: import Blog from "../components/Blog" import { Form, useLoaderData } from "react-router-dom" import { useState } from "react" export default function Index(props) { const allBlogs=useLoaderData() const [image, setImage] = useState('app.logomakr.com/3EC6KR') const handleInputChange = (event) => { setImage(event.target.value) } return( <> <h1>Index</h1> <hr/> <h1>Add a Post</h1> <Form action="/create" method="post"> <label htmlFor="subject"> Title: <input type="text" subject="subject" id="subject"/> </label> <label htmlFor="details"> Write your post here: <input type="textarea" name="details" id="details"/> </label> <label htmlFor="image_url"> Image Link: <input type="text" … -
No such file or directory: 'ffmpeg' in Django/Docker
I run my Django code in Docker. I run transcription software that requires ffmpeg to function. However I've been getting the error [Errno 2] No such file or directory: 'ffmpeg' whenever I try to run my code. Here's my views.py: def initiate_transcription(request, session_id): ... with open(file_path, 'rb') as f: path_string = f.name transcript = transcribe_file(path_string,audio_language, output_file_type) ... Here's my Dockerfile: # Pull base image FROM python:3.11.4-slim-bullseye # Set environment variables ENV PIP_NO_CACHE_DIR off ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV COLUMNS 80 #install Debian and other dependencies that are required to run python apps(eg. git, python-magic). RUN apt-get update \ && apt-get install -y --force-yes \ nano python3-pip gettext chrpath libssl-dev libxft-dev \ libfreetype6 libfreetype6-dev libfontconfig1 libfontconfig1-dev\ && rm -rf /var/lib/apt/lists/* RUN apt-get update && apt-get install -y git RUN apt-get update && apt-get install -y libmagic-dev RUN apt-get -y update && apt-get -y upgrade && apt-get install -y --no-install-recommends ffmpeg # Set working directory for Docker image WORKDIR /code/ RUN apt-get update \ && apt-get -y install libpq-dev gcc # Install dependencies COPY requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . I've searched online for possible solutions but have not been … -
Unable to link files with eachother in Django
I was working on something, and I'm stuck. Here is what I'm trying to do - suppose a user enters the order number on the site (named index.html), I would like to check if that order exists in the database. If it does, then it should redirect the user to the shipment page (shipment.html), where all the details are available regarding the same. I'm completely blank and not getting any ideas whatsoever. Please help. here it is what I tried doing, still not working! **here are the source code - ** Index.html - `{% block content %} {% csrf_token %} <button type="submit"> Track </button> </form> {% endblock %} {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %}` **views.py - ** def shipment(request): if request.method == 'POST': order_number = request.POST['order_number'] try: shipment = Shipment.objects.get(order_number=order_number) return redirect('shipment') except Shipment.DoesNotExist: message = f"Order ID {order_number} does not exist in the database." else: message = "" return render(request, 'index.html', {'message': message}) **models.py - ** class Shipment(models.Model): member_id = models.CharField(max_length=100) order_number = models.CharField(max_length=100) tracking_id = models.CharField(max_length=10) priority = models.IntegerField() current_location = models.CharField() destination … -
Django rest framework : unable to login user with correct email and password
I am new to Django. I am trying to build a simple login/registration with MongoDB as database. The user is successfully signing up but unable to login using correct password and email. Here is my serializers.py file class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'email', 'first_name', 'last_name', 'password') Here is my models.py file 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_doctor', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class User(AbstractBaseUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_doctor = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = UserManager() def __str__(self): return self.email Here is my views.py for Login @api_view(['POST']) @csrf_exempt def login_view(request): email = request.data.get('email') password = request.data.get('password') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) serializer = UserSerializer(user) return Response(serializer.data) else: return Response({'error': 'Invalid email or password'}, status=status.HTTP_401_UNAUTHORIZED) It is always shows the Invalid email or password. -
Issue with redirecting a user after successfully logging into a Django app
I have a written a django app which requires a user to log in to access certain pages. The login process is working correctly but when they log in they are not been sent to the correct page and a 404 error is being displayed. My URLS.py is path('contact/', views.contact, name='contact'), path('about/', views.about, name='about'), path('login/', LoginView.as_view ( template_name='app/login.html', authentication_form=forms.BootstrapAuthenticationForm, extra_context= { 'title': 'Log in', 'year' : datetime.now().year, } ), name='login'), My settings.py is """ " import os import posixpath DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True LOGIN_URL = '/api/login/' LOGIN_REDIRECT_URL = '/api/listsystemhazardcontrols/' ALLOWED_HOSTS = [] # Application references # https://docs.djangoproject.com/en/2.1/ref/settings/#std:setting-INSTALLED_APPS INSTALLED_APPS = [ 'app', 'rest_framework', 'rest_framework_simplejwt', 'djoser', # Add your apps here to enable them 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap5', ] # Middleware framework 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 = 'RiskManagementSoftware.urls' # Template configuration TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # 'DIRS': [], # … -
Trouble inserting modifiers inside kitchenorderitem in Django
I'm currently working on a Django project where I have models for kitchen orders. I'm encountering an issue where I can insert products into the kitchen order, but I'm unable to insert modifiers inside the products. Here's a simplified version of my code: item_id = uuid.uuid4() kitchen_order = KitchenOrderItem.objects.create( id=item_id, kitchen_order=instance, product_id=product.get("product_id"), quantity=product.get("quantity"), note=product.get("note"), ) for modifier in product.get("modifiers"): kitchen_order_items.append(KitchenOrderItem( modifier_id=item_id, product_id=modifier.get("product_id"), quantity=modifier.get("quantity"), note=modifier.get("note"), )) I expect the modifiers to be inserted along with the products, but it seems like only the products are being inserted into the database. Could anyone help me figure out what might be causing this issue? Am I missing something in my code or is there a better approach to achieve inserting both products and modifiers into the kitchen order? -
Celery Worker Doesn't Do Any Writes while Running In Docker
I don't know how to describe the problem but basically, I have a celery task that do some work and write objects to the database. from app.celery import celery_app from some.models import Thing import requests @celery_app.task def my_task_1(): response = requests.get("https://example.com/response1.json") things = [] for data in response.json()['records']: thing, _ = Thing.objects.get_or_create( name=data['name'], data=data['data'], ) things.append(thing) # ... snip ... @celery_app.task def my_task_2(): response = requests.get("https://example.com/response2.json") things = [] for data in response.json()['records']: thing, _ = Thing.objects.get_or_create( name=data['name'], data=data['data'], ) things.append(thing) # ... snip ... Tasks are being scheduled using django-celery-beat with only one worker. The code above works perfectly (or so I think) on my dev machine. however, when I deploy the project using docker I encounter some wired problem. 1- I could see that Thing objects are getting created. but not accessible? 2- The newly created Thing objects are not visible in django-admin. 3- Once I restart my worker the objects will be visible. My docker-compose file looks like this: version: '3' services: db: image: postgres:latest restart: always environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres volumes: - db_data:/var/lib/postgresql/data redis: image: redis:latest restart: always web: build: . restart: always command: /webserver-entrypoint.sh environment: POSTGRES_HOST: db CELERY_BROKER_URL: 'redis://redis:6379/0' CELERY_RESULT_BACKEND: 'redis://redis:6379/0' ports: … -
Docker error: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2
I've recently cloned my repository to a new device. My repository is run in a docker environment. However, despite having one successful docker image build on this device, whenever I try to build a new Docker image(by running docker build . ) I encounter this error when installing in requirements.txt: Dockerfile:30 -------------------- 28 | # Install dependencies 29 | COPY requirements.txt . 30 | >>> RUN pip install -r requirements.txt 31 | 32 | # Copy project -------------------- ERROR: failed to solve: process "/bin/sh -c pip install -r requirements.txt" did not complete successfully: exit code: 2 I haven't been able to find anything related to error code 2 online. I've restarted Docker and ran the command at least 10 times. I've also increased pip timeout to 2 mins using set PIP_TIMEOUT=120 but it still results in the same error. Here is the full traceback(along with the last package being installed: Collecting nvidia-cudnn-cu11==8.5.0.96 (from torch==2.0.1->-r requirements.txt (line 45)) 179.9 Downloading nvidia_cudnn_cu11-8.5.0.96-2-py3-none-manylinux1_x86_64.whl (557.1 MB) 239.0 ━━━━━━━━━━━━━━━━━╸ 250.1/557.1 MB 1.1 MB/s eta 0:04:38 239.0 ERROR: Exception: 239.0 Traceback (most recent call last): 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 438, in _error_catcher 239.0 yield 239.0 File "/usr/local/lib/python3.11/site-packages/pip/_vendor/urllib3/response.py", line 561, in read 239.0 data = self._fp_read(amt) if … -
EOF error occured in Docker compose up (Django)
I have EOF error when python manage.py makemigrations in docker compose up (0.001) SELECT "django_migrations"."id", "django_migrations"."app", "django_migrations"."name", "django_migrations"."applied" FROM "django_migrations"; args=(); alias=default Traceback (most recent call last): File "/code/manage.py", line 22, in <module> main() File "/code/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.10/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/core/management/commands/makemigrations.py", line 235, in handle changes = autodetector.changes( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 46, in changes changes = self._detect_changes(convert_apps, graph) File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 179, in _detect_changes self.create_renamed_fields() File "/usr/local/lib/python3.10/site-packages/django/db/migrations/autodetector.py", line 955, in create_renamed_fields if self.questioner.ask_rename( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 220, in ask_rename return self._boolean_input( File "/usr/local/lib/python3.10/site-packages/django/db/migrations/questioner.py", line 101, in _boolean_input result = input() EOFError: EOF when reading a line This is my Dockerfile FROM python:3.10.11 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ RUN chmod +x /code/entrypoint.sh ENTRYPOINT ["sh", "-c", "/code/entrypoint.sh"] And it is my docker-compose.yml version: '3.8' services: db: image: postgres:14.10-alpine volumes: - postgres_data:/var/lib/postgresql/data environment: - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} - POSTGRES_DB=${DB_NAME} django: build: . … -
how to redirect "back" button in browser using Django
I am developing a testing system for students using django, the idea is that if a student wants to pass a test, he must enter an access code that the teacher will send him. I faced the problem that when the student finished the test and clicked the send answers button and was transferred to the results page, he can return to the test by clicking the "back" button in the browser. I need that if he clicked this button on the results page, he would be transferred to the main page here is my code: def test(request): unique_code = request.POST.get('accessCode',None) first_name = request.POST.get('first_name',None) last_name = request.POST.get('last_name',None) if unique_code: try: # We get the model with a unique key TestFile = Test.objects.get(unique_code=unique_code) if not os.path.exists(TestFile.file.path): return HttpResponse('File not found') except Test.DoesNotExist: return HttpResponse('File not found') questions = [] answers = [] isQuestion = False with open(TestFile.file.path, "r", encoding="utf-8") as f: for line in f: # Checks if the string is not empty if line != '\n': if not isQuestion: questions.append(line.strip()) isQuestion = True else: tempAnswers = [] tempVal = line.strip() tempAnswers.append(tempVal) for temp_line in f: if temp_line == '\n': break tempAnswers.append(temp_line.strip()) answers.append(tempAnswers) isQuestion = False # We save the data … -
Custom manager isn't accessible via model instances
This is my model: class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=News.Status.PUBLISHED) class News(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'پیشنویس' PUBLISHED = 'PB', 'منتشر شده' user = settings.AUTH_USER_MODEL image = FileBrowseField( 'تصویر خبر', max_length=255, directory='news/', extensions=['.png', '.jpg'] ) title = models.TextField('عنوان خبر') slug = models.SlugField( 'نامک', max_length=255, unique=True, help_text=('نامک آدرس لینک خبر در مرورگر است و باید یکتا باشد.'), allow_unicode=True, ) author = models.ForeignKey( user, on_delete=models.CASCADE, related_name='news', verbose_name='نویسنده' ) body = RichTextUploadingField('متن خبر', config_name='extended') publish = models.DateTimeField('تاریخ انتشار', default=timezone.now) created = models.DateTimeField('تاریخ ایجاد', auto_now_add=True) updated = models.DateTimeField('بروزرسانی', auto_now=True) status = models.CharField( max_length=2, choices=Status.choices, default=Status.DRAFT ) objects = models.Manager() published = PublishedManager() class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish'])] verbose_name = 'اخبار' verbose_name_plural = 'اخبار' def __str__(self): return self.title But I get "AttributeError: Manager isn't accessible via News instances. Did you mean: 'publish'?" I've read other posts about this problem. None of them are applicable here? The above code is actually from a book called Django 4 by Example with slight modifications. -
Django formset is valid but returns empty dict list
I'm attempting to render a form that is a table where each row contains a name and a checkbox to allow the user to select players for a game. Googling around I've realized that I need to generate a formset so that each line in the table is a separate form. I finally have the table rendering correctly and posting without errors but what I've found is that while the formset is valid, the cleaned data contains a list of empty dicts. I found some StackOverflow posts that were similiar that said to create your own Formset class and set empty_permitted=True but that did not fix my issue. I can't seem to get passed this issue so any help is appreciated. Code Snippets # forms.py class InvitePlayerForm(forms.Form): """ Form to invite players to the new game """ invited = forms.CheckboxInput() class InvitePlayerFormset(BaseFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for form in self.forms: form.empty_permitted = False # views.py ef create_game_players(request): """ View to invite players to a game """ context = dict() # if this is a POST request we need to process the form data if request.method == "POST": num_players = request.session["invites"]["num_players"] print(f"num_players: {num_players}") invite_formset = formset_factory(InvitePlayerForm, formset=InvitePlayerFormset, extra=num_players) invite_forms … -
How to use django orm in python-socketio inside django project?
Now I created new app "ws" (it's in INSTALLED_APPS) and I use this code there in views.py: import socketio #from task_tracker.models import TaskColumn sio = socketio.Server(cors_allowed_origins="*") app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print(sid, 'connected') @sio.event def disconnect(sid): print(sid, 'disconnected') @sio.event def getColumns(sid, environ): print(environ) I run this code with: gunicorn -b 127.0.0.1:5000 --threads 50 views:app And everything is fine till I try to import my model from the other app. The error is: (venv) dbte5@Denis-MBP ws % gunicorn -b 127.0.0.1:5000 --threads 50 views:app [2024-04-05 18:00:52 +0500] [3112] [INFO] Starting gunicorn 21.2.0 [2024-04-05 18:00:52 +0500] [3112] [INFO] Listening at: http://127.0.0.1:5000 (3112) [2024-04-05 18:00:52 +0500] [3112] [INFO] Using worker: gthread [2024-04-05 18:00:52 +0500] [3113] [INFO] Booting worker with pid: 3113 [2024-04-05 18:00:52 +0500] [3113] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker worker.init_process() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/gthread.py", line 95, in init_process super().init_process() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() ^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() ^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/gunicorn/util.py", line 371, in import_app mod = … -
TemplateDoesNotExist using django_tables2
I'm developing a Python Django application and I've come across this error: when the view passes a table, I get a "TemplateDoesNotExist" error, but when passing a query, the template works. I've installed 'django_tables2' and added everything to the installed_apps in the settings.py file. The file log_allarmi.html extends componenti/list.html, which in turn extends base.html. Installed Apps - settings.py Template DIR - settings.py View log_allarmi Templates tree I have verified that everything was installed correctly, but I might have overlooked something. Thank you for the help. -
nginx no carga css, js, etc
Tuve el siguiente problema, tengo un sistema alojado en un droplet de digital ocean, soy nueva en este servidor asi que cualquier ayuda me sirve. El mismo funcionaba sin problema hasta que venció el dominio y dejo de cargar. Por cuestion de tiempo, el mismo debio volver a ser registrado y delegado ya que no alcance a renovar. Antes de ser registrado nuevamente se ingresaba mediante la ip publica y cargaba sin problema, por ejemplo http://125.31.190.131/home/ pero luego de hacer el proceso mencionado del dominio el acceso al sistema se empezó a cargar mediante el puerto 8001, es decir http://125.31.190.131:8001/home/ ya que si ingresaba como al principio solo levantaba apache y no el sistema en si. Por si sirve el sistema carga mediante gunicorn django/python y mediante nginx los archivos static El problema especifico seria nginx que dejo de responder ya que al ingresar al sistema no reconoce las rutas de los static. Me fije en los archivos log de error y no se encontraron, incluso las rutas de configuración donde se encuentran los static, tambien en la configuracion nginx se encuentra configurado "listen 80" y por las dudas quise cambiar a 8001 pero nginx deja de funcionar. -
Django deploy on Heroku causes causes too many connections error
I have a well-established Django app running on Heroku. It has a Heroku Postgres Standard 0 plan. My latest build upgraded the app to Python 3.12 and Django 4.0, as well as a few dependencies, specifically: redis>=4.0.0 APScheduler==3.10.4 mozilla-django-oidc==4.0.1 channels-redis==4.2.0 channels==4.0.0 daphne>=4.0.0 In addition, the channels upgrade broke part of my app which uses channels and I couldn't get the SSL None to work so I amended CHANNEL_LAYERS to: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [f"{REDIS_URL}?ssl_cert_reqs=none"] }, }, } Other than the above, there were no changes to any source code. I tested everything locally and again on my test Heroku Staging server and all was fine. When I deployed to my Heroku Production server my site ground to a halt with the following error: app/heroku-postgres source=HEROKU_POSTGRESQL_DB addon=postgresql-db sample#num_connections_over_limit=90 message=Database connections over limit. Please upgrade your database plan. In the end my only solution was to roll back to the previously deplyed version. I inspected the number of connections to the Postgres DB and found: In the original working deploy the number of connections would typically sit anywhere between 20 and 24 As soon as this new version was deployed the number of connections rocketed to … -
How to add an explicit field in UserSerializer?
The following error is being shown with the new release of python 3 in django and I can figure out how to get the URL running. from django.contrib import admin from django.urls import path, include from api.views import CreateUserView from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('admin/', admin.site.urls), path("api/user/register/", CreateUserView.as_view(), name="register"), path("api/token/", TokenObtainPairView.as_view(), name="get_token"), path("api/token/refresh", TokenRefreshView.as_view(), name="refresh"), path("api-auth/", include("rest_framework.urls")), ] urls.py from django.shortcuts import render from django.contrib.auth.models import User from rest_framework import generics from .serializers import UserSerializer from rest_framework.permissions import IsAuthenticated, AllowAny # Create your views here. class CreateUserView(generics.CreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [AllowAny] views.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User field = ["id", "username", "password"] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user serializers.py -
Real time data not display it return an error message: {"error": "'QuerySet' object has no attribute 'body'"}
I like to implement real time data display in django app using Ajax, i want to enable user to be able to see what they are writing in real time, to do this, i'm using django JsonResponse, using the below method: def get_real_time_data(request): if request.method == 'POST': body = request.POST.get('body') try: question = Question.objects.filter(body=body) if question is not None: content = question.body response_data = { 'content': content } return JsonResponse(response_data) else: return JsonResponse({'error': 'No content found for the given body'}, status=404) except Exception as e: return JsonResponse({'error': str(e)}, status=500) else: return JsonResponse({'error': 'Invalid request method'}, status=400) Using the above method, it's means, every time, a user started writing something in the form, the data will be displayed in real time, but I don't know why the data does not display, instead, it return an error message in the browser console: Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 :8000/get-real-time-data/:1 Failed to load resource: the server responded with a status of 500 (Internal Server Error) question/:89 {"error": "'QuerySet' object has no attribute 'body'"} error @ question/:89 jquery.min.js:2 POST http://127.0.0.1:8000/get-real-time-data/ 500 (Internal Server Error) … -
I am getting a console.log error in my django react application with CORS_ALLOWED_ORIGINS
According to the docs I have everything set up correctly but I am still getting an error. This is the error message from console.log() Access to fetch at 'http://127.0.0.1:8000/api/wells' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. This is the code from settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'wells', 'core', ] CORS_ALLOWED_ORIGINS = ['http://localhost:3000'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] According to the docs, this should work. So, I am not sure how to fix the error. -
SQLALCHEMY cursor and execute AttributeError
I'm currently using sqlalchemy 2.0.29 in django with postgres sql and while updating an entry i encountered AttributeError regarding cursor and execute. try: qry = "UPDATE fhc_imp_glidepath_initiatives SET canceller = 'tan.gt.1', end_date = '05/04/2024 10:08:03' WHERE uid = '2'" conn = sa.create_engine(f'postgresql://{user}:{pwd}@{srv}:{port}/{db}') cursor = conn.cursor() cursor.execute(qry) conn.commit() return True except Exception as e: print(e) return False What will be the solution or proper query to fix this? Thank you in advance. Expecting to fix the AttributeError regarding cursor and execute when using sqlalchemy 2.0.29 and knowing what's the correct syntax to use in this type of situation. -
issue in Django 5.0.2 and django_rest_framework
hi guys i have issue with reading sql data from postgresql with django. i created my model with manage.py inspectdb command from existing database. my model: from django.db import models class Regions(models.Model): code = models.CharField(unique=True, max_length=4) capital = models.CharField(max_length=10) name = models.TextField(unique=True) class Meta: managed = False db_table = "regions" My serializer: from rest_framework import serializers class RegionsSerializer(serializers.ModelSerializer): class Meta: model = "france.models.Regions" fields = "__all__" my viewset: from rest_framework import viewsets from rest_framework.response import Response from .models import Regions from .serializers import RegionsSerializer class RegionsView(viewsets.ViewSet): def list(self, request): regions = Regions.objects.all() serializer = RegionsSerializer(regions, many=True) return Response(serializer.data) and error i get: AttributeError at /regions/ 'str' object has no attribute '_meta' Request Method: GET Request URL: http://127.0.0.1:1000/regions/ Django Version: 5.0.4 Exception Type: AttributeError Exception Value: 'str' object has no attribute '_meta' Exception Location: C:\Projects\play_ground\python\django_one\venv\Lib\site-packages\rest_framework\utils\model_meta.py, line 35, in get_field_info Raised during: france.views.RegionsView Python Executable: C:\Projects\play_ground\python\django_one\venv\Scripts\python.exe Python Version: 3.12.2 Python Path: ['C:\\Projects\\play_ground\\python\\django_one', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\safkh\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Projects\\play_ground\\python\\django_one\\venv', 'C:\\Projects\\play_ground\\python\\django_one\\venv\\Lib\\site-packages'] Server time: Fri, 05 Apr 2024 08:19:46 +0000 can you help me with issue thnx all -
Question about auto re-issue Access token in Django (simple jwt)
Hello I have a question about JWT in backend django, so I'm leaving a question. (I'm using Simple-jwt package.) Currently, when the user logs in, both access and refresh tokens are being sent to the response body. (I'm trying to send refresh tokens to the header because there's a security problem.) At this time, when the access token expires, I know the procedure to reissue it through refresh, but I don't know how django will handle it automatically. I wanted to go to the procedure of reissuance before the expiration time of access at the front(web/app), but there is a problem that the access token increases indefinitely. When the front sends a general API request, I know that if client send both access and refresh, the access token will expire through the IsAuthenticated procedure at the back server, and I understand that it automatically reissues the access token through refresh and performs the previously requested API. So I tried Googling this, but I didn't see the code that automatically reissued it, only sending it to the endpoint (/jwt-token-auth/refresh/) provided by default. However, if I get caught in IsAuthenticated, the server spit out the error because it's invalid token, how do … -
How do I create separate fields for normal users and admins users in Django?
I have a custom user model that has fields common for both a normal user and an admin (which are email[used to log into the system], first name, and last name). But I want to give additional fields for the normal users of the system. How do I achieve this? class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, password=None): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) email = email.lower() user = self.model( email=email, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, first_name, last_name, password=None): user = self.create_user(email, first_name, last_name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) profile_picture = models.ImageField(default='default.jpg', upload_to='profilePictures', null=True, blank=True) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email + " | " + self.first_name Ii tried the above code but it only create a one single table for both normal users and admins