Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can't distribute django project by elasticbeanstalk
I wanna distribute django-project to use ElasticBeanStalk. But there's problem when I do 'eb create' code. Honestly, I saw hundreds of documents for this problem. Someone says it is 'pillow' package problem, pip problem, etc. But I think pythonpath problem. Here's my errorcode and ElasticBeanStalk application log. 2019-08-14 04:56:44 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2019-08-14 04:56:48 ERROR [Instance: i-0e32d61b630bb7337] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. Here's EB logs /var/log/eb-activity.log Collecting future==0.16.0 (from -r /opt/python/ondeck/app/requirements.txt (line 13)) Downloading https://files.pythonhosted.org/packages/00/2b/8d082ddfed935f3608cc61140df6dcbf0edea1bc3ab52fb6c29ae3e81e85/future-0.16.0.tar.gz (824kB) Collecting idna==2.7 (from -r /opt/python/ondeck/app/requirements.txt (line 14)) Could not find a version that satisfies the requirement pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 22)) (from versions: ) No matching distribution found for pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 22)) You are using pip version 9.0.1, however version 19.2.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2019-08-14 04:56:44,147 ERROR Error installing dependencies: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1 Traceback (most recent call last): File … -
How to display serializers validation error message in vue template?
Here i am using vue.js for the client side rendering and django-rest framework for the server side.I am customizing the PasswordResetSerializer class in order to check whether the entered email is registered in our database or not.If the email is not in our db then it does not send the success message which is good but also it does not display the validation error messgae but i have configured the error message in the PasswordResetSerializer class if there is not user with that email address. Note:It is displaying the success message Password reset email has been sent if the email address is in our database. How can i display the serializers.ValidationError message in my login form ? serializers.py from django.contrib.auth.forms import PasswordResetForm from django.conf import settings class PasswordResetSerializer(serializers.Serializer): email = serializers.EmailField() password_reset_form_class = PasswordResetForm def validate_email(self, value): self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError('Error') if not User.objects.filter(email=value).exists(): raise serializers.ValidationError('Sorry.No user found with that email address.') return value def save(self): request = self.context.get('request') opts = { 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, } self.reset_form.save(**opts) loginform.vue <template> <div class="login-card"> <div class="container"> <form @submit.prevent="login(credentials.username, credentials.password)"> <div class="input-container"> <img class="icon-user" src="@/assets/icons/user.png" alt=""> <input class="username" type="text" placeholder="Username" v-model="credentials.username" name="username" required> </div> <div class="input-container"> <img class="icon-password" … -
Django admin Inline is not displayed, without any error
I have a Shelter model which is the parent of Suite model and for Suite model I created an admin inline to define some constrains on it. class Shelter(models.Model): title = models.CharField(max_length=255, verbose_name=_('Title')) city = models.ForeignKey(City, on_delete=models.CASCADE, verbose_name=_('City')) address = models.CharField(max_length=255, verbose_name=_('Address')) class Suite(Shelter): room = models.IntegerField(verbose_name=_('Room')) class SuiteConstrain(models.Model): suite = models.ForeignKey(Suite, on_delete=models.CASCADE, verbose_name=_('Suite')) start_date = jmodels.jDateField(verbose_name=_('Start Date')) end_date = jmodels.jDateField(verbose_name=_('End Date')) req_limit = models.IntegerField(verbose_name=_('Request Count Limit')) req_max_attendants = models.IntegerField(verbose_name=_('Max Attendants')) req_max_nights = models.IntegerField(verbose_name=_('Max Nights')) And in my admin.py: class ShelterAdmin(ModelAdminJalaliMixin, admin.ModelAdmin): form = ShelterForm inlines = [ShelterPictureInline, ] list_display = ('title', ) class SuiteConstrainInline(admin.TabularInline): model = SuiteConstrain extra = 1 @admin.register(Suite) class SuiteAdmin(ShelterAdmin): inlines = [SuiteConstrainInline, ShelterPictureInline] pass with a great surprise I have now just ShelterPictureInline visible in my admin panel. ConstrainInline Doesn't show without any error! -
how do i count and make a table from the data
i have two tables that is the occurrance table and waterbody table,i want to view how many species occur in a particular waterbody i have already listed down the water bodies but now picking and counting the number of species in each water body is the problem this is my def occurrance water_body = WaterBody.objects.get(name=water_body), this is my models.py water_body = models.ForeignKey(WaterBody, blank=True, null=True, on_delete=models.SET_NULL) this is my water_analytics.html <tbody> <tr> <td>Lake Victoria</td> <td>{{w.id.name.count }}</td> </tr> <tr> <td>Kazinga Channel</td> <td>{{occurance.count}}</td> </tr> i expect to output the number of number of species in a particular waterbody please help me as quickly as you can -
API Django post url return 403 forbidden error
I am using rest-framework-api for my project and I am trying to create a User using an endpoint with a POST method. However, the response is always 403 Forbidden -> (CSRF token missing or incorrect.): I have tried all the methods on stackoverflow : csrf_exempt decorators, authentication_classes = [], CsrfExemptMixin And none of these methods works ... I always get the same answer "403 Forbiddden" PS : I am sending request with POSTMAN API : permission_classes = (AllowAny,) authentication_classes = [] # Serializer class to validate input and serialize output # Can be overridden by get_serializer_class() queryset = User.objects.all() serializer_class = UserSerializer` Url: api.register(r'auth/sign-up', views.UserEP, basename='userEP') My aim is just to implement an endPoint that allows any user to create an account. -
Django factory-boy - maximum recursion depth
I have a User, Profile and Shop model. The former two are from the common recipes page on the official documentation: @factory.django.mute_signals(post_save) class UserFactory(factory.DjangoModelFactory): class Meta: model = User profile = factory.RelatedFactory(ProfileFactory, 'user') @factory.django.mute_signals(post_save) class ProfileFactory(factory.DjangoModelFactory): class Meta: model = models.Profile # We pass in profile=None to prevent UserFactory from creating another profile # (this disables the RelatedFactory) user = factory.SubFactory('accounts.factories.UserFactory', profile=None) shop = factory.RelatedFactory('shops.factories.ShopFactory') class ShopFactory(factory.DjangoModelFactory): class Meta: model = models.Shop owner = factory.SubFactory(UserFactory) url = factory.Faker('url') The error comes from declaring a shop on the profile. How should I change the code for it to work properly with the ShopFactory? Thanks! -
Postgres DateTimeField incorrect time
I have in my module DateTimeField: class Pairs(models.Model): id = models.AutoField(primary_key=True) timestamp = models.DateTimeField(null=True) and I insert data from python like this: timestamp = datetime.fromtimestamp(pair['timestamp']) tz_aware_datetetime = timestamp.replace(tzinfo=pytz.timezone('Asia/Jerusalem')) pair_recored =Pairs(session=session_obj,timestamp=tz_aware_datetetime) pair_recored.save() the timestamp from my code is: 2019-08-15 08:50:07.795000+02:21 but in my DB this field has different value: 2019-08-15 09:29:07.795+03 why there is this difference between these values? -
How to get sublime text 3 editor to auto-complete the "{% " with " %}" to save time?
I have started developing django apps with Sublime Text 3, and find the "{% %}" brackets in jinja logic to be very tedious to type, so i wonder is there a way to auto-complete the "{% " bracket with " %}" to save some time? -
Why Django application can't connect to remote MySQL database in Docker container?
I have Django application which works with remote MySQL database. I run application with the help of docker container. Unfortunatly in logs of the application I notice error. When I am using my application without Docker it works. Why can't an application running in Docker connect to the database? ERROR Internal Server Error: /main/login/ Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/beewifi/main/views/auth.py", line 47, in wifi_login zone = Zone.objects.get(identity=params['identity']) File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 374, in get num = len(clone) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 232, in __len__ self._fetch_all() File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 1105, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 863, in execute_sql sql, params = self.as_sql() File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 420, in as_sql where, w_params = self.compile(self.where) if self.where is not None else ("", []) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 373, in compile sql, params = node.as_sql(self, self.connection) File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/where.py", line 79, in as_sql sql, params = compiler.compile(child) … -
path function for URL throwing error when we want to capture an integer or slug paramter
I am a beginner in django 2.2.4. I was trying to the following the urls.py file. from firstapp import views from django.contrib import admin from django.urls import re_path, path urlpatterns = [ re_path(r'^admin/$', admin.site.urls), re_path(r'^$', views.index), path('articles/2003/', views.index), path('articles/<int:year>/', views.index), ] I see that the url http://127.0.0.1:8000/articles/2003/ executes the views.index. However, when I run the url http://127.0.0.1:8000/articles/2005/ ,there is an error. Request URL: http://127.0.0.1:8000/articles/2005/ Django Version: 2.2.4 Exception Type: TypeError Exception Value: index() got an unexpected keyword argument 'year'enter code here Why is this not working? As above.It was expected this ur would be matched by the linee path('articles//', views.index). -
How to insert items into Django models from views.py file?
I'm trying to insert an item into my database record from the views.py file. How can I do this? -
Calling attrs in FormHelper
I want to call Datepicker in my crispy-forms. I am using FormHelper but i just can't find a way to call attrs of datepicker. These are important for me as i have to define the format in it. class DeviceFilterFormHelper(FormHelper): # updated_date is the field in which i want to call the attrs form_id = "Device-search-form" form_method = "GET" form_tag = True html5_required = True layout = Layout( Div( Div('name', css_class="col-md-6"), Div('location', css_class="col-md-6"), css_class='row' ), Div( Div('phone_number', css_class="col-md-6"), Div(Field('updated_date', css_class="date-time-picker1", attrs={ 'required': True, 'theme': 'dark', 'class': 'date-time-picker', 'data-options': '{"format":"Y-m-d H:i", "timepicker":"true"}' })), css_class='row' ), FormActions( Submit("submit", ("Search"), css_class="col-md-5"), css_class="col-8 text-right align-self-center", ), ) -
NO SUCH TABLE DJANGO ERROR EVEN AFTER MAKING MIGRATIONS
I am getting Operational Error accessing http://127.0.0.1:8000/orders/create/ The error I get: OperationalError at /orders/create/ no such table: orders_order I have already tried making migrations. But the issue won't go away My models.py look like this: from django.db import models from ecom.models import Product # Create your models here. class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return 'Order {}'.format(self.id) def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) #item info class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items',on_delete=models.PROTECT) product = models.ForeignKey(Product,related_name='order_items',on_delete=models.PROTECT) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return '{}'.format(self.id) def get_cost(self): return self.price * self.quantity and my views.py looks like this: from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart # Create your views here. def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() return render(request, 'order/created.html', {'order': order}) else: form = OrderCreateForm() return render(request, 'order/create.html', {'cart': cart, 'form': form}) The line which Django … -
Feed customization and email notification based on it
There is a blog. It have a three model classes, who is subcategory of each other. And fourth model is post. They have a structure like that: ├───Category1 │ ├───Subcategory11 │ │ ├───subsubcategory111 │ │ ├───subsubcategory112 │ │ └───subsubcategory113 │ ├───Subcategory12 │ │ ├───subsubcategory121 │ │ ├───subsubcategory122 │ │ └───subsubcategory123 │ └───Subcategory13 │ ├───subsubcategory131 │ │ ├───post1311 │ │ ├───post1312 │ │ └───post1313 │ ├───subsubcategory132 │ │ ├───post1321 │ │ ├───post1322 │ │ └───post1323 │ └───subsubcategory133 │ ├───post1331 │ ├───post1332 │ └───post1333 It is necessary to implement the mechanism of email alerts about creation/update/deletion of the categories \ subcategories \ posts as follows: - the user can subscribe to a category (add to favorites) - then he will receive notifications about all movements of the category itself and its child objects (subcategories, posts - when adding \ editing \ deleting thereof) - the user can subscribe to a subcategory (add to favorites) - then he will receive notifications about all movements in this subcategory and its child objects (posts - when adding \ Editing \ removing add) - the user can subscribe to the post (add) - then it will receive notification of all movements (editing \ delete \ commentary) … -
How can Django mysql continuous deployment be implemented on windows server
I have a Django app currently running on local dbsqilte3. I used to deploy earlier using git, where git would sync sqilte3 databases both on the server and on my local machine. And I used to simply push/pull changes. Now I would like to migrate it to MySQL. How can I implement sync and at the same time experiment on the MySql database independent of server instance? I am running a windows server. I have a guess in this method's implementation. Won't I first install MySQL on the server and local machines independently and then somehow using some third party software I would be able to sync my databases or at least push updates and still not lose data that's already on the server? Any help with articles, migrations, agile methodology is much appreciated. As this is my first project with continuous deployment. -
Django admin template customization
I have a django admin site with multiple apps and also multiple admin sites inside and I need to add a logo for all pages. I've made it work by adding a index_template a and extending the base_site.html with my logo. Admin Site class xxxxAdminSite(admin.AdminSite): site_header = "xxx" site_title = "xxx" index_title = "xxx" index_template = "index.html" Base Site.html {% extends "admin/base.html" %} {% load static from staticfiles %} {% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %} {% block branding %} <h1 id="site-name"> <img src="{% static 'xxx.png' %}" height="40px" /> </h1> {% endblock %} {% block nav-global %}{% endblock %} The problem is I'm currently changing the pages for all scenario's of the admin site eg. change_form_template, change_list_template, etc. But I need to add change_form_template and change_list template for all my admin.ModelAdmin's ModelAdmin class xxxxAdmin(admin.ModelAdmin): change_form_template = 'change_form.html' change_list_template = 'change_list.html' delete_confirmation_template = 'delete_confirmation.html' object_history_template = 'object_history.html' Any cleaner way to do it? Something like all model admins to point to a single eg. change_form?. -
OperationalError, no such column: hospi_treatmentgiven.patient_id
I am having three Models, and each model is connected to another with ForeignKey, and migrations are also running successfully but when I am trying to add TreatmentGiven manually from admin, I am getting Operation error class Patient(models.Model): firstname = models.CharField(max_length=200) lastname = models.CharField(max_length=200) phone = models.CharField(max_length=20) alternate_phone = models.CharField(max_length=20) address = models.TextField() patient_id = models.AutoField(primary_key=True) gender= models.CharField(max_length=6, choices=Gender) class Ipd(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,blank=True) reason_admission = models.CharField(max_length=200, blank=True) provisional_diagnosis = models.CharField(max_length=200,) ipd_id = models.AutoField(primary_key=True) weight = models.CharField(max_length=10,blank = True) bill_responsible = models.CharField(max_length=100,blank = True) bill_relation = models.CharField(max_length=100,blank = True) rooms = models.ForeignKey(Rooms,on_delete=models.CASCADE, blank=True) date_of_admission = models.DateField(("Date"), default=datetime.date.today) condition_admission = models.CharField(max_length=20, choices=Admission_condition) consultant = models.CharField(max_length=20, choices=Consultant) def __str__(self): return self.patient.firstname class TreatmentGiven(models.Model): patient = models.ForeignKey(Ipd,on_delete = models.CASCADE,default = None) medicine_name = models.CharField(max_length = 100,null = True) types_of_doses = models.CharField(max_length = 100,null = True) route = models.CharField(max_length = 100,null = True) number_of_days = models.IntegerField(null = True) -
Celery task not starting at the start time provided
I have a Django app that utilizes celery in order to handle user scheduled tasks. I'm currently having a problem where I set start time for the PerodicTask and it does not start at that specific time, rather sometime later instead. Environment: Celery 4.3 Django 2.2 Python 3.7 task = PeriodicTask(name="foo",task="bar_task", start_time=DateTime5MinutesAhead, interval=EveryHourInterval) task.save() I expect the task run first in 5 minutes from when the task was created and then every hour after that. Instead, it seems to run at some arbitrary point later, completely ignoring the start_time argument. Am I mistaken on what the start_time argument is for? I've tried with IntervalSchedule as well as CrontabSchedule and neither seem to start at the exact start time. Bonus: What's actually really weird in my findings is that if I use IntervalSchedule set to every minute it actually DOES, in fact, start on correctly and run correctly, but if I set it to anything else it no longer works. -
Can't properly install Django-requests module
I followed the steps in this doc: https://django-request.readthedocs.io/en/latest/index.html Except step 4, which I'm not sure what it means: "Make sure that the domain name in django.contrib.sites admin is correct. This is used to calculate unique visitors and top referrers." However, I get this error, when I try to load my app: django.db.utils.OperationalError: no such table: request_request -
'str' object has no attribute 'items' using Django Rest Framework
I have a working Django project and when I deploy it to my server I get this error: AttributeError at /api/myData/ Django Version: 2.2.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'items' Exception Location: /pathToProject/lib/python3.7/site-packages/rest_framework/fields.py in to_representation, line 1729 On my local machine I am using Python3.6 but on the server I have 3.7. Requirements are the same. Any idea why this happens? settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', ‘myapp’, ‘myapp2’, ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_EXPOSE_HEADERS = ( 'Access-Control-Allow-Origin: *', 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE', 'Access-Control-Allow-Headers: Authorization', ) CORS_ORIGIN_WHITELIST = ( 'http://127.0.0.1:3000', 'http://127.0.0.1:8000', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',) } ROOT_URLCONF = ‘MyProject.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 = 'MyProject.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ‘somedatabasename’, 'USER': 'postgres', 'PASSWORD': ’somepassword’, 'HOST': 'localhost', 'PORT': '5432', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] STATIC_URL = '/static/' -
Is there a way to apply a filter to a URL generated with the URL tag in Django?
For part of my user interface I need a URLencoded URL. This code doesn't work, but it's intended to give an impression of what I'd like to do: {% url 'team_event_calendar' id=team.id | urlencode %} Basically, get a particular URL - in this case "team_event_calendar" for a particular team, and then URLencode it. I suppose I could make a new version of the URL tag which URLencodes everything, but is there a way to do it with just Django's built-in tags? -
Big django queryset in Python's if conditional expression
I have a queryset that was used in below code. result = 1 if queryset else 0 In case of small queryset it's okay but when queryset gets bigger (more than 500 000 results) program freezes, it takes some time to stop it. What is happening behind the scenes when Django's queryset is tested in the code above? Is some extra work performed during that check? Even though the queryset is big, there is no problem with calling count() or iterator() or any other methods, it is that conditional expression where the problem appears. -
Decide which model to retrieve data on Django Rest Framework
I'm trying to build a simple API which should do the following: A user makes a request on /getContent endpoint, with the geographical coordinates for this user. By content, it means audio files. Every time they send a request, we should just get a random object from a Model and return the URL field from it, to be consumed by the front end. For this, it can be a random one, it doesn't matter much which one. Also, we should keep tracking about the requests each user makes. This way, we can check how many requests the user has made, and when they were made. Every 5 requests or so, the idea is to send the user a customized content based on their location. My idea is to store this content in another model, since it would have many more fields in comparison from the standard content. Basically, at every request, I'd check if it's time to send a special content. If not, just send the random one. Otherwise, I'd check if the time is appropriate, and the user is within a valid location based on the special content's data in the model. If this validation passes, we send the … -
Django: Is there a way to make client render Python 3 functions locally?
I have a project that I want a client to run a for/while loop on his/her machine. Is there a way to do such a thing since views are run on server-side, such as below: views.py from django.shortcuts import render def index(request): for i in range(0,10000): # Do stuff return render(request, 'app/index.html') Javascript was one of the option for client side but I have some libraries that are from Python 3 I want to run. -
Django values_list extremely slow on large dataset
Getting a values_list in django is extremely slow on a large dataset (6M+ items). I have a Django application with a DB structure like: class Taxon(models.Model): name = models.TextField() class Specimen(models.Model): taxon = models.ForeignKey("Taxon", related_name='specimens') class Imaging(models.Model): taxon = models.ForeignKey("Specimen") image = models.ImageField(("Imaging")) And need to get a list of all (images, taxon) belonging to a Taxon, if there are more than "100" images of that taxon. This worked fine in development with a small database: image_list = list(Imaging.objects .annotate(items_per_taxon=Count('specimen__taxon__specimens__images')) .filter(items_per_taxon__gte=100) .values_list('image', 'specimen__taxon')) But takes 30 minutes on a full dataset (6M Taxon rows, and 2M image rows). Is there a way of indexing the 'foreign key of a foreign key' or creating a virtual column in postgres that can make this faster?