Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Removing celery tasks by name (with wildcard?)
Is there a way I can remove a specific set of tasks from Celery? Maybe using a wildcard? Something like: app.control.delete("foobar-only-*") I know I can delete all tasks with from proj.celery import app app.control.purge() which comes from here, but that's not very helpful as it doesn't seem that I can use that code to tweak it and do what I want. -
Advice for running concurrent pysftp commands
Does anyone have any advice for running concurrent pysftp api commands, such as listing files in a directory and downloading them from a server. It seems that when I test this all requests are blocked until the previous is finished. I'm using pysftp with Django and I'm not sure how to implement this in a way that will scale a bit so I can have multiple users on the page making requests without them being blocked until another users request has been served. Thanks for reading! I tried something like this: class sftp: def __init__(self): self.response = HttpResponse() self.cnopts = pysftp.CnOpts() self.cnopts.hostkeys = None def dl(self): with pysftp.Connection('host.exmaple.com', username='user1', password='test_password', cnopts=self.cnopts) as sftp: sftp.getfo( '/var/lib/stuff/file.mp3', self.response) self.response['Content-Type'] = 'audio/mp3' return self.response Then in my view I would call something like this: return sftp().download() -
Using gte, lte, and range with Django REST Framework
Has anyone successfully used DRF to make API calls using gte, lte, and range? If so, what extension did you use? I've tried django-filters and django-rest-framework-filters but neither work as stated. If someone can share their code that would be much appreciated. Thanks. -
How to fix 'Argument data to tableXXX is required' in django-tables2?
I'm setting up a webstore manager and I'm relying on django-tables2 package to show a list of products using the SimpleTableMixin. I want to add the filter/search capability to the view. As recommended by the django-tables2 package one can rely on django-filter package to provide filtering. However, it the case of a model with many fields it becomes almost impossible to query and develop forms for those efficiently. My goal is to use django-haystack to have a single input search form as a mean to query the model instances which should be displayed in a similar table/form. I've tried to add the SimpleTableMixin to the django-haystack package generic SearchView. However I keep on getting the following error: TypeError at /manager/front/products/ Argument data to ProductTable is required So far my implementation goes as follow: view: # ############## Products ############## (previous implementation with django-filter) # @method_decorator(staff_member_required, name='dispatch') # class ProductList(SingleTableMixin, FilterView): # model = Product # table_class = tables.ProductTable # filterset_class = filters.ProductFilter # template_name = 'manager/front/products/product_list.html' ############## Products ############## @method_decorator(staff_member_required, name='dispatch') class ProductList(SingleTableMixin, SearchView): model = Product table_class = tables.ProductTable template_name = 'manager/front/products/product_list.html' search_indexes.py: from haystack import indexes from front.models import Product class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): … -
django.core.exceptions.FieldError: Unknown field(s) (username) specified for Employee
I am trying to extend the user model so I created a new model called employee with foreignkey to user model from django.db import models from django.contrib.auth.models import User class Employee(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) department = models.CharField(max_length=200) and tried to create a form for the signup from django.contrib.auth.forms import UserCreationForm from employee.models import Employee class EmployeeForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = Employee fields = UserCreationForm.Meta.fields + ('department',) These are the only changes I made I am getting the following error: File "/home/sugumar/python/django/project1/project1/urls.py", line 18, in from employee.views import signup File "/home/sugumar/python/django/project1/employee/views.py", line 2, in from .forms import EmployeeForm File "/home/sugumar/python/django/project1/employee/forms.py", line 4, in class EmployeeForm(UserCreationForm): File "/home/sugumar/.local/share/virtualenvs/project1-j0yhUYNK/lib/python3.5/site-packages/django/forms/models.py", line 266, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (username) specified for Employee -
Django REST Framework lookup_field to ReadOnlyField with source
I have a class: from django.contrib.contenttypes.models import ContentType import basehash class Hasher(object): base62 = basehash.base62() @classmethod def from_model(cls, obj, klass=None): if obj.pk is None: return None return cls.make_hash(obj.pk, klass if klass is not None else obj) @classmethod def make_hash(cls, object_pk, klass): content_type = ContentType.objects.get_for_model( klass, for_concrete_model=False ) return cls.base62.hash( "%(contenttype_pk)03d%(object_pk)06d" % {"contenttype_pk": content_type.pk, "object_pk": object_pk} ) @classmethod def parse_hash(cls, obj_hash): unhashed = "%09d" % cls.base62.unhash(obj_hash) contenttype_pk = int(unhashed[:-6]) object_pk = int(unhashed[-6:]) return contenttype_pk, object_pk @classmethod def to_object_pk(cls, obj_hash): return cls.parse_hash(obj_hash)[1] And models: class HashableModel(Model): """Provide a hash property for models.""" class Meta: abstract = True @property def hash(self): return Hasher.from_model(self) class Contest(HashableModel, Base): # type: ignore event = ForeignKey("events.Event", on_delete=CASCADE, related_name="contests") owner = ForeignKey( settings.AUTH_USER_MODEL, on_delete=CASCADE, related_name="contests" ) members = ManyToManyField(settings.AUTH_USER_MODEL, blank=True) And serializer returns hash instead of id class ContestSerializer(serializers.ModelSerializer): """Serialize a `contests.Contest` instance.""" id = serializers.ReadOnlyField(source="hash") event = EventSerializer() owner = UserSerializer() members = UserSerializer(many=True) class Meta: model = Contest lookup_field = "id" exclude = ("is_removed",) class ContestViewSet( mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): """ A simple ViewSet for creating and viewing contests. """ queryset = Contest.objects.all() serializer_class = ContestSerializer lookup_field = "id" But, if I want to get an object by hash, not an id, I don’t get … -
Create a form to activate user permission
The goal is to get a form that is an instance of a User and to propose a form in the form of radio to activate or deactivate a permission. A html code of this kind is expected at the end: <div class="form-group"> <label for="change_user">Can edit user:</label> <div class="labeled" id="change_user"> <input class="with-gap" name="change_user_False" type="radio" id="change_user_False" value="False"> <label for="change_user_False">No</label> <input class="with-gap" name="change_user_True" type="radio" id="change_user_True" value="True" checked=""> <label for="change_user_True">Yes</label> </div> </div> The example permission here will be "change_user" and the goal is to handle all the process in a clean form. I do not know what is the most appropriate way... Use on a simple form and manage everything in the clean function by passing in parameter a User object. from django import forms class PermissionForm(forms.Form): change_user = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'No'), (False, 'Yes')), required=True) def __init__(self, *args, **kwargs): self.fields['change_user'].initial = select_user.has_permission('auth.change_user ') def clean(self, select_user): if self.cleaned_data['change_user']: select_user.permissions.add('change_user') Or use a form of the User instance: from django.contrib.auth.models import User from django import forms class ProfileForm(forms.ModelForm): class Meta: model = User fields = [] widget = ... But how to generate a widget in radioselect on a permission and catch errors when returned data wrong??? -
Geodjango - display OSM widget in modelform
I've been trying to display a map widget for a modelform template to create model objects, it shows the field but the map is blank geom_linea is a MultiLineStringField spatial field here's the code: model.py class Pavim_ima(models.Model): fecha_solicitud = models.DateField(default=timezone.now) unidad_vecinal = models.ForeignKey(D_uvs, on_delete=models.CASCADE, blank=True, null=True) sede_vecinal = models.ForeignKey(D_juntas, on_delete=models.CASCADE, blank=True, null=True) sector = models.CharField(max_length=50) calle = models.CharField(max_length=50) obras = models.CharField(max_length=150) observaciones = models.TextField(max_length=500, null=True, blank=True) estado_diseno = models.CharField(max_length=10) fecha_inicio_ejecucion = models.DateField(null=True) estado_ejecucion = models.CharField(max_length=10) geom_linea = models.MultiLineStringField(srid=32719, blank=True, null=True) forms.py from django.contrib.gis import forms class Pav_ima_form(forms.ModelForm): class Meta(): model = Pavim_ima fields = '__all__' widgets = { 'observaciones': Textarea(attrs={'cols': 80, 'rows': 5}), 'geom_linea': forms.OSMWidget(attrs={'map_width': 800, 'map_height': 500}), } def limpiar(self): cd = self.cleaned_data admin.py from django.contrib import admin from .models import Pavim_ima, Pavim_Proy_Particip, Pavim_Conservacion from leaflet.admin import LeafletGeoAdmin class Pav_ima_Admin(LeafletGeoAdmin): pass admin.site.register(Pavim_ima, Pav_ima_Admin) in the template I call {{ form|bootstrap }} to display the fields thanks!! -
Django - How to get current logged in user to populate in django admin?
I’ve created a form to when the current logged in user makes a submission I have everything I want populated in the admin, except the current logged in user’s username. The Custom User Model I’m using is located in from users.models import CustomUser if that helps. How do I get the current logged in user’s username to populate in admin.py in the user column? Any help i gladly appreciated, Cheers Screenshot of Admin: user_profile/models from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from users.models import CustomUser class Listing (models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from django.conf import settings from django.views.generic.edit import FormView from django.views.generic.edit import UpdateView from django.views.generic import TemplateView from .forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from .models import Listing from users.models import CustomUser from django.urls import … -
How can I exit a subprocess that calls a django server?
I am running an otree erperiment on a django server on localhost:8000 and I want to run a subprocess that starts another django server on 8080. The browser tab will not open if in first order the subprocess is called. How can I fix this? How can I quit the new server (and the browser tab) and go back to my first one? This is for an oTree experiment. During this experiment, I need to open another django project, specially I want to run a django-oscar shop. class MyPage2(Page): def before_next_page(self): os.environ['DJANGO_SETTINGS_MODULE'] = 'shop.settings' subprocess.call(['py', 'shop2/manage.py', 'runserver', '0.0.0.0:8080'], shell=True) webbrowser.open('http://localhost:8080', new=2) -
Celery apply_async task
I have a case where I need a task to run every 45 minutes. But, not a single task periodically. The case is this: Some backend code executes, when successful -> calls a task apply_async(*args, eta=45 minutes from now once this task has finished processing it calls the same fnction again apply_async(*args, eta=45 minutes from now) So, the task looks like this: @app.task(....) def my_task(*args): .... # Finished... my_task.apply_async(*args, eta=datetime.utcnow() + timedelta(minutes=45)) Is there anything wrong with doing this? Just adding the task to execute again another 45 minutes later... But, it's unclear to me if doing this will cause the original task to stall in it's completion and cause things to build up. -
AttributeError: module 'django_filters.widgets' has no attribute 'DateRangeWidget'
I am trying to install Saleor onto Windows. I have been following instructions as per https://saleor.readthedocs.io/en/latest/gettingstarted/installation-windows.html. I have installed all necessary packages using python -m pip install -r requirements.txt. But for some reason, all the packages did not install. I have been running python manage.py migrate, over and over and it does not install everything. I get loads of ModuleNotFound errors and have to manually install them myself by googling their package names for pip. Now, I am after running into a different issue. I get the error AttributeError: module 'django_filters.widgets' has no attribute 'DateRangeWidget'. I do not know what to try and install. -
WordPress Static Pages and Django Project
I have a live Django project with static pages for the homepage page and other pages. It is hosted on AWS Now I have new static pages built in WordPress and I want to be able to use my current domain hosted by AWS to point to use the WordPress static pages I have. Is this possible? -
How to add a property to an object that is in a ManyToMany field?
I would like to send to a template a new property in a model that is in a ManyToManyField I have this loop in one of my models with ManyToManyField: for bar in foo.bars.all(): #This property 'allow_something' doesn't exist in model, I just need it in this situation bar.allow_something = True In the same code, if I try this everything goes as expected: #It will print "True" print(bar.allow_something) But when I call the new property in the template, it doesn't work. This is the code in my HTML template: {% for bar in foo.bars.all %} {{ bar.allow_something }} <-- nothing happens here. It should display "True" {% endfor %} Please, can you tell me what am I doing wrong? -
CORS with Axios to send HttpRequestt instead of XMLHttpRequest
I am trying to send a POST request from a React app using Axios to a Django local server, but I get a CORS error: Access to XMLHttpRequest at 'localhost:3000/es/api-auth/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https I can see that Axios is sending a XMLHttpRequest and I believe it must send a HttpRequest for it to be accepted. I tried to send the request adding the prefix http:// to the url in Axios as advised here, but I get a 404 error: POST http://localhost:3000/es/api-auth/login/ 404 (Not Found) This is the code for my React app Axios POST call: handleClick() { const axios = require('axios'); axios.post('localhost:3000/es/api-auth/login/', { // This gets a CORS Error axios.post('http://localhost:3000/es/api-auth/login/', { // This gets a 404 error next: '/', username: 'admin@funtastic.tours', password: 'funtadmin' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) } This is my CORS configuration in settings.py: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', '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', ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ['localhost:3000'] CSRF_TRUSTED_ORIGINS = ['localhost:3000'] -
Should I use Django for this kind of project? In which host?
I'm on my first job now as a web developer(it's a really good oportunitty to get a nice job and stop been poor) , but I have some huge questions. Short and faster, I'm going to rebuild the entire site of a laboratory, in the begining it's going to be just a blog site, with nice designe, carrousel of pics, and pretty much that. But in the future, probably a few months from now, they going to want a login for employees and an online store of their products. In the Last time, I work a lot with Django and I love it, but are a lot of thing that I have to learn. So, should I at the begining start to develop on Django, or it would be better that I develop on HTML5 without a framework, and in the future that project implement on Django? In the case that I develop at the begining on Django wich host would be better and easy to use? (I try pythonanywhere and it's really nice) **in the begining I don't going to have the requeriments or the model of the data base, that they going to want in the future **take … -
request.method == 'POST' vs. request.is_ajax(). Mutually exclusive?
As the title says, I'm interested to know if request.method == 'POST' and request.is_ajax() are mutually exclusive. Thanks -
blank=False,null=False (but object created with string of length 0)(without django forms)
class MyMod(models.Model): title = models.CharField(max_length=100,null=False,blank=False,validators=[empty]) MyMod.objects.create() generates MyMod object with empty title how can i stop it from doing I cant use forms, I tried validators option What else I can do -
hot to fix (Argument 'api_key' passed by position and keyword in constructor call)
django AT = Airtable(os.environ.get('AIRTABLE_MOVIESTABLE_BASE_ID'), 'Movies', api_key=os.environ.get('AIRTABLE_API_KEY')) -
Getting exception from djangorestframework
I am getting the following exception from djangorestframework's JSONEncoder class: Traceback: File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 156. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 154. response = response.render() File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/rest_framework/response.py" in rendered_content 72. ret = renderer.render(self.data, accepted_media_type, context) File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/rest_framework/renderers.py" in render 106. allow_nan=not self.strict, separators=separators File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/rest_framework/utils/json.py" in dumps 28. return json.dumps(*args, **kwargs) File "/usr/lib/python3.6/json/__init__.py" in dumps 238. **kw).encode(obj) File "/usr/lib/python3.6/json/encoder.py" in encode 199. chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.6/json/encoder.py" in iterencode 257. return _iterencode(o, 0) File "/home/ubuntu/Envs/env_md/lib/python3.6/site-packages/rest_framework/utils/encoders.py" in default 56. elif (coreapi is not None) and isinstance(obj, (coreapi.Document, coreapi.Error)): Exception Type: AttributeError at /v0/ui/website/subject-assignment/ Exception Value: module &#39;coreapi&#39; has no attribute &#39;Document&#39; So, basically, it is saying my application (coreapi) does not have Document attribute. All the other apis are working fine but it is giving this error in one particular api. I can't find anything different with that api as well. Is there anything wrong with the djangorestframework or any idea what should I do to debug? Note: I am using django 2.1.4, djangorestframework==3.9.0 and python version is 3.6.5. -
Django admin site, reverse the model association
Right now I have the following models. class Publisher(models.Model): name = models.CharField() class Article(models.Model): name = models.CharField() publisher = models.ManyToManyField(Publisher, related_name='articles', blank=True) When I go to Django admin site -> add/edit Article page, I get the select list of the Article to link. But when I go to Add/Edit Publisher page I don't see a select list to associate Article How to show Article list in Publisher add/edit page. How to hide Publisher list in Article add/edit page. -
Post form using AJAX in Django
I'm trying to POST form in Django using Ajax. I've already done this way before but now i cant find whats wrong with my code. When submitting the form, ajax POST's to wrong URL even though i've provided the right URL. I want to post to "/upload/videoUpload/" but it keeps on posting to "/upload".Below is the code. HTML: <form id="videouploadForm" method="POST" > {% csrf_token %} <input type="text" id="vidlc" name="video" value="submit" style="display: none" > <input type="submit" id="sBm120" style="display: none"/> </form> AJAX: <script> $('#sBm120').trigger('click'); $(document).ready(function() { $("#videouploadForm").submit(function(event){ event.preventDefault(); $.ajax({ method:"POST", url:"/upload/videoUpload/", data: { 'video': $('#vidlc').val(), 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, success: function(data){ if (data.status){ alert(data.status); var result = " <video poster='{% static 'images/single-video.png' %}' style='height:30vh' controls='controls' width='100%' height='30%'><source src='http://gateway.ipfs.io/ipfs/"+data.filehash+"' type='video/mp4; codecs='avc1.42E01E, mp4a.40.2'></video>"; document.getElementById("upv").innerHTML=result; } } }); return false; //<---- move it here }); }); </script> URLS.py: path('upload/videoUpload/', uploadVid, name="uploadVideo"), -
django gunicorn error inside aws ec2 instance
gunicorn errors: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Thu 2019-01-03 16:22:43 UTC; 29s ago Main PID: 10426 (code=exited, status=3) Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: return util.import_app(self.app_uri) Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: File "/home/ubuntu/monetimes/env/lib/python3.5/site-packages/gunicorn/util.py", line 350, in impor Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: __import__(module) Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: ImportError: No module named 'monetimes' Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: [2019-01-03 16:22:43 +0000] [10433] [INFO] Worker exiting (pid: 10433) Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: [2019-01-03 16:22:43 +0000] [10426] [INFO] Shutting down: Master Jan 03 16:22:43 ip-172-31-27-161 gunicorn[10426]: [2019-01-03 16:22:43 +0000] [10426] [INFO] Reason: Worker failed to boot. Jan 03 16:22:43 ip-172-31-27-161 systemd[1]: gunicorn.service: Main process exited, code=exited, status=3/NOTIMPLEMENTED Jan 03 16:22:43 ip-172-31-27-161 systemd[1]: gunicorn.service: Unit entered failed state. Jan 03 16:22:43 ip-172-31-27-161 systemd[1]: gunicorn.service: Failed with result 'exit-code'. gunicorn file [Unit] Description=gunicorn daemon After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/monetimes ExecStart=/home/ubuntu/monetimes/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/monetimes/monetimes.sock monetimes.wsgi:app$ [Install] WantedBy=multi-user.target my-django structure is: monetimes: env src: monetimes: __init__.py urls.py wsgi.py landing static_files templates media db.sqlite3 requirements.txt manage.py django aws gunicorn error inside ec2 instance. i have gunicorn inside my virtualenv . i have shared all the files and codes. please have a look … -
Channel tests with selenium in Django raise error message
I'm following this tutorial to experiment Channels with Django. I'm working on Windows 10 HOME, Django 2.1.4 and Python 3.7.1 The goal of this tutorial is to build a chat app. After downloading chromeDriver and adding it in the PATH, I run this command in my prompt : py manage.py test chat.tests Which returns this error message : EETraceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) EOFError: Ran out of input Traceback (most recent call last): File "<string>", line 1, in <module> File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\spawn.py", line 115, in _main self = reduction.pickle.load(from_parent) EOFError: Ran out of input ====================================================================== ERROR: test_when_chat_message_posted_then_not_seen_by_anyone_in_different_room (chat.tests.ChatTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\kevin\Envs\myproject\lib\site-packages\django\test\testcases.py", line 202, in __call__ self._pre_setup() File "C:\Users\kevin\Envs\myproject\lib\site-packages\channels\testing\live.py", line 52, in _pre_setup self._server_process.start() File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\process.py", line 112, in start self._popen = self._Popen(self) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__ reduction.dump(process_obj, to_child) File "c:\users\kevin\appdata\local\programs\python\python37-32\Lib\multiprocessing\reduction.py", line 61, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'DaphneProcess.__init__.<locals>.<lambda>' ====================================================================== ERROR: test_when_chat_message_posted_then_seen_by_everyone_in_same_room … -
Reducing number of ORM queries in Django web application
I'm trying to improve the performance of one of my Django applications to make them run just a bit smoother, as part of a first iteration in improving what I currently have running. When doing some profiling I've noticed that I have a very high number of SQL queries being executed on a couple of pages. The dashboard page for instance easily has 250+ SQL queries being executed. Further investigation pointed me to the following piece of code in my views.py: for project in projects: for historicaldata in project.historical_data_for_n_months_ago(i): for key in ('hours', 'expenses'): history_data[key] = history_data[key] + getattr(historicaldata, key) Relevant function in models.py file: def historical_data_for_n_months_ago(self, n=1): n_year, n_month = n_months_ago(n) try: return self.historicaldata_set.filter(year=n_year, month=n_month) except HistoricalData.DoesNotExist: return [] As you can see, this will cause a lot of queries being executed for each project in the list. Originally this was set-up this way to keep functionality centrally at the model level and introduce convenience functions across the application. What would be possible ways on how to reduce the number of queries being executed when loading this page? I was thinking on either removing the convince function and just working with select_related() in the view, but, it would still …