Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango captcha Error messages getting duplicated
my captcha error messages get duplicated my template error display code: {% if form.non_field_errors %} {% for error in form.non_field_errors %} <h3 style = "color:red;text-align:center">{{ error }}</h3> {% endfor %} {% elif messages %} {% for message in messages %} <h3 class = "{% if message.tags == 'success' %} message-green {% elif message.tags == 'error' %} message-red {% endif %}" style = "text-align:center">{{message}}</h3> {% endfor %} {% endif %} and my views: def Insertvalue(request): if request.method == "POST": form = EmpInsertForm(request.POST) if form.is_valid(): form.URL = request.POST.get('URL') form.email = request.POST.get('email') form.save() messages.success(request,'Info saved. Be on the lookout for a confirmation e-mail') else: messages.error(request,'Captcha not cleared. Please try again.') return render(request,'Index.html',{"form":form}) else: form = EmpInsertForm() return render(request,'Index.html',{"form":form}) the messages.error is the one that gets duplicated. to reproduce it, I first have to get the non field error which is bascally a unique_together error, and then get the captcha error and it will be printed as many times as I got the non field error + 1. Is there any way to delete all messages in the messages array if non field error is raised? Thank you in advanced. -
Work with django user permissions in ajax/jquery
Is it possible to user django permissions inside of ajax. I have the following code in a template in django which works perfect for checking permissions. {% if perms.users.change_account %} <a class="btn btn-info btn-sm" href="/users/account_edit/"> <i class="fas fa-pencil-alt"> </i> Edit </a> {% endif %} And i have a js file with ajax and wanted to add that check for permission when adding some elements to innerhtml const sendSearchData = (dev) => { $.ajax({ type: 'POST', url: '/customers/dev_search', data: { 'csrfmiddlewaretoken': csrfDevice, 'dev': dev, 'id': cid, }, success: (res)=> { const devData = res.data if(Array.isArray(devData)){ resultsListDev.classList.remove('not-visible') resultsListDev.innerHTML = "" devData.forEach(dev=>{ resultsListDev.innerHTML += ` <tr> <td> ${dev.name} </td> <td> # Is there a way to check user permissions in django from ajax and if it has a specific permissions # then display, like how can i check this in ajax "perms.users.change_account" <a class="btn btn-info btn-sm" href="/users/account_edit/"> <i class="fas fa-pencil-alt"> </i> Edit </a> </td> </tr> ` }) } }, error: (err)=> { console.log(err) } }) } No idea on how to check user permissions from ajax in django. Tried looking through documentation and searching web, but couldn't find anything. -
What exactly PyCharm Django Test run configuration do
I have a custom test command in my Django project: class Command(test.Command): def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( "--fit", action="store_true", help="Fit persistent tests instead of checking them.", ) def handle(self, *test_labels, **options): if options["fit"]: ... super(Command, self).handle(*test_labels, **options) It works when running from the console, e.g. python manage.py test --fit. However, when I'm using a PyCharm Django Tests configuration, it does not execute the handle(...) method. I can add --fit flag as an option and I can't add some random --qwerty flag. So, it means that the command is registered. While running in debug mode, I could reach the point in the add_arguments(...), but not in the handle(...) (as well as not in the django.core.management.commands.test.Command.handle(..), by the way). The only problem is that PyCharm executes this command some other way, without calling handle(...) method. So the question is - maybe someone know, what PyCharm is actually calling? -
Django upload many files & start working on them before all files are uploaded
Alright, I'm fairly new to asking questions here so bear with me. I've got a Django app that is currently in production and I'm trying to access uploaded files as each one finishes uploading rather than after all files have completed the upload process. The current solution: Upload of 10000 files starts Upload finishes Backend analyzes files asynchronously and streams them to the front in cooperation with my JS. The solution I'd like to implement: Upload of 10000 files starts Backend asynchronously analyzes the files as they come and streams them to the front end in cooperation with my JS Upload finishes I honestly just don't know where to start here and I'd appreciate any indication of the right way to do this. Additional info: Application coded in Python3.11/Django4.2/CSS(2023)/JS(ECMAScript) Files are uploaded using a JS drag & drop datastream and submitted via a Django FileField with a forms.ClearableFileInput() that accepts multiple files Application deployed on a Ubuntu 22.04 LTS server via Nginx & Gunicorn Each file analyzed can be anywhere from 17kb to 12mb By 'analyzes' I mean that calculations are run on each file to then my app produces a list of calculated values When I say that my … -
send an email to my gmail address with django in cpanel server
I have a Cpanel server which runs a Django app, and I have a form in my website that I want erverytime an anonymous user has filled the form a new email send to my Gmail address, I dont know the best practice to implement this scenario -
Attribute error : force_str(urlsafe_base64_decode(uid))
id= force_str(urlsafe_base64_decode(uid)) user=Customuser.objects.get(id=id) File "C:\Users\Abhishek\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\http.py", line 198, in urlsafe_base64_decode s = s.encode() AttributeError: 'NoneType' object has no attribute 'encode' It should not raise error during decode -
How to debug Django app with Spyder (and breakpoints)
So I created a project but if I press run, of course execute the python file I am looking at so I need to specify to run the classic manage.py but as far I can see that configuration is not by project but globally. So I can configure globally to run manage.py runserver and fix that issue easily but the second one is on how to connect for breakpoints usage without specify in the code for the pdb functions (I can find only that). Months ago I forked the original django-pdb to bump the django support https://github.com/Mte90/django-pdb-extended but the problem is that execute pdb on the whole page automatically. Online there aren't any information useful about Django for spyder, but also for Flask (to get inspiration for the configuration). I am writing here to see if someone has more hints on to achieve to use that editor to develop (and debug) in Django. -
upstream timed out error in ubuntu, using nginx, uwsgi
i'm working on a django project, and i deployed it with AWS, ubuntu, nginx and uwsgi. It work's well, but everytime i try to run a feature with big throughput, an error message below comes out and the feature doesn't work. And also i searched stack overflow, and i couldn't find someone having the same 'Unknown error' like mine. 2023/11/07 15:14:13 [error] 7487#7487: *1 upstream timed out (110: Unknown error) while reading response header from upstream, client: xx.xxx.xxx.xxx, server: _, request: "POST /file_upload/upload/ HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/docusift/uwsgi.sock", host: "xx.xxx.xxx.xx", referrer: "http://xx.xxx.xxx.xx/success_with_token/WeDkQYs84hDYcDsl/" (I hided my public ip with 'x') So i searched google, and i found that i should set the nginx, uwsgni settings. I setted up my settings like below, but it still has the same error above. [uwsgi] chdir=/home/ubuntu/docusift/blog module=blog.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/home/ubuntu/docusift/debug_uwsgi.log home=/home/ubuntu/docusift/venv virtualenv=/home/ubuntu/docusift/venv socket=/home/ubuntu/docusift/uwsgi.sock chmod-socket=666 socket-timeout=600 harakiri = 300 http-timeout = 300 server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; proxy_buffer_size 512k; proxy_buffers 16 512k; proxy_busy_buffers_size 1024k; proxy_connect_timeout 500s; proxy_send_timeout 500s; proxy_read_timeout 500s; send_timeout 500s; } location /static/ { alias /home/ubuntu/docusift/blog/staticfiles/; } http { upstream django { server unix:/home/ubuntu/docusift/uwsgi.sock; } client_max_body_size … -
django model migration problem table already exist
hello i have a legacy database which contain a users table and I want just to add to this table some field and override abstract base user of Django model auth the problem is when I am trying to migrate is says that the table users is already exist in database from django.contrib.auth.base_user import AbstractBaseUser,BaseUserManager from django.db import models import sha512_crypt import time # function that return actual timestamp def actual_epoch_time(): return int(time.time()) class UserManager(BaseUserManager): def create_user(self,email,username,password=None): user = self.model(email = normalize_email(email),username=username) user.set_password(password) user.save() return user def create_superuser(self,email,username,password=None): user = self.create_user(username=username,password=password,email=email) user.is_admin = True user.save() return user #here is the abstracted user model from xui database with additional fields class Users(AbstractBaseUser): username = models.CharField(max_length=50, blank=True, null=True,unique=True) password = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) ip = models.CharField(max_length=255, blank=True, null=True) date_registered = models.IntegerField(default=actual_epoch_time()) last_login = models.IntegerField(blank=True, null=True) member_group_id = models.IntegerField(blank=True, null=True) credits = models.FloatField(blank=True, null=True) notes = models.TextField(blank=True, null=True) status = models.IntegerField(blank=True, null=True) reseller_dns = models.TextField(blank=True, null=True) owner_id = models.IntegerField(blank=True, null=True) override_packages = models.TextField(blank=True, null=True) hue = models.CharField(max_length=50, blank=True, null=True) theme = models.IntegerField(blank=True, null=True) timezone = models.CharField(max_length=255, blank=True, null=True) api_key = models.CharField(max_length=64, blank=True, null=True) objects = UserManager() USERNAME_FIELD = 'username' class Meta: managed = True db_table = 'users' def … -
Caddy: How to serve static files from Django
It's my first experience with Caddy and I'm having dificulties to configure it properly concerning static files. I'm using an Ubuntu server and I'm running Caddy and Django+Gunicorn as Docker containers. It works perfectly well except that it gives a 404 on static files such as CSS and JS files. I've collected all static files to their corresponding directories in /home/myusername/static and have the following Caddyfile: mydomain.com { encode gzip handle_path /static/* { root * "/home/myusername/static/" file_server } handle_path /media/* { root * "/home/myusername/media/" file_server } reverse_proxy django-gunicorn-container-name:8000 } What should I do to make Caddy serve static files correctly? Any suggestions will be much appreciated! Thanks! -
In Django, how to remove language prefix conditionnally after internationalization ? Media file src problem
In a django project, after a query I'm sending image srcs to a JS file that will then create popovers dynamically on my home page using these image srcs and some text data. ex : popover_photo.src = 'media/' + popover_data['photo__src'] After adding internationalization to my project, all my pages are prefixed by language code like 'en' or 'es', the problem being that my image srcs also gets prefixed by a language code automatically. Instead of having 'media/my-exemple-image.png' I will get 'en/my-exemple-image.png' and the image file won't be found. So, is there a way to remove language prefix conditionnally in django on a particular endpoint OR more specifically, is there a way to exclude my call to my media folder from having a language prefix ? Thanks in advance if any dev is willing to share a workaround about this ! My main urls.py currently looks like this (I'm still in development, but I'm going to use AWS S3 in a bit to stock my images, might the same problem occur?): urlpatterns = [ path('admin/', admin.site.urls), path('__debug__/', include('debug_toolbar.urls')), ] urlpatterns += urlpatterns + i18n_patterns( path('rosetta/', include('rosetta.urls')), path('', include('core.example_app.urls', namespace='example_app')), ) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
The tests are failing in GitHub Actions
I'm writing the backend on Django in a Docker container. I've created models and tests for them, and here's the issue: the tests pass locally and everything works fine. However, when I push the code to GitHub, I encounter this error during test execution in GitHub Actions: `django.db.utils.OperationalError: connection to server at "db" (172.18.0.2), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? Error: Process completed with exit code 1. Please, can you help me with this? Docker-compose.yml version: '3.11' services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./app:/app command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme depends_on: - db db: image: postgres:13-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASSWORD=changeme volumes: dev-db-data: Dockerfile FROM python:3.11.5-alpine LABEL maintainer="https://github.com/Arvitheslayer" ENV PYTHONUNBUFFERED 1 COPY ./requirements.txt /tmp/requirements.txt COPY ./requirements.dev.txt /tmp/requirements.dev.txt COPY ./app /app WORKDIR /app EXPOSE 8000 ARG DEV=false RUN python -m venv /py && \ /py/bin/pip install --upgrade pip && \ apk add --update --no-cache postgresql-client && \ apk add --update --no-cache --virtual .tmp-build-deps \ build-base postgresql-dev musl-dev && \ /py/bin/pip … -
Issue with signup and signin in django
this is my views.py from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.messages.views import SuccessMessageMixin from django.views.generic.edit import CreateView from django.urls import reverse_lazy from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout #################################################### class Main(TemplateView): template_name = 'emnosys/main.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['css_file'] = 'styles.css' return context ################################################### def Registration(request): if request.method == "POST": username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] myuser = User.objects.create_user(username, emnail, password1) myuser.save() return redirect('signin') return render(request, "emnosys/registration.html") ############################################### def signin(request): if request.method == 'POST': username = request.POST['username'] password1 = request.POST['pass1'] user = authenticate(username=username, password=password1) if user is not None: login(request, user) return render(request, "authentication/index.html") else: return redirect('home') return render(request, "emnosys/signin.html") ################################################ def signout(request): logout(request) return redirect('home') This is my urls from django.urls import path from . import views from .views import Main urlpatterns = [ path('', Main.as_view(), name='home'), path('registration/', views.Registration, name='registration'), path('signin/', views.signin, name='signin'), path('signout/', views.signout, name='signout'), ] this is my registration.html !DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="../../static/emnosys/css/styles-registration.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action=""> <div class="login"> <h3>Registration</h3> <form action="/signup" method="post"> {% csrf_token %} <label for="">Username</label> <input type="text" … -
Django Ninja REST API to React - Forbidden (CSRF cookie not set.)
I made a Django REST API using Ninja API, and most calls work, except POST, DELETE, etc.. CONFIGURATIONS Django site URL: http://127.0.0.1:8000/ API CALL: http://127.0.0.1:8000/hello Methode: POST Parameters: None settings.py: INSTALLED_APPS: [..., "corsheaders"...] MIDDLEWARE: [..., "corsheaders.middleware.CorsMiddleware"...] # Set CORS settings CORS_ALLOW_ALL_ORIGINS = True CORS_ORIGIN_ALLOW_ALL = True CSRF_HEADER_NAME = "HTTP_X_CSRFTOKEN" CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ] CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_NAME = "X-CSRFToken" CSRF_HEADER_NAME = "X-CSRFToken" CSRF_TRUSTED_ORIGINS = [ "http://localhost:3000", ] generate csrf token for react GET: @router.get("/get_csrf_token", summary="Get CSRF Token") def get_csrf_token(request: HttpRequest) -> JsonResponse: """.""" csrf_token = get_token(request) print("TOKEN: ", csrf_token) return JsonResponse({"csrf_token": csrf_token}) hello POST rest api call: @api.post("/hello") def hello(request: HttpRequest, data: HelloSchema) -> str: """.""" return f"Hello {data.name}" React site When I make a call to django I get a csrf_token: const tokenResponse = await axios.get("/login/get_csrf_token"); const csrfToken = tokenResponse.data?.csrf_token; which is used in my REST API /hello call: const response = await axios.post("/hello", { headers: { "Content-Type": "application/json", "X-CSRFToken": csrfToken, }, credentials: "include", }); PROBLEM First, I fetch the CSRF token from my Django REST API and use this CSRF token in my HEADER for the POST calls, but I get a forbidden 403 every time. I know it's because I'm messing up the CSRF token, but … -
Error while connecting to MSSQL db using django application running on apache web server with ODBC17
Im trying to connect to a MSSQL2012 db with django 4.2.4, the application is running on an Apache2 web server using mod_wsgi running on debian12. Im getting the followinf error "('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SSL Provider: [error:0A00014D:SSL routines::legacy sigalg disallowed or unsupported] (-1) (SQLDriverConnect)')". db config in settings.py: DATABASES = { 'default': { 'ENGINE': 'mssql', 'NAME': '****', 'USER': '****', 'PASSWORD': '****', 'HOST': '192.168.50.20', 'PORT': '1433', 'OPTIONS': { "driver": "ODBC Driver 17 for SQL Server", "MARS_Connection": "True", }, }, } wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PortaleScot.settings') application = get_wsgi_application() apache virtual host <VirtualHost *:443> DocumentRoot /var/www/PortaleScot/ ServerName *****.it ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess PortaleScot python-path=/var/www/PortaleScot/ python-home=/var/www/PortaleScot/venv/ WSGIProcessGroup PortaleScot WSGIScriptAlias / /var/www/PortaleScot/PortaleScot/wsgi.py <Directory /var/www/PortaleScot/> Require all granted </Directory> Alias /static/ /var/www/PortaleScot/scotHub/static/ <Directory /var/www/PortaleScot/scotHub/static/> Require all granted </Directory> <IfModule mod_ssl.c> SSLEngine on SSLCertificateFile /etc/letsencrypt/live/portalescotsrl.it/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/portalescotsrl.it/privkey.pem SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+EXP </IfModule> Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> The driver is installed correctly and everything works just fine when ran locally using manage.py runserver or when trying to access it with tsql from the cli, but it doesnt work with apache. I think it might be a problem with wsgi/apache not being configured properly but nothing i've tried seemd to work. -
TinyMCE in a Django template
I am trying to implement an TinyMCE textarea in my Django project on the frontend via an template. When i use the js statement nothing happens. I have tried to run the same code on a 'Normal' Webserver and it worked out of the Box. Here is my Code: html file: {% extends "base.html" %} {% load static %} {% block content %} <script src="https://cdn.tiny.cloud/1/bkgmn58j8jobid31da2q8ncozamffoi5pkzf9115d22j593x/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script> <script> tinymce.init({ selector: 'textarea#content', plugins: 'ai tinycomments mentions anchor autolink charmap codesample emoticons image link lists media searchreplace table visualblocks wordcount checklist mediaembed casechange export formatpainter pageembed permanentpen footnotes advtemplate advtable advcode editimage tableofcontents mergetags powerpaste tinymcespellchecker autocorrect a11ychecker typography inlinecss', toolbar: 'undo redo | blocks fontfamily fontsize | bold italic underline strikethrough | link image media table mergetags | align lineheight | tinycomments | checklist numlist bullist indent outdent | emoticons charmap | removeformat', tinycomments_mode: 'embedded', tinycomments_author: 'Author name', mergetags_list: [ { value: 'First.Name', title: 'First Name' }, { value: 'Email', title: 'Email' }, ], ai_request: (request, respondWith) => respondWith.string(() => Promise.reject("See docs to implement AI Assistant")), }); </script> <textarea id="content"></textarea> {% endblock content %} -
How to Add search Bar in Django raw_id_fields?
So here is the problem I a facing, I have multiple apps in one app have all the contact info of my users and other apps are my departements where I will register the users form contact app. I used raw_id_fields to extend thier info and achieve what I want this is the problem enter image description here When i click on that maginyfing Glass it takes me to contacts but it has no search bar [no search bar in raw_id_fields}(https://i.stack.imgur.com/Ywp0e.png) How to do i add the bar in it This is my code class PersonRegistrationAdmin(admin.ModelAdmin): list_display = ('person_role', 'contact') search_fields = ('contact__name', 'contact__phone_number', 'contact__email', 'contact__date_of_birth', 'contact__cnic') raw_id_fields = ('contact',) admin.site.register(PersonRegistration, PersonRegistrationAdmin) I tried a few ways but looks like I could not achieve what I want -
How to capture Data from a column and add it to a dropdown menu for a form to fill another table
Here is my Model. I would like to capture the data in column "Address" then display it in a dropdown menu for a form that i am using to fill another table instead of typing the email address again. Create your models here. class Employee(models.Model): address = models.EmailField(max_length=100,null=True) first_name = models.CharField(max_length=50,null=True) sec_name = models.CharField(max_length=50,null=True) department = models.CharField(max_length= 50,null=True) company = models.CharField(max_length= 50,null=True) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.first_name + ' - ' + self.department This is the form i am using to add data to the second model class SaveCategory(forms.ModelForm): name = forms.CharField(max_length="250") description = forms.Textarea() status = forms.ChoiceField(choices=[('1','Active'),('2','Inactive')]) class Meta: model = Category fields = ('name','status') def clean_name(self): id = self.instance.id if self.instance.id else 0 name = self.cleaned_data['name'] # print(int(id) > 0) try: if int(id) > 0: category = Category.objects.exclude(id=id).get(name = name) else: category = Category.objects.get(name = name) except: return name raise forms.ValidationError(f"{name} Category Already Exists.") This is the model i am adding data into. class Category(models.Model): name = models.CharField(max_length=250) status = models.CharField(max_length=2, choices=(('1','Active'),('2','Inactive')), default=1) date_created = models.DateTimeField(default=timezone.now) date_updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name -
Django Test Detail View Returns 404 with object created in testcase
Im trying to create a detail view with a form because i need the reference of the object i use in the form. Pardon the spanglish. Heres the code below: The view: class CreateSolicitud(FormMixin, generic.DetailView): model = models.Solicitud_Curso template_name = 'forms/formulario_estudiantes.html' form_class = forms.CreateSolicitudF success_url = reverse_lazy('solicitud:home') def get_form_kwargs(self) -> dict[str, Any]: dict = super().get_form_kwargs() aux = models.Curso.objects.filter(id=self.get_object().id) cursos = models.CursosNecesarios.objects.filter(id=aux) dict['quantity'] = len(cursos.curso_necesario) dict['cursos'] = cursos.curso_necesario def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid: return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form: Any) -> HttpResponse: form.save() return super().form_valid(form) the form: class CreateSolicitudF(forms.Form): nombre = forms.CharField(max_length=255) apellido = forms.CharField(max_length=255) foto_carnet1 = forms.ImageField() foto_carnet2 = forms.ImageField() titulo = forms.FileField() institucion = forms.CharField() aval = forms.FileField() certificacion_ingles = forms.FileField() titulo_informacion = forms.FileField() def __init__(self, *args, **kwargs) -> None: self.quantity = self.kwargs.pop('quantity', None) self.cursos = self.kwargs('cursoskey', None) self.curso = self.kwargs.pop('curso', None) super().__init__(*args, **kwargs) count = 0 while count < self.quantity: self.fields['archivo' +str(count)] = forms.FileField() def save(self, commit=False): solicitud = models.Solicitud_Curso.objects.create( nombre = self.nombre, apellido = self.apellido, foto_carnet_cara = self.foto_carnet1, foto_carnet_tapa = self.foto_carnet2, titulo = self.titulo, institucion = self.institucion, aval = self.aval, certificacion_ingles = self.certificacion_ingles, titulo_informacion = self.titulo_informacion, curso = self.curso ) solicitud.save() cursos = models.CursosNecesarios.only('curso_necesario').filter(curso_id=self.cursos) cursos_solicitud = models.Solicitud_Curso_Necesario.objects.create(solicitud=solicitud) cursos_solicitud.save() for i … -
Django-simple-history: serializer m2m objects
I'm using django-simple-history==3.2.0 library and my models show below: class Employee(models.Model): last_name: str | None = models.CharField(max_length=100, null=True) # type: ignore first_name: str | None = models.CharField(max_length=100, null=True) # type: ignore middle_name: str | None = models.CharField(max_length=100, null=True) # type: ignore job_title: str | None = models.CharField(max_length=512, null=True) # type: ignore class Meta: app_label = "task_flow" class Assignment(models.Model): overdue: int = models.IntegerField(null=True) # type: ignore # ManyToManyField executors: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="executor_assignments", blank=True) # type: ignore coordinators: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="coordinator_assignments", blank=True) # type: ignore approvers: QuerySet[Employee] = models.ManyToManyField(Employee, related_name="approver_assignments", blank=True) # type: ignore # ForeignKey status: Status | None = models.ForeignKey(Status, on_delete=RESTRICT, related_name="assignments") # type: ignore access: Access = models.ForeignKey(Access, on_delete=RESTRICT, related_name="assignments", default=Access.Choices.general, null=True, blank=False) # type: ignore document_type: DocumentType | None = models.ForeignKey(DocumentType, on_delete=SET_NULL, null=True, related_name="assignments") # type: ignore domain: Domain = models.ForeignKey(Domain, on_delete=RESTRICT, null=False, related_name="assignments", default=Domain.Choices.internal) # type: ignore source: str | None = models.CharField(max_length=2048, null=True, blank=True) # type: ignore created_at: datetime = models.DateTimeField(auto_now_add=True) # type: ignore updated_at: datetime = models.DateTimeField(auto_now=True) # type: ignore history = HistoricalRecords(m2m_fields=[executors, coordinators, approvers]) So, now i want to serializer Assignment.history.all() queryset with employees all fields like this: "results": [ { "id": 551, "overdue": 243, "executors": [ { "id": 32, "last_name": "Копытов", … -
PyLint Django: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured
My Django app works fine when i am just launch my application through python src/manage.py runserver But i would like to integrate pylint here, and when i launch the command pylint src --load-plugins pylint_django i got the following traceback: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 87, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 102, in __getattr__ self._setup(name) File "/venv/lib/python3.11/site-packages/django/conf/__init__.py", line 82, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MO DULE or call settings.configure() before accessing settings. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/venv/lib/python3.11/site-packages/pylint_django/checkers/foreign_key_strings.py", line 114, in open django.setup() File "/venv/lib/python3.11/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/venv/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/venv/lib/python3.11/site-packages/django/apps/config.py", line 178, in create mod = import_module(mod_path) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 1126, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load … -
Combining two Queryset for sorting , Django
I have two Queryset result. I need to combine before it gets sorted. How to solve this problem in Django? And it should convert it back to Queryset for sending it to template. Tried to convert it to a list but its not converts back to Queryset. -
Stripe payment gateway not working after Installing certbot ssl certificate in django site
Stripe payment gateway in my django website was working fine but after installing certbot ssl certificate Stripe payment gateway not working. I am getting error - No api proxy found for service "urlfetch". you can see error in this image do I need to change payment gateway??? -
Running docker with mysql and django bachend
My first time dealing with docker and i kinda can't start it up properly. This is my docker-compose.yml file: version: "3" services: mysql: image: mysql container_name: my-mysql restart: on-failure ports: - 3306:3306 volumes: - ./mysql_data:/var/lib/mysql environment: MYSQL_ROOT_PASSWORD: "" MYSQL_USER: intranet MYSQL_PASSWORD: "" MYSQL_DATABASE: intranet MYSQL_ALLOW_EMPTY_PASSWORD: yes healthcheck: test: [ "CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-pmy-root-password", ] interval: 10s timeout: 5s retries: 5 backend: build: context: . dockerfile: Dockerfile container_name: my-backend restart: on-failure volumes: - .:/app environment: DATABASE_URL: mysql2://intranet@mysql:3306/intranet SECRET_KEY: x ports: - 8000:8000 depends_on: - mysql command: ["./etc/entry", "web-prod"] I created in mysql workbench database 127.0.0.1:3306 with name intranet and code in it: CREATE USER 'intranet'@'localhost'; CREATE DATABASE intranet; GRANT ALL PRIVILEGES ON intranet.* TO 'intranet'@'localhost'; FLUSH PRIVILEGES; And I got dockerfile like this: FROM python:3.7 RUN wget https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O /usr/local/bin/cloud_sql_proxy \ && chmod +x /usr/local/bin/cloud_sql_proxy RUN pip3 install poetry ENV LC_ALL C.UTF-8 ENV LANG C.UTF-8 # -- Install Application into container: WORKDIR /app COPY pyproject.toml pyproject.toml COPY poetry.lock poetry.lock RUN poetry config virtualenvs.create false && poetry install COPY . /app ARG GIT_VERSION ENV GIT_VERSION $GIT_VERSION ENTRYPOINT ["/app/etc/entry"] CMD ["web-prod"] When running docker-compose up i got this error: django.db.utils.OperationalError: (1045, "Access denied for user 'intranet'@'172.19.0.3' (using password: NO)") … -
Double nested loop in Django HTML template not getting desired results
I have been staring at this one for a while and need some help. I am trying to display a 'quit' button instead of a 'book' button on days where a logged in user has already booked into a session. Can someone please provide some guidance here? Models class Member(models.Model): gym = models.ForeignKey(Gym, on_delete=models.CASCADE, blank=True, null=True, related_name="gym_membership") member = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name="member_of_gym") def __str__(self): return f'{self.member.username}' class Session(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, blank=True, null=True, related_name="session_program") focus = models.ForeignKey(Focus, on_delete=models.CASCADE, blank=True, null=True, related_name="session_focus") location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=True, null=True, related_name="session_location") booking_counter = models.IntegerField(default=0) start_datetime: datetime = models.DateTimeField() duration = models.DurationField() day = models.CharField(max_length=12, blank=True, null=True) week_number = models.IntegerField(blank=True, null=True) def __str__(self): return f'{self.program}, {self.day} - Week {self.week_number}' class Booking(models.Model): member = models.ForeignKey(Member, on_delete=models.CASCADE, blank=True, null=True, related_name="member_booking") session = models.ForeignKey(Session, on_delete=models.CASCADE, blank=True, null=True, related_name="booking_session") booking = models.BooleanField() date_booked = models.DateTimeField() date_cancelled = models.DateTimeField(blank=True, null=True) attendance_verified = models.BooleanField(blank=True, null=True) def __str__(self): return f'{self.member.member.username} booked {self.session}' Views def index(request): # store the user information in a variable user = request.user # get the membership object for that user member = Member.objects.get(member=user.id) context = { "sessions": Session.objects.all(), "bookings": Booking.objects.filter(member=member) } return render(request, "booking/index.html", context) index.html {% extends "booking/layout.html" %} {% block body %} …