Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
capture pre-registered addresses correctly in Django
I would like to capture addresses pre-created by the client there is one default address and several one address or several addresses but currently I am catching it from the notes thanks to the post method but I cannot link it to the key foreign default address or other address thank you for your help def get_address(self): return "%s, %s, %s, %s, %s, %s, %s" %(self.address, self.address2, self.city,self.state,self.country,self.zipcode,self.phone) views.py: def orders(request,order_id): try: the_id=request.session['cart_id'] cart=Cart.objects.get(id=the_id) except: the_id=None return HttpResponseRedirect(reverse("carts:cart")) try: new_order=Order.objects.get(cart=cart) except: new_order=None return HttpResponseRedirect(reverse("carts:cart")) notes={} try: address=request.POST.get('address') notes['address']=address except: address=None if new_order is not None: new_order.sub_total=cart.total new_order.status="Finished" new_order.notes=notes new_order.save() final_amount=new_order.get_final_amount messages.success(request, "your order has been completed") if new_order.status=="Finished": new_order.save() del request.session['cart_id'] del request.session['items_total'] else: pass context={} template="orders/user.html" return render(request,template,context) -
only getting SMTPServerDisconnected: please run connect() first when call through api
I recently enabled email sending feature to Django with Sendgrid smtp as the backend here are my email settings: #AUTO SEND EMAIL EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'apikey' EMAIL_HOST_PASSWORD = 'the_sendgrid_key' EMAIL_PORT = 587 In one of my api got the following codes: student = request.user subject = 'test', text_content = 'test' email = EmailMultiAlternatives(subject, text_content, os.environ.get('DEFAULT_FROM_EMAIL'), to=[student.email]) email.attach_alternative(html_content, "text/html") email.send() During local development whenever i call the api the email got sent and i received it normally But when i called the api on the server it keep returning the following error: SMTPServerDisconnected: please run connect() first (Most recent call last) File /root/study/api/views/views.py line 1470 in post args locals email.send() File /usr/lib/python3.8/smtplib.py line 753 in starttls args locals self.ehlo_or_helo_if_needed() File /usr/lib/python3.8/smtplib.py line 604 in ehlo_or_helo_if_needed args locals if not (200 <= self.ehlo()[0] <= 299): File /usr/lib/python3.8/smtplib.py line 444 in ehlo args locals self.putcmd(self.ehlo_msg, name or self.local_hostname) File /usr/lib/python3.8/smtplib.py line 371 in putcmd args locals self.send(str) File /usr/lib/python3.8/smtplib.py line 363 in send args locals raise SMTPServerDisconnected('please run connect() first') SMTPServerDisconnected: please run connect() first After looking up this error there only answers about incorrect email settings but i checked and the email settings is … -
Is it possible to disable permissions in django cms?
I want to add my own custom permission inside the django cms pages instead of CMS model permissions. How can I do that ? For example: {% if request.user.is_manager %} {% cms_toolbar %} {% endif %} -
How to use LIKE statements with parametrized Django raw queries
Let's say I have this query (truncated) using the MariaDB connector for Django: ... WHERE st_notation LIKE concat('%', ?, '%') ... I'm trying to find the equivalent of concat('%', ?, '%') for Django MySQL raw queries but I couldn't. Could not find anything in the Django docs. Does anyone know how to do it? -
How to add custom fields to Historical Records and assign values to them using signals in django-simple-history
I wanted to add Custom fields to HistoricalRecords with abstract model.I want to display history records with additional field "replaced_with".Each file history should tell by which file it was replaced. models.py: class AdditionalFileHistory(models.Model): replaced_with = models.CharField( max_length=100, null=True, blank=True, verbose_name=_('replaced by') ) class Meta: abstract = True class ReviewFile(models.Model): review = models.OneToOneField( Review, verbose_name=_('review'), on_delete=models.CASCADE, related_name='files' ) file = models.FileField( upload_to='documents/%Y/%m/%d', null=True, blank=True, verbose_name=_('file') ) filename = models.CharField( max_length=100, null=True, blank=True, verbose_name=_('filename') ) history = HistoricalRecords(bases=[AdditionalFileHistory, ], cascade_delete_history=True) class Meta: verbose_name_plural = 'Files' def __str__(self): return f'Review Step {self.file.name}' signals.py: @receiver(pre_create_historical_record) def pre_create_historical_record_callback(sender, **kwargs): history_instance = kwargs['history_instance'] print(history_instance.replaced_by) source_instance = kwargs['instance'] history_instance.replaced_with = source_instance.replaced_with it was giving current file history,previous file is replaced by current file in history -
Add unique users to ProjectMember model in Django
I'm new to Django. Can anyone out there for the rescue. In my current proect, I've couple of models inside a Django app: Project, ProjectMember. Here's their model and admin structure. models.py class Project(models.Model): name = models.CharField(max_length=100) start_date = models.DateField() end_date = models.DateField() description = models.TextField(max_length=1000) class ProjectMember(models.Model): project = models.ForeignKey(Project, on_delete=models.SET_NULL, null=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) admin.py from .models import Project, ProjectMember class ProjectMemberInline(admin.TabularInline): model = ProjectMember extra = 0 class ProjectAdmin(admin.ModelAdmin): list_display = ('name', 'start_date', 'end_date') inlines = [ProjectMemberInline] admin.site.register(Project, ProjectAdmin) What I want to achieve is, every Project(i.e. model) should have unique users(ProjectMember) and every user can be associated with multiple projects. But with the current structure, system allows duplicate ProjectMember insertion in the admin. Please see the screenshot, I've add here 2 same users. Any help is appreciated. -
How to set up formsets in class based view in django
I am adding formsets for my clientcreateview and clientupdateview. I've been watching tutorials but it's mostly dependent to def based. I would likt to know how to implement it for class based views. I am stuck in this problem. Please help me. Thank you very much in advance. here's my models.py: class Client(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) position = models.CharField(max_length=30, default=None) organization = models.ForeignKey(UserProfile, null=True, blank=True, on_delete=models.CASCADE) agent = models.ForeignKey("Agent", related_name="clients", null=True, blank=True, on_delete=models.SET_NULL) category = models.ForeignKey("Category", related_name="clients", null=True, blank=True, default=6, on_delete=models.SET_NULL) company_name = models.CharField(max_length=50 , default=None) street_address = models.CharField(max_length=50 , default=None) baranggay = models.CharField(max_length=50 , default=None) city = models.CharField(max_length=50 , default=None) region = models.CharField(max_length=50 , default=None) date_added = models.DateTimeField(auto_now_add=True) phoned = models.BooleanField(default=False) special_files = models.FileField(blank=True , null=True) def __str__(self): return self.company_name class Branches(models.Model): client = models.ForeignKey("Client", related_name="+", blank=True, null=True, on_delete=models.SET_NULL) branches_quantity = models.IntegerField(default=1, blank=True, null=True) baranggay = models.CharField(max_length=50) city = models.CharField(max_length=50) region = models.CharField(max_length=50) def __str__(self): return self.client class Meta: db_table = "branches" class ContactPerson(models.Model): client = models.ForeignKey("Client", related_name="+", blank=True, null=True, on_delete=models.SET_NULL) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=20) position = models.CharField(max_length=30) mobile_number = models.CharField(max_length=12) email = models.EmailField(null=True, blank=True) def __str__(self): return self.client class Meta: db_table = "contact_person" class ClientUpdateView(OrganizerAndLoginRequiredMixin, generic.UpdateView): … -
How to handle encrypted requests and answers with distant server using a certain protocol with react native and javascript
I'm working on a mobile application project using react native, the mobile app should use a distant server to get information for example : to login i must send an encrypted request to a distant server with certain protocol for example : 03000F10081B367ACF10500019601010200 0300- Command OF10 - Data length 081B367A -Time etc .... the answer also will be like that and i have also to encrypt and decrypt all So my question is how can i handle that ? is there any techniques or librairies to easily do it ? and should i use an api in my app ? can i program the encrypt and decrypt functions in javascript and integrate them to post and get http requests ? after the login i must display certain information that i need to send request to the server to obtain them the same way as the login (encrypted message, protocl,etc ...) all functionalities should be like already mentioned (connection status, battery level ....) -
Django range filter based on created, updated and deleted signals
I want to make API for timelines for that I have created model, serializer, and views. Here is my model, serializers, and views file from that how I can make a filter based on the date range class Timeline(models.Model): activity = models.CharField(max_length=150) types = models.CharField(max_length=25) date_time = models.DateTimeField(auto_now_add=True) class TimelineViewSet(ReadOnlyModelViewSet): queryset = Timeline.objects.all() serializer_class = TimelineSerializer filterset_fields = {'types': ['exact']} Please, anybody, have an idea on this help me with this problem -
How to properly close MariaDB and MySQL connections when using both connectors within a project
I am currently working on a project in which there are approximately 100 functions that are responsible for making raw queries to the DB. Depending on whether the code is on the local server or on the staging server, one connector or the other (MySQL or MariaDB) will be used. To do this, I have implemented the get_cursor() function that returns the cursor for each case. The point is that, as far as I know, this is not a good practice since I have to close the connections after the queries are made. def get_cursor(): #MariaDB cursor for Django if 'local' == settings.DJANGO_HOST: conn = mariadb.connect( user="user", password="password", host="localhost", database="db-dummy") return conn.cursor(named_tuple=True) else: #Default Django MySQL cursor return connection.cursor() #MariaDB connector def get_some_data_mariadb(record_id): results = [] cursor = get_cursor() try: cursor.execute("SELECT blabla some query") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results except mariadb.Error as e: print(f"Error: {e}") #MySQL connector def get_some_data_mysql(record_id): results = [] cursor = get_cursor() cursor.execute("SELECT blablabla") columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results The code for now works, but if I do a lot of … -
How do I set up server side events using django rest framework backend
I was able to set up Websockets in my django rest framework project using channels library. However I found that server sent events covers my use case because I only need to communicate data from the back-end to the UI. For UI to backend I can just use my HTTP apis. I need some detailed description about what code I need to write to set this up. Ever article I have read gives a very vague idea about how to set this up -
"nonFieldErrors": ["Invalid data. Expected a dictionary, but got InMemoryUploadedFile."]
How to upload image in foreign key models While creating an product an error occur "nonFieldErrors": "Invalid data. Expected a dictionary, but got InMemoryUploadedFile." if i pass parser_classes = (MultiPartParser,) in model Serializer it show init() missing 3 required positional arguments: 'META', 'input_data', and 'upload_handlers' Model class Product(Core): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='product') brand = models.ForeignKey(Brand, on_delete=models.RESTRICT, related_name='product') name = models.CharField( _('Product Name'), max_length=255, validators=[ MinLengthValidator(30), MaxLengthValidator(255), ], help_text=_('Title should be Minimum 30 Characters'), ) slug = models.SlugField(unique=True, blank=True) is_active = models.BooleanField(default=True) is_approved = models.BooleanField(default=False) def get_absolute_url(self): return reverse('products', args=[self.slug]) def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(Product, self).save(*args, **kwargs) def __str__(self): return self.name class ProductImage(Core): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='image') image = models.ImageField(upload_to=path_and_rename) Serializers class ProductImageSerializer(ModelSerializer): class Meta: model = ProductImage fields = ('image',) class ProductSerializer(ModelSerializer): image = ProductImageSerializer(many=True, required=True) class Meta: model = Product fields = '__all__' def create(self, validated_data): product = Product.objects.create(**validated_data) image_data = validated_data.pop('image') image = ProductImage.objects.create( product=product, image=image_data ) product.save() return product Views class ProductViewSet(ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'slug' -
Kubernetes Django Redis values randomly change
Hello I'm trying to make a Django website with an api route that when called will increment a redis value, I need to use kubernetes and host this project on GCP I've been following this tutoruial: https://medium.com/google-cloud/deploying-django-postgres-and-redis-containers-to-kubernetes-part-2-b287f7970a33 And have my code hosted here: https://github.com/MartinBarker/DockerDjangoRedis I followed everything (had to make some small changes since this tutorial is a little out of date) but I have my Django/Redis/Postgresql containers running, and the guestbook django project displays a number of how many times you have visited the page in guestbook\guestbook\views.py: from django.conf import settings from django.core import serializers from django.http import HttpResponse from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response from .models import Message from django.core.cache import cache import math import logging globalcounter=0 def __update_visited(): """ Updates the visited count by one in the cache :return: The visited count in string form. """ visited = cache.get('visited') if not visited: visited = 0 else: visited = int(visited) visited += 1 cache.set('visited', str(visited)) return str(visited) But in production when you visit the site http://35.247.25.226/ this number changes randomly, it doesn't seem to be stored consistently and I cant figure out why: #1 page visit: "This guestbook … -
Django middleware to route requests/responses to database schemas
I am currently using django middleware to process request/response to different postgresql schemas using URL. I want to use another database to store history data with same schemas: like - default_db{customer1 schema} to history_db {customer1 schema}. middleware.py from tenant.utils import set_tenant_schema_for_request class TenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): set_tenant_schema_for_request(request) response = self.get_response(request) return response utils.py file from django.db import connection from tenant.models import Tenant def hostname_from_request(request): # split on `:` to remove port return request.get_host().split(":")[0].lower() def tenant_schema_from_request(request): hostname = hostname_from_request(request) tenants_map = get_tenants_map() return tenants_map.get(hostname) def set_tenant_schema_for_request(request): schema = tenant_schema_from_request(request) print(schema) with connection.cursor() as cursor: cursor.execute(f"SET search_path to {schema}") def get_tenants_map(): connection.cursor().execute(f"SET search_path to public") sub_domains = Tenant.objects.order_by('id').values_list("sub_domain", flat=True) schema_names = Tenant.objects.order_by('id').values_list("schema_name", flat=True) tenants = dict(zip(sub_domains, schema_names)) return tenants # return {"customer1.example.com": "customer1", # "customer2.example.com": "customer2", # "example.com": "public"} router.py file from django.db import models class HistoryRouter: history_app = {'history'} def db_for_read(self, model, **hints): """ Attempts to read auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.history_app: return 'history_db' return None def db_for_write(self, model, **hints): """ Attempts to write auth and contenttypes models go to auth_db. """ if model._meta.app_label in self.history_app: return 'history_db' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations … -
running scripts is disabled on this system vscode, cannot activate virtual environment
I found solution for this question as well, first check which terminal your vs-code is using (power shell or command prompt) and proceed forward with that: Search for terminal (used in vs-code) in start menu open that as administrator (cmd or powershell) check for the execution status with this code, get-executionpolicy If result is restricted, then execute the following code, Set-ExecutionPolicy Unrestricted Then it will return you a paragraph, enter "Y" and click enter. Now it is solved. -
(MyPy) Missing type parameters for generic type "ModelAdmin"
When I run mypy, I get this error: emails/admin.py:43: error: Missing type parameters for generic type "ModelAdmin" And this is the corresponding code snippet: @admin.register(Message) class MessageAdmin(admin.ModelAdmin): list_display = ('subject', 'thread', 'user', 'email_account', 'from_name', 'from_email', 'local_timestamp') search_fields = ('subject','thread__synced_with_email', 'user__username', 'email_account__synced_email_current', 'from_name', 'from_email') ordering = ('subject', 'thread') This class is not exactly a function so I do not understand why the type-hint is checked by mypy. There is nothing that gets returned and no parameters are passed. -
How to lazily create expensive database entries in Django
Disclaimer: I'm new to Django. My site generates puzzles for people to play. A puzzle is generated algorithmically from a seed which is in the url. The generation can take a little time, so I want to store each puzzle after they're created. The seed field on my Puzzle model is unique to avoid duplicates in my database, currently I call this method on my Puzzle class: @staticmethod def from_seed(seed): try: return Puzzle.objects.get(seed=seed) except Puzzle.DoesNotExist: p = expensive_model_generation(seed) try: p.save() return p except IntegrityError as e: # This catches more than just a duplication error, but unsure right now how to # make a duplication check agnostic to the database/django version. return Puzzle.objects.get(seed=seed) There are two problems I see with this. If multiple users request a puzzle for the same seed at the same time, the server will kick off multiple expensive_model_generation calls even though only one of them will be used. The generation function might run for a few minutes so I probably should point the user to a waiting page and generate the puzzle asynchronously. I guess I could solve 1) by making a database table for like "in progress" seeds that I check before running generation code … -
How to check active accordion based on object id?
Here {% c_url request 'display' %} this will return either display class or None. if display class return I want to keep accordion collapse open. But this is opening all the collapse. I want to apply display class to the particular #collapseid only. How can I do it ? template {% for n in navs %} <li> <a data-toggle="collapse" class="sub{{n.id}} {% c_url request 'active' %}" href="#collapse{{n.id}}" aria-expanded="true" aria-controls="collapse" ><p> {{n.title}} </p></a > <div class="collapse{{n.id}} {% c_url request 'display' %}" id="collapse{{n.id}}"> <ul class="nav"> {% for i in n.nav_set.all %} .............. {% endfor %} </ul> </div> </li> {% endfor %} c_url template tag @register.simple_tag def c_url(request, value): if request.resolver_match.url_name in ['url1', 'url2']: return value -
request.POST has data but save method does not update the db in django
I am trying to perform below process in my Django application: Adding member to 'Member' table whenever a user registers. Creating tasks to populate 'Task' table. Allocating those tasks to member and hence populating Allocation table. I see the data submitted is passed through request.POST but my table is not updated with the same data. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Member(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) DESIGNATION = [ ('Developer', 'Developer'), ('Tester', 'Tester'), ('Support', 'Support'), ] name = models.CharField(max_length=200, null=True) role = models.CharField(max_length=100, null=True, choices=DESIGNATION) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name class Task(models.Model): CATEGORY = [ ( 'Low', 'Low'), ('Medium', 'Medium'), ('Urgent', 'Urgent'), ] STATUS = [ ('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Completed', 'Completed'), ] name = models.CharField(max_length=200, null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL) task_status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return self.name class Allocation(models.Model): member = models.ForeignKey('Member', null=True, on_delete=models.SET_NULL) task = models.OneToOneField('Task', null=True, primary_key=True, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.task.name views.py def allocate_task(request): try: unallocated_tasks = Task.objects.get(member__isnull=True) except Task.DoesNotExist: unallocated_tasks = None if unallocated_tasks … -
how to access python variable inside a vue.js input fields
Here I have written python code. So in this python code I have an variable "query_class" That i want to acces in below vue.js template inside the input fields. So how can we do that if anyone have an idea please let me know def PostAdUpdate(request, adv_id): if ((request.session.get('email') is None) or (request.session.get('email') == "")): return HttpResponseRedirect("/home") `query_class` = classifieds.objects.filter(email=request.session.get('email'), id=adv_id).first() query_tran = transaction_table.objects.filter(classifieds_id=adv_id).first() query_master = master_fields.objects.filter(classifieds_id=adv_id).first() return render(request, 'postAdUpdate.html', {'query_cart': query_class, 'query_tran': query_tran, 'query_master': query_master, }) template here inside of this input field I want to access the above python code variable that is "query_class" <div id="vue"> <input v-model.lazy="category" placeholder="Search your category" name="category" maxlength="200" id="id_post_type"> </div> <script> new Vue({ el: '#vue', data: { category:'', }, methods: {}, }); </script> -
Using Custom Field in ModelSerializer into to_representations
I create a Custom Field ( JDateField ) as follow: class JDateField(serializers.Field): def to_representation(self, value): return str(value) def to_internal_value(self, date): return datetime.strptime(date, '%Y-%m-%d') I have implemented two approaches to using it: 1. Approach ONE: class CustomerSerializer(serializers.ModelSerializer): birthday = JDateField() class Meta: model = Customer fields = ( 'birthday', ... ) 2. Approach TWO: class CustomerSerializer(serializers.ModelSerializer): def to_representation(self, instance): birthday = JDateField() return { 'birthday': birthday, ... } The first one works fine but in the second I get the following error: TypeError: Object of type JDateField is not JSON serializable Question: How can I use JDateField as a Custom Field in to_representation method? -
authentication method is not working after extending custom user model
here is an incomplete simple login and register methods which are not working and it is showing the user object is returning none, previously did the same without extending custom user then it worked but now it is not working after extending custom user. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager class MyUserManager(BaseUserManager): def create_user(self,email,user_name,is_seller,is_buyer,passkey,password=None): if not email: raise ValueError("email is required") if not user_name: raise ValueError("user_name is required") if is_seller is None: raise ValueError("is_seller is required") if is_buyer is None: raise ValueError("is_buyer is required") if not passkey: raise ValueError("passkey is required") user= self.model( email=self.normalize_email(email), user_name = user_name , is_buyer = is_buyer , is_seller = is_seller , passkey = passkey ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,user_name,is_seller,is_buyer,passkey,password=None): user=self.create_user( email = email, user_name = user_name, is_seller=is_seller, is_buyer=is_buyer, passkey = passkey, password=password ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(verbose_name="Email",unique=True) shop_name=models.CharField(verbose_name="shop_name" ,max_length=150) first_name = models.CharField(verbose_name="first_name",max_length=150) last_name = models.CharField(verbose_name="last_name",max_length=150) user_name = models.CharField(verbose_name="user_name",max_length=150) phone=models.CharField(max_length=20,verbose_name="user phone") is_seller=models.BooleanField(verbose_name="is_seller", default=False) is_buyer=models.BooleanField(verbose_name="is_buyer", default=False) passkey=models.CharField(verbose_name="passkey",max_length=30) date_joined=models.DateTimeField(verbose_name="date_joined",auto_now_add=True) last_login=models.DateTimeField(verbose_name="last_login",auto_now=True) is_admin=models.BooleanField(default=False) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS=['user_name','is_seller','is_buyer','passkey'] objects=MyUserManager() def has_perm(self, perm, obj=None): return True def has_module_perms(self,app_label): return True views.py from django.shortcuts import redirect, render from .models import MyUser from django.contrib.auth import authenticate, login from django.contrib … -
optimize multiple queries in django
I want to filter my model based on some features that maybe choose or not. In the views.py I have these codes: result = models.Catalogue.objects.filter(Q(type__in=intersections) & Q(type__isnull=False)).order_by('-datetime') if date_time: date_time = datetime.datetime.now() - datetime.timedelta(days=int(date_time)) result = result.filter(Q(datetime__gte=date_time)) if max_age == '' or max_age is None: pass else: if nulls: result = result.filter(Q(age__lte=max_age) | Q(age__isnull=True)) elif not nulls: result = result.filter(Q(age__lte=max_age) & Q(age__isnull=False)) if (city == ['None'] or city == ['']) and (district is None or district == ''): if not city_district: pass else: result = result.filter((reduce(operator.or_, (Q(city__contains=x) for x in city_district)) & Q(city__isnull=False)) | (reduce(operator.or_, (Q(district__contains=x) for x in city_district)) & Q(district__isnull=False))) There are some more queries and so, it takes a long time to retrieve result. db is MySQL and attributes are indexed. How can I change it for an optimal querysets? -
How to retrieve "Table A which matches Table B, where Table A = condition"
I'm having a problem on how to fetch my data from Django. In English, I would like to achieve this: Retrieve all Leg objects and the associated Positions, where each Position object has 1 or more Leg object whose attribute close_trx_id = None. class Position(models.Model): position_id=models.AutoField(primary_key=True) class Leg(models.Model): leg_id=models.AutoField(primary_key=True) close_trx_id=models.ForeignKey(Transaction, on_delete=models.CASCADE,blank=True,null=True,related_name="close_trx_id") position_id=models.ForeignKey(Position,on_delete=models.CASCADE) Ideally, the end result should be a dataset which shows each Leg's and associated Position's attributes joined in a single row. Thanks much for help! -
Uncaught ReferenceError: (function = named as handleTweetActionBtn) is not defined at HTMLButtonElement.onclick ((index):1) [duplicate]
I have been trying to solve this error for quite some time now. The error in the console bar looks like this Console error image I have been trying to develop my logic towards creating like and unlike button. My index.html with script code looks like this {% extends "network/layout.html" %} {% block body %} <div class="row text-center"> <div class="col"> <h2>Welcome to Network</h2> </div> </div> <div class="row mb-3"> <div class="col-md-4 mx-auto col-10"> <form class="form" id="tweet-create-form" method="POST" action="/tweet-create"> {% csrf_token %} <div class="d-none alert alert-danger" id="tweet-create-form-error"> </div> <input type="hidden" value="/" name="next"> <textarea class="form-control" name="content" placeholder="What's happening?"></textarea> <button type="submit" class="btn btn-primary col-12">TWEET</button> </form> </div> </div> <div class="row" id="tweets"> Replace me </div> <script> document.addEventListener('DOMContentLoaded', function() { const tweetCreateFormEl = document.getElementById("tweet-create-form") tweetCreateFormEl.addEventListener("submit", handleTweetCreateFormDidSubmit) const tweetsContainerElement = document.getElementById("tweets") //tweetsElement.innerHTML = "Loading..." // Forms in JS function handleTweetCreateFormDidSubmit(event){ event.preventDefault() const myForm = event.target const myFormData = new FormData(myForm) const url = myForm.getAttribute("action") const method = myForm.getAttribute("method") const xhr = new XMLHttpRequest() const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.onload = function() { if (xhr.status === 201){ handleTweetFormError("", false) const newTwt = xhr.response const newTweetElement = formatTweetElement(newTwt) const ogHtml = tweetsContainerElement.innerHTML tweetsContainerElement.innerHTML = newTweetElement + ogHtml myForm.reset() } else if (xhr.status …