Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use the OpenAI stream=true property with a Django Rest Framework response, and still save the content returned?
I'm trying to use the stream=true property as follows. completion = openai.Completion.create( model="text-davinci-003", prompt="Write me a story about dogs.", temperature=0.7, max_tokens=MAX_TOKENS, frequency_penalty=1.0, presence_penalty=1.0, stream=True, ) Unfortunately, I don't know what to do from here to return it to my React frontend. Typically, I've used standard response objects, setting a status and the serializer.data as the data. From my readings online, it seems I have to use the StreamingHttpResponse, but I'm not sure how to integrate that with the iterator object of completion, and actually save the outputted data once it is done streaming, as the view will end after returning the iterator to the endpoint. Any help? -
How to fix? Error 500: No WSGI daemon process called... (Apache/ Django)
I have an internal Server Error 500 on my Django Server. When I check the error.log, I get the following error: No WSGI daemon process called "..." has been configured: "..." I hope someone can help me to fix this Error. Here is my Apache config: <VirtualHost *:80> ServerAdmin ADMIN ServerName DOMAIN ErrorLog /home/USER/PROJECT/site/logs/error.log CustomLog /home/PROJECT/PROJECT/site/logs/access.log combined Alias /static /home/USER/PROJECT/static <Directory /home/USER/PROJECT/static> Require all granted </Directory> <Directory /home/USER/PROJECT/src/social> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess PROJECT python-path=/home/USER/PROJECT/ python-home=/home/USER/PROJECT/VIRTUALENV WSGIProcessGroup PROJECT WSGIScriptAlias / /home/USER/PROJECT/src/social/wsgi.py </VirtualHost> -
Django runserver not working; Did I miss something?
It's been a while since I posted anything here, and now my problems have become more advanced. For reference, I'm running on Win10. I'm trying to use the Django framework. Python's been installed on my computer forever; it's the latest version, and it's installed on environment variables/added to system paths. I think those are enabled by default, but I did make sure that they were checked when I reinstalled it. pip's been updated too. Django installed successfully. I managed to get all the way to installing my new project with django-admin startproject PROJECTNAME, but when I try to run python3 manage.py runserver I'm getting this error: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. ...Interesting. If I type in python --version, I get a response (Python 3.11.0). Here's what I get if I do pip freeze: asgiref==3.6.0 Django==4.1.6 sqlparse==0.4.3 tzdata==2022.7 Python IDLE runs fine; all .py files run fine. Alright. So, with that in mind and in accordance to a lot of popular advice I've seen floating around, I added the Path to my Environment Variables. For space-saving reasons, my Python is installed on … -
Defaulting to user installation because normal site-packages is not writeable : While nstallinng DjangoCorsHeaders
$ pip3 install django-cors-headers $ Defaulting to user installation because normal site-packages is not writeable I got this Error . I tried $ python3.10 -m pip install django-cors-headers But it's not works for mycase . -
Issue importing application in Django in urls.html
My src directory's layout is the following: Learning innit.py settings.py urls.py wsgi.py pages innit.py admin.py apps.py models.py tests.py views.py Views.py has this code from django.shortcuts import render from django.http import HttpResponse def home_view(*args,**kwargs): return HttpResponse("<h1>Hello World, (again)!</h1>") urls.py has this code """Learning URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path("", home_view, name = "home"), path('admin/', admin.site.urls), ] The part where it says 'pages.views' in 'from pages.views import home_view' has a yellow/orange squiggle underneath it meaning that it is having problems importing the file and it just doesn't see the package/application called 'pages' and doesn't let me import it even though the package has a folder called 'innit.py'. Even worse is the fact that the tutorial I … -
Django ALLOWED_HOSTS settings
I developing a mobile application, using react-native like a front-end and python Django REST framework like a back-end. The question is what I should write in Django settings.py ALLOWED_HOSTS, besides my server's adress? I don't use any website like a front-end, because my application is on App Store and Google Play. If I will write ['*'], it certainly will work, but it is not a safe method -
Unable to load fixture for through model django
What I am trying to do? I have created a fixture for my through model and now I want to load it in my database. What is the problem? While loading the fixture using Django loaddata command for through model I get this error: django.core.serializers.base.DeserializationError: Problem installing fixture '<fixture-path>/fixtures/m.json': ['“Dave Johnson” value must be an integer.']: (room.membership:pk=None) field_value was 'Dave Johnson' models.py class Person(models.Model): name = models.CharField(max_length=100, unique=True) def natural_key(self): return self.name class Group(models.Model): name = models.CharField(max_length=100, unique=True) members = models.ManyToManyField(Person, through='Membership') def natural_key(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) joined_on = models.DateTimeField(auto_now_add=True) def natural_key(self): return self.person.name, self.group.name I am creating fixture like this: python manage.py dumpdata room.Membership --pks='12' --natural-foreign --natural-primary > m.json which creates the following json: [ { "model": "room.membership", "fields": { "person": "Dave Johnson", "group": "Django Learning", "joined_on": "2020-12-03T13:14:28.572Z" } } ] I have also added get_by_natural_key method in the manager for through model like this: class MembershipManager(models.Model): def get_by_natural_key(self, person_name, group_name): return self.get(person__name=person_name, group__name=group_name) But loading the fixture like below gives the above error python manage.py loaddata m.json Loading of fixtures for other models is working fine but it only happens with through model. -
showing two model in same page Django
I have two models : class Post(models.Model): title= models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() postimage = models.ImageField(null= True, blank= True, upload_to="images/") created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title + " | "+ str(self.author) def get_absolute_url(self): return reverse('article_deatil', args=(str(self.id))) class AboutMe(models.Model): title1= models.CharField(max_length=255, default="About Me") body = models.TextField() skill1= models.CharField(max_length=255) skill1body = models.TextField() skill2= models.CharField(max_length=255) skill2body = models.TextField() skill3= models.CharField(max_length=255) skill3body = models.TextField() edu1=models.CharField(max_length=255) edu1body = models.TextField() edu2=models.CharField(max_length=255) edu2body = models.TextField() edu3=models.CharField(max_length=255) edu3body = models.TextField() def __str__(self): return self.title1 I want to show both of them in my home.html class HomeView(ListView): model = Post template_name = 'home.html' queryset = Post.objects.order_by('-published_date')[:3] url.py urlpatterns = [ path('',HomeView.as_view(), name="home"), path('',PostViewList.as_view(), name="postlist"), ] I'm new to django and not sure how to show case two model in one template. I did put the post.body and other tags in my html but it not showing the About me part. I really appreciate your help. thank you -
facing this error while trying to get request invalid literal for int() with base 10: b'10 00:00:00'
i was trying to do get request to the url http://127.0.0.1:8000/books/list/ but im now facing an erorr invalid literal for int() with base 10 `i was trying to do get request to the url http://127.0.0.1:8000/books/list/ but im now facing an erorr invalid literal for int() with base 10` #my views.py from django.shortcuts import render from book_api.models import Book from django.http import JsonResponse from book_api.serializer import BookSerializer from rest_framework.response import Response from rest_framework.decorators import api_view # Create your views here. @api_view(['GET']) def book_list(request): books=Book.objects.all() serializer=BookSerializer(books,many=True) return Response(serializer.data) @api_view(['POST']) def book_create(request): serializer=BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) #my serializer.py from rest_framework import serializers from book_api.models import Book class BookSerializer(serializers.Serializer): id=serializers.IntegerField(read_only=True) title=serializers.CharField() number_of_pages=serializers.IntegerField() publish_date=serializers.DateField() quantity=serializers.IntegerField() def create(self,data): return Book.objects.create(**data) #book_api.urls from django.contrib import admin from django.urls import path from book_api.views import book_list,book_create urlpatterns = [ path('',book_create), path('list/',book_list) # book/urls.py """BOOK URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the … -
Multilingual site django
I need to make a multilingual website and have found instructions on how to do this. I did everything according to the instructions but when I write /en/ for example nothing happens settings.py from pathlib import Path from django.utils.translation import gettext_lazy as _ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/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 ALLOWED_HOSTS = [] # LOGIN_URL = '/users/login' AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' # Application definition SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainConv', 'users', 'modeltranslation', 'gettext', ] LANGUAGES = [ ('en', _('English')), ('ru', _('Russian')), ] LOCALE_PATHS = [ BASE_DIR / 'locale/', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Converter.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Converter.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'sxgc1', … -
Apach24 and Django in Windows
I would be very grateful if anyone can help. I am trying to start Apache server on my laptop with Windows 11. I entered command "mod_wsgi-express module-config" and got next: LoadFile "C:/Program Files/WindowsApps/PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0/python310.dll" LoadModule wsgi_module "C:/Users/Sergey/ProgPython/CabeeFashion/my_env1/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/Sergey/ProgPython/CabeeFashion/my_env1" All these I added to httpd.conf file, but when I am trying to start httpd.exe, I am getting next error:cannot load httpd.exe: Syntax error on line 539 of C:/Users/Sergey/ProgPython/CabeeFashion/Apache24/conf/httpd.conf: Syntax error on line 1 of C:/Users/Sergey/ProgPython/CabeeFashion/Apache24/conf/extra/httpd-wsgi.conf: Cannot load C:/Program Files/WindowsApps/PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0/python310.dll into server: \xce\xf2\xea\xe0\xe7\xe0\xed\xee \xe2 \xe4\xee\xf1\xf2\xf3\xef\xe5. I used extart file httpd-wsgi.conf and included it in httpd.conf Include conf/extra/httpd-wsgi.conf How can I fix this. Why http.exe says me cannot lod file, if it exists. I have checked version of Apache and wsgi modules, all of them are 64. VC is installed. -
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' (render.com)
I'm trying to deploy a simple CRUD Django app suing the service of render.com. I have set up the config based on their documentation, but when I try to deploy it, the error ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' comes up. Build error Feb 4 10:45:16 AM ==> Cloning from https://github.com/user/django-crud-app... Feb 4 10:45:20 AM ==> Checking out commit ed701ede6bde3f7c7abd1378f656c7763b063917 in branch main Feb 4 10:45:24 AM ==> Using Python version: 3.7.10 Feb 4 10:45:28 AM ==> Running build command 'pip3 install -r requirements.txt'... Feb 4 10:45:29 AM ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' Feb 4 10:45:29 AM WARNING: You are using pip version 20.1.1; however, version 23.0 is available. Feb 4 10:45:29 AM You should consider upgrading via the '/opt/render/project/src/.venv/bin/python -m pip install --upgrade pip' command. Feb 4 10:45:29 AM ==> Build failed 😞 Feb 4 10:45:29 AM ==> Generating container image from build. This may take a few minutes... I have generated my requirements.txt See Image Here asgiref==3.6.0 autopep8==2.0.1 dj-database-url==1.2.0 Django==4.1.5 gunicorn==20.1.0 psycopg2-binary==2.9.5 pycodestyle==2.10.0 sqlparse==0.4.3 whitenoise==6.3.0 No sure what el to do. I try to deploy a Django app with render.com -
Updating a django form involving 2 seperate functions (template function & form specific function)
I am trying to a update a form from a separate function. By clicking on button "Add" the existing form is updated by adding a user to the form. Adding the user to the form works fine. However I am loosing the text input from the initial form when submitting my update. The reason why I am using 2 functions is because I have multiple forms on the same template: each form is redirected to a specific url defined in action="{% url %}" The usual way I use to update a form is as follows: def function(request, id) instance = get_object_or_404(Model, pk=id) data = Model(request.POST or None, instance = instance) This is not working in this case because I need to provide the instance_id on the parent function, but the id parameter is provided on the function that supports the form. (child function) I suppose there is 2 options/questions: Can I access the form_id from the parent function? Should I deal with this in the form function? and in this case how do I keep the existing text when updating form? model class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) class Model(models.Model): user = models.ManyToManyField(User, blank=True) text = models.TextField('text', blank=True) template … -
Failed to change read-only flag pycharm in ubuntu
When I try to write something in file it show error "Failed to change read-only flag from pycharm in ubuntu" -
Google one tap Login With Django ( The given origin is not allowed for the given client ID issue )
I'm trying to connect Google One Tap Login with Django framework, but I'm having issue. I'm not sure why this is displaying an issue. I followed all of the guidelines described in the Google documentation. issue - The given origin is not allowed for the given client ID Here is my Google API client configuration for the javascript origin url. Here is the login html template code. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Hi Reddit</h1> <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="i don't want to shere" data-context="signin" data-ux_mode="popup" data-login_uri="http://localhost:8000/google/login/" data-auto_select="true" data-itp_support="true"> </div> <div class="g_id_signin" data-type="standard" data-shape="pill" data-theme="outline" data-text="continue_with" data-size="large" data-logo_alignment="left"> </div> </body> </html> </body> </html> I'm not sure why this is displaying an issue. Is it possible to load Google One Tap Javascript in Django? What should I do to load Google One Tap Javascript in Django? -
Django if statement is not working inside a html tag
(https://i.stack.imgur.com/tGf0u.jpg) I am trying to execute if statement in html file inside Js block in which I am writing JavaScript code. When I am trying to insert if statement is showing Expression Expected but if statement is written outside tag it is working. I tried to write it outside tag it is working but inside tag it is not working. -
Object update by PATCH for Django REST Framework
I am using viewsets.ModelViewSet from rest_framework import viewsets class ProjectViewSet(viewsets.ModelViewSet): serializer_class = s.ProjectSerializer queryset = m.Project.objects.all() def patch(self,request,*args,**kwargs): instance = self.get_object() serializer = self.get_serializer(instance,data = request.data) if serializer.is_valid(): self.perform_update(serializer) return Response(serializer.data) return Response() Then I test to update the object via django restframework UI. Then this error occurs. My basic idea that changing object data via PATCH is correct? How can I update the data via Django REST Framework Expected view ProjectViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. -
Selenium in Django on Linux - Ubuntu
I have problem with python selenium in Django when my project run on apache2 - Ubuntu Desktop. My app send forms to selenium script which reset user password. If im running server like this python3 manage.py runserver everything is fine and works good. When app works on apache i got error like this: Exception Type: TimeoutException Exception Value: Message: Failed to read marionette port Im sending forms - "name" and "ID" from function 'submitmyfrom' to 'reset_user_pw'. view.py: def submitmyfrom(request): form = FormsReset(request.POST) my_name = request.POST['name'] my_id = request.POST['id'] ip = request.META.get('REMOTE_ADDR') if len(id) < 12: passwd = reset_user_pw(user_name=my_name) mydictionary = { "my_name" : my_name, "my_id" : my_id, 'password' : passwd } return render(request,'submitmyfrom.html', context=mydictionary) reset_user_pw: def reset_user_pw(user_name): os.environ['MOZ_HEADLESS'] = '1' pwd = mypwd LoginName = "login" user_login = user_name cert = webdriver.FirefoxProfile() cert.accept_untrusted_certs = True web = webdriver.Firefox(executable_path='/var/www/my_project/src/geckodriver', log_path='/var/www/my_project/src/Reset/geckodriver.log', service_log_path='/var/www/my_project/src/myapp/geckodriver.log') web.get('https://example.com/test') time.sleep(1) next is the rest of the function reset_user_pw I use firefox and would ideally like to stay with it What can i do to make it on apache2. I remind you that the python3 manage.py runserver run fine -
I can't pass values to database with Ajax and Django
i'm new in Ajax and Django i'm try sent videoP1 = 1 when percentage = 100 i'm use script tag on html to write js To get videoP1-videoP17 from database via views.py to set value in array and call it. var videos = [ { id: 1, name: "1", src: "../static/frontend/video/1.mp4", videoP1: {{ video_db.videoP1 }}, }, { id: 2, name: "2", src: "../static/frontend/video/2.mp4", videoP2: {{ video_db.videoP2 }}, }, { id: 17, name: "17", src: "../static/frontend/video/17.mp4", videoP17: {{ video_db.videoP17 }}, }, ]; var player = videojs("videoP"); function light(Cvideo) { for (let i = 0; i < videos.length; i++) { let video = videos[i]; if (videos[i].id === Cvideo) { document.getElementById("nameV").innerHTML = videos[i].name; player.src({ type: "video/mp4", src: videos[i].src }); player.play(); if (!video["videoP" + (i + 1)]) { player.controlBar.progressControl.hide(); player.on("timeupdate", function() { var percentage = (player.currentTime() / player.duration()) * 100; document.getElementById("percentage").innerHTML = Math.round(percentage) + "%"; if (percentage === 100) { video["videoP" + (i + 1)] = 1; var videopro = video["videoP" + (i + 1)] = 1; $.ajax({ type: "POST", url: "/update-video-progress/", data: { video_id: video.id, videoPro: videopro, }, success: function(response) { console.log("Video progress updated"); }, error: function(xhr, textStatus, errorThrown) { console.error("Failed to update video progress"); }, }); return; } }); } else { … -
Django Views which one should I follow? [closed]
I'm new to Django framework I'm confused about the difference in which one I should follow use. Many developers use "django.views import View" and some are using "django.views.generic import ListView ..." which one is optimized in both of them? I know their output are the same but which one should I follow? from django.views import View .... class HomePage(View): def get(self, request): posts = Post.object.all().order_by('created') context = {'posts':posts} return render(request, 'html/homepage.html', context) or this one class HomePage(ListView): model = Post template_name = 'html/homepage.html' context_object_name = 'posts' ordering = ['created'] paginate_by = 3 -
How to get specific objects based on ManyToMany field match
I'm doing a cookbook app, which help users find meal thay can do with their ingridients. I'm using Django RestFramework, and i need to return list of avaliable meals that user can do, but don't know how to do search by ingridients My models.py: #models.py class Meal(models.Model): name = models.CharField(max_length=250) description = models.TextField(blank=True, null=True) recipe = models.TextField() is_published = models.BooleanField(default=False) category = ForeignKey('Category', on_delete=models.CASCADE, null=True) user = ForeignKey(User, verbose_name='User', on_delete= models.CASCADE) difficulty = ForeignKey('Difficulty', on_delete=models.PROTECT, null=True) ingridients = models.ManyToManyField('Ingridient') class Ingridient(models.Model): name = models.CharField(max_length=100, db_index=True) ico = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, null=True) category = ForeignKey('CategoryIngridients', on_delete=models.CASCADE, null=True) def __str__(self): return self.name class CookBookUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ingridients = models.ManyToManyField('Ingridient') serializer.py class MealSerializer(serializers.ModelSerializer): class Meta: model = Meal fields = "__all__" views.py class CraftWithUsersIngridientsListAPIView(generics.ListAPIView): serializer_class = MealSerializer def get_queryset(self): return Meal.objects.filter(ingridients=CookBookUser.objects.filter(user_id = self.request.user.id).ingridients) CraftWithUsersIngridientsListAPIView isn't working and I get AttributeError 'QuerySet' object has no attribute 'ingridients', can someone help fix this? I tried building different serializer but it doesn't help -
Annotate over multiple Foreign keys of the same type in one model
I have the following models. I absolutely have to use multiple foreign keys instead of a many-to-many field. class Job(models.IntegerChoices): ADMIN = (0, "Admin") ARCHITECT = (1, "Architect") ENGINEER = (2, "Engineer") class Employee(models.Model): job = models.IntegerField(_("Job"), choices=Job.choices) salary = models.DecimalField(_("Salary"), max_digits=12, decimal_places=4) class Company(models.Model): name = models.CharField(...) employee_one = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) employee_two = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) employee_three = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) ... employee_ten = models.ForeignKey(Employee, on_delete=models.SET_NULL, null=True) I want to get the total salary for each job, as in the following format: {'name': 'MyCompany', 'admin_total': 5000, 'architect_total': 3000, 'engineer_total': 2000}. I do this by iterating through each of the ten employees, checking their role and adding them together if they have the same role: Company.objects.all().annotate( admin_one=Case( When(employee_one__job=Job.ADMIN, then=F("employee_one__salary")), default=0, output_field=models.DecimalField(max_digits=12, decimal_places=4), ), admin_two=Case( When(employee_two__job=Job.ADMIN, then=F("employee_two__salary")), default=0, output_field=models.DecimalField(max_digits=12, decimal_places=4), ), ..., admin_total=F("admin_one") + F("admin_two") + ... + F("admin_ten"), ) As you can see this is just a very long query and it is only including the one of the three total salaries. And if another job is added, the annotation will just get longer. Is there a more efficient way to do this? -
ValueError at /approve/2/ Field 'id' expected a number but got ''
I am workin on a projec using modelformset to render multiple instance of a model and whenever i try to update my data, i get the error below. Template error: In template /home/dubsy/virtualenvs/djangoproject/libmain/templates/books/approve.html, error at line 67 Field 'id' expected a number but got ''. 57 : <thead> 58 : <tr> 59 : <th>Book Title</th> 60 : <th>Approved</th> 61 : <th>Not Approved</th> 62 : </tr> 63 : </thead> 64 : <tbody> 65 : {% for form in formset %} 66 : <tr> 67 : <td> {{ form.instance.book.title }} </td> 68 : <td>{{ form.approved }}</td> 69 : <td>{{ form.not_approved }}</td> 70 : </tr> 71 : {% endfor %} 72 : </tbody> 73 : </table> 74 : <button type="submit">Update</button> 75 : </form> 76 : 77 : </body> Exception Type: ValueError at /approve/2/ Exception Value: Field 'id' expected a number but got ''. I have tried using the users context in views.py to render out the form which works fo book title but doesn't work for the two input field as it renders out the value from database instead of a checkbox input field Here is my views.py def approve(request,pk): users = PendingRequest.objects.filter(member__id=pk) RequestFormset = modelformset_factory(PendingRequest, fields=("approved", "not_approved"),extra=0) if request.method == "POST": formset … -
django_plotly_dash: error exporting to pdf with html2pdf.js
I am trying to export a django_plotly_dash dashboard to pdf and can't quite get it. I am stuck with the following error in console when clicking on the button to trigger the export: ReferenceError: html2pdf is not defined at Object.nClicksToPDF [as n_clicks] which is telling me that html2pdf cannot be found. I have tried importing in assets folder as well as cdn directly in the app layout but nothing seems to do the trick and I am out of things to try: here is how I import it in the app: html.Script(src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"), here is my callback where it is called: app.clientside_callback( """ function nClicksToPDF(n_clicks){ if(n_clicks > 0){ document.querySelector('.chkremove').style.display = 'none'; const opt = { margin: 2, filename: 'myfile.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 1}, jsPDF: { unit: 'cm', format: 'a2', orientation: 'p' }, pagebreak: { mode: ['avoid-all'] } }; console.log('ok') html2pdf().from(document.getElementById("print")).set(opt).save(); setTimeout(function(){ document.querySelector('.chkremove').style.display = 'block'; }, 2000); } } """, Output('js','n_clicks'), Input('js','n_clicks') ) Don't know what else to do, any help would be highly welcome! -
Django - overload post on UpdateView so it auto completes some fields
So I have this view: class ProfileView(generic.UpdateView): model = User fields = [....] template_name_suffix = '_update_form' success_url = reverse_lazy('home') def post(self, request, *args, **kwargs): self.object = self.get_object() self.object.is_active = False return super().post(request, *args, **kwargs) when the user saves his data on update, I want some fields to be completed automatically, such as is_active = False. I used the approach above but my inserted fields aren't changed. Why and how can I get the desired result? Thanks.