Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django combine multiple ListView using get_query and search form
in my project, I have three models models.py class Category(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True, null=True, blank=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') class Tag(models.Model): tag = models.CharField(max_length=75, verbose_name='Tag') slug = models.SlugField(null=True) class Post(models.Model): title = models.CharField(max_length=150) slug = models.SlugField(max_length=150, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) tags = models.ManyToManyField(Tag, related_name='tags', blank=True) and I created search filter view in views.py def is_valid_queryparam(param): return param != '' and param is not None class SearchPepsiView(ListView): template_name = "blog/NewSearch.html" model = Post paginate_by = 10 def get_queryset(self): return Post.objects.filter(category__slug=self.kwargs['slug']) def get_context_data(self, *args, **kwargs): context = super(SearchPepsiView, self).get_context_data(*args, **kwargs) context['category'] = Post.objects.filter(category__slug=self.kwargs['category']) return context def get(self, request, *args, **kwargs): request = self.request qs = Post.objects.all() categories = Category.objects.filter(parent=None).order_by('name') PostOrAuthor_query = request.GET.get('PostOrAuthor') SearchCategory_query = request.GET.get('SearchCategory') if is_valid_queryparam(PostOrAuthor_query): qs = qs.filter(Q(title__icontains=PostOrAuthor_query) | Q(content__icontains=PostOrAuthor_query) | Q(author__username__icontains=PostOrAuthor_query)).distinct() if is_valid_queryparam(SearchCategory_query) and SearchCategory_query != 'Choose...': qs = qs.filter(category__name=SearchCategory_query) count = qs.count() or 0 return render(request, self.template_name, { 'queryset': qs, 'categories': categories, 'count': count, }) and I created Post Per Category View in views.py class PostPerCategoryCBV(ListView): model = Post template_name = 'blog/Category_Projects.html' def get_queryset(self): self.category = Category.objects.get(slug=self.kwargs['slug']) return Post.objects.filter(category=self.category) def get_context_data(self, **kwargs): context = super(PostPerCategoryCBV, self).get_context_data(**kwargs) context['category'] = self.category return context and I created Post Per Tag View … -
Add an additional form to a formset using POST without Javascript and validation
I want to use a Django formset, but with pure server rendering and without the need of Javascript to add additional forms to it. The user should just click a button on the page and the page should reload with an additional form in the formset. All user input should be preserved! The relevant part in the view is: if request.POST.get('add_form') == "true": cp = request.POST.copy() cp['form-TOTAL_FORMS'] = int(cp['form-TOTAL_FORMS']) + 1 fs = MyFormSet(cp) The problem is that when MyFormSet(cp) renders a form representation it adds validation errors to it (like "This field is required"). This is ugly and not acceptable. How can I render it without the errors (they should only be present when the whole form was submitted)? MyFormSet(initial=...) seems not to be an option as it must also work in a UpdateView (the docs are pretty clear that initial is only for extra forms) and also the POST data can't be directly used as initial values. I am super thankful for any hint as it took me several hours without getting anywhere (and it seems to be such a common feature as the rest of Django is so Javascript unaware). -
Cache control decorator has no effect on rendered page in Django
I am trying to add cache control to a page in a Django application: from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control from django.shortcuts import render @login_required @cache_control(no_cache=True, must_revalidate=True, no_store=True) def fooView(request): return render(request, 'foo.html') But no meta information is appearing in the head section of the page. Does this decorator not work in conjunction with render, or in development mode (DEBUG = False)? Also I couldn't find any documentation on the parameters for the cache control decorator. I'm wondering what are the defaults. -
How can I count my followers in django template?
This is my second time when i am asking this question again because i guess first time this question didn't reach to the people who can tell me the solution of this question. Well here i just want to count followers and following, but i don't know how can i count tell and show them in a profile detail template. I don't understand how can i find followers and following respectively with a single follower field which is mentioned in model.py. If anybody know answers than please answer. I shall be very thankful to you. models.py. class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' view.py(profile detail view) def get_context_data(self, *args, **kwargs): context = super(UserProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] '''#Trying with this but it is not working i guess this is wrong way to this but i am not sure!!''' allprofile = UserProfile.objects.all() followers = 0 for u in allprofile.follower: if u == user.userprofile: followers+=1 context['followers']=followers return context if more detail is require than tell me in a comment session. I will update my question with … -
What is the "|" character in Django called?
"|" is equivalent to Angular Pipes but what is it called in Django? Like in the official Django Polls App tutorial enter image description here vote{{ choice.votes|pluralize }} is to let Django automatically appends an "s" character after the string "vote" if there are more than 2 votes being rendered from the databse, otherwise don't but I don't know what is called in Django. On another hand, this equivalent technology in Angular is called Angular Pipes. -
How to pass a key field's value to filter dependent field's values in Django / jquery-autocomplete
In my Django app, I am using jQuery autocomplete for fields to complete a transaction. For an independent field, i.e. the entered value in the field not based on another field's value, the routine is successfully completed. There are situations, where the entered (field) value has a parent object, and I need to use a .filter (as explained in subsequent paragraphs) in order to get the correct value/s of the (dependent) field. This is akin to cities assigned to a specific country. In the transaction, the user has to first enter the parent field's value (e.g. "Country Id" in the following code example). And later select a value from one of the dependent values (e.g. the cities). My auocomplete routine is as follows: Template: $(function() { $( "#id_city_cd" ).autocomplete({ source: "{% url 'city_search' %}", select: function(e, ui) { $("#id_city_cd").val(ui.item.city_cd : '' ); $("#id_city_name").val(ui.item.label); return false; }, change: function(ev, ui) { $("#id_city_cd").val(ui.item? ui.item.city_cd : '' ); $("#id_city_name").val(ui.item.label); }, minLength: 1, delay: 0, autoFocus: true, }); }); My View is as under: def CitySearch(request): if request.is_ajax(): tmpCountryId = "some_value" // Here I want a value for Country Id (e.g. "DE") q = request.GET.get('term','') city_search = City.objects.filter(country_id=tmpCountryId).filter(city_name__icontains=q).annotate(value=F('city_name'), label=F('city_name')).values('city_id', 'value', 'label') // I have … -
Getting error in dependent ChoiceField form django?
I am trying to create a Dependent Dropdown in django(Country->State->City).My model structure is class Country(models.Model): name = models.CharField(max_length=100) class State(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=100) state = models.ForeignKey(State, on_delete=models.CASCADE) class Organization(models.Model): name = models.CharField(max_length=50) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) COUNTRIES = [(choice.pk, choice) for choice in Country.objects.all()] COUNTRIES.insert(0, ('', 'Select Country')) My forms.py class OrganizationForm(forms.ModelForm): name = forms.CharField(label='Company name', min_length=2, error_messages={ 'required': 'Company name should not be empty', 'min_length': 'Atleast 2 characters required', 'max_length': 'Should not exceed 50 characters'}) country = forms.ChoiceField(choices=COUNTRIES, error_messages={ 'required': 'Country should not be empty'}) state = forms.ChoiceField(error_messages={ 'required': 'State should not be empty'}) city = forms.ChoiceField(error_messages={ 'required': 'City should not be empty'}) class Meta: model = Organization fields = ['name','city'] templates/states.html <option value="">Select State</option> {% for state in states %} <option value="{{state.id}}">{{state.name}}</option> {% endfor %} My rendering part works fine.But when I submit the form it displays an error for state field as Select a valid choice. 70 is not one of the available choices. where 70 is id of a state. And one more doubt, is it ok to store only city as foreign key in my organization model or do I need to store country and … -
How to import dajngo models with their ForeignKeys ond new ids?
I need to import some data in django and I stopped on one problem. I have few models in JSON file and they are all connected via ForeignKey field. In my app I potentialy could have some models with the same ids as those in file, and I would like to keep both. Therefore, for each model in file, while saving it, I would need to generate new id, which as ar as I know is done automatically, if 'id' section in file is empty. My problem is: what with ForeignKeys? How to keep connection between models, and in the same time for each of them generate new id? -
How can I display a single post while they are giving me the error (No post found matching the query)
I am working with a django project to design a blog app. I am at the stage of displaying the posts, but I tried to display a single post (127.0.0.1:8000/post/1/), but I met error below: * Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Raised by: rymapp.views.PostDetailView No post found matching the query * ** See my views.py ** from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post def home(request): return render(request, 'rymapp/home.html', {'title': 'home'}) def about(request): return render(request, 'rymapp/about.html', {'title': 'about'}) def blog(request): context = { 'posts': Post.objects.all() } return render(request, 'rymapp/blog.html', context) class PostListView(ListView): model = Post template_name = 'rymapp/blog.html' #<app>/<model>_<viewtype>.html context_object_name = 'posts' ordering = ['-date_posted'] class PostDetailView(DetailView): model = Post Below is my urls.py from django.urls import path from .views import PostListView, PostDetailView from .import views urlpatterns = [ path('', views.home, name='rymapp-home'), path('about/', views.about, name='rymapp-about'), path('blog/', PostListView.as_view(), name='rymapp-blog'), path('post/<int:pk>/', PostDetailView.as_view(), name='rymapp-post_detail'), ] And here it is my post_detail.html {% extends "rymapp/base.html" %} {% block content %} <article class="media content-section mt-2"> <div class="media-body"> <lu class="list-group mr-5"> <li class="list-group-item list-group-item-light"> <div class="article-metadata"> <img class="rounded-circle article-img" width="50" height="50" src="{{ object.author.profile.image.url }}"> <a class="mr-2 ml-2" href="#"> {{ object.author }} </a> <small class="text-muted"> {{ object.date_posted … -
pass data from two models into one single html page - Djagno
i'm facing problem with show data from two models into single html page i have two models - first called Course and second called Lesson okay , so i want add course then add lesson in the course and show data in one html page models.py : class Course(models.Model): title = models.CharField(max_length=100,default="") name = models.CharField(max_length=100,default="") app_contect = RichTextField(blank=True,null=True) app_image = models.ImageField(upload_to='images/',null=True, blank=True) post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True) post_tag = models.CharField(max_length=50,default="",choices = COURSE_SECTION) objects = SearchManager() slug = models.SlugField(default="",blank=True,unique=True,editable=True) def save(self, *args, **kwargs): if not self.id or not self.slug: super(Course, self).save(*args, **kwargs) self.slug = slugify(f"{self.title} {str(self.id)}") super(Course, self).save(*args, **kwargs) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name class Meta: ordering = ('-post_date',) class Lesson(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) name = models.CharField(max_length=100) youtube_url = models.URLField() def __str__(self): return self.name admin.py : from django.contrib import admin from blog_app.models import Course,Lesson class InlineLessons(admin.StackedInline): model = Lesson class CourseAdmin(admin.ModelAdmin): inlines = [ InlineLessons ] admin.site.register(Lesson) admin.site.register(Course,CourseAdmin) so how to show data from course and lesson model into one html page ? i tried do this but it's don't work , it just show data from Course model views.py : def course_posts(request,slug): lesson = Lesson.objects.all() course_posts = get_object_or_404(Course, … -
WebSocket connection to 'wss:// failed: Error during WebSocket handshake: Unexpected response code: 404 on channels
I face this error while using channels for WebSockets on django production: WebSocket connection to 'wss://domain.me/ws/orders/confirm_all/' failed: Error during WebSocket handshake: Unexpected response code: 404 while there's no problem on localhost ( with runserver command ) routing.py: from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from management.consumers import ConfirmAllOrdersConsumer application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter([ url(r'ws/orders/confirm_all/$', ConfirmAllOrdersConsumer), ]) ), }) js: const ws_scheme = window.location.protocol === "https:" ? "wss" : "ws"; const ordersSocket = new WebSocket( ws_scheme + '://' + window.location.host + '/ws/orders/confirm_all/' ); consumers.py: import json from channels.generic.websocket import WebsocketConsumer from orders.models import Orders from time import sleep class ConfirmAllOrdersConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, code): self.disconnect(code) def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) action = text_data_json['action'] if action == 'confirm_all': revision_orders = Orders.objects.filter(status__exact='revision') for idx, order in enumerate(revision_orders): print(idx) order.status = 'confirmed' order.save() sleep(0.33) self.send(json.dumps({ 'total_orders': revision_orders.count(), 'new_val': idx + 1 })) it's working on localhost over http/ws, but not working over https/wss on production Any idea? Thank you. -
Django: Static files not being served during deployment
So basically I have a Django project stored in a folder called PROJECT - within that I have 2 folders munbase and MUNbase munbase contains my settings.py assgi.py wsgi.py and so on and so forth. the settings.py for the same looks something like this: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = () # SECURITYWARNING: keep the secret key used in production secret! SECRET_KEY = 'some secret key' # SECURITYWARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['0.0.0.0'] #ip adress redacted for obv reasons # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MUNbase' ] MIDDLEWARE = [ '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', ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ] ROOT_URLCONF = 'munbase.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 = 'munbase.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS … -
Steck overflow - How to search and learn about the specific topics in stack overflow
how to search and how to set the preferences for the topics to search and learn about in stack overflow. In this I have learning more. Is there any way to set the preferences for Python, Django, Angular, Javascript and Typescript -
Refused to execute script because its MIME type ('text/html') is not executable AJAX DJANGO
I have this Django app that's working fine. But I keep getting this error in console: Refused to execute script from 'http://localhost:8000/live/detect/static/JS/livedetect.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. I tried answers from stack, but I cant find out what is wrong!! Here's the script file function fetchData(){ csrfToken = $('#MainCard').data("token"); $.ajax({ url: document.URL, async: true, dataType: 'json', data:{ csrfmiddlewaretoken: csrfToken, }, type: 'post', success: function(responce){ $('#ExtractedText').text(responce["text"]); } }); } $(document).ready(function(){ setInterval(fetchData, 1000); }); -
Django serializer return OrderdDict instead of JSON
I am creating a Django Rest API using django-rest-framework. I am using a JSONField to store JSON data in mongo collection. Everything is working fine but when I am fetching the record, I am getting an OrderdDict instead of json. Here is my Model - from django.contrib.auth.models import AbstractBaseUser from django.db import models from djongo import models class Content(models.Model): id = models.BigAutoField(primary_key=True,auto_created = True, serialize = False) slides = models.JSONField(blank = True, default=[]) and the response I am getting - [ { "id": 2, "slides": "OrderedDict([('id', '1'), ('name', 'Creator 1')])" } ] but I expect a response like [ { "id": 2, "slides": [ { "id":1, "name":"Creator 1" } ] } ] View file - class ContentList(ListAPIView): serializer_class = ContentSerializer def get_queryset(self): limit = self.request.query_params.get('limit') if limit: pagination.PageNumberPagination.page_size = limit queryset = Content.objects.all().order_by('-id') return queryset I tried using encoder and decoder but getting error - slides = models.JSONField(blank = True, encoder= None, decoder=None, default=[]) TypeError: __init__() got an unexpected keyword argument 'encoder' The Django version is 3.0. How can I do this? I am new to python and started learning recently and stuck here for last 2 days. Tried a lot of solution but not working. -
why the form not save in django?
I have a formset and I am trying to save it back. But, when I try to check if employ_academic_forms.is_valid() and save, validation always fails even if nothing in the formset has been changed. I am displaying already existing data using formset and trying to edit it. I don't know where I am going wrong. Can someone please help? view: def employedit(request, pk, id): employ_academic = EmployAcademicInfo.objects.filter(employ_id=pk) employ_academic_forms = EmployAcademicUpdateFormSet(queryset=employ_academic) if request.method == 'POST': employ_academic_forms = EmployAcademicUpdateFormSet(request.POST, queryset=employ_academic) if employ_academic_forms.is_valid(): user_obj = User.objects.get(id=pk) name = employ_basic_forms.cleaned_data['name'] email = employ_basic_forms.cleaned_data['email'] user_obj.username=email user_obj.first_name=name user_obj.email=email user_obj.save() instances = employ_academic_forms.save(commit=False) print(instances) for instance in instances: instance.employ_id = user_obj instance.save() return redirect('employ-list') context = { 'employ_academic_forms':employ_academic_forms, } return render(request, 'admins/employ/edit_employ.html', context) form: EmployAcademicUpdateFormSet = modelformset_factory( EmployAcademicInfo, exclude = ['employ_id'], extra=0, labels = { 'degree': 'Enter Employ Degree', 'last_passing_institution_name': 'Enter Employ Passing Institution', 'last_passing_year': 'Enter Employ Passing Year', }, widgets = { 'degree' : forms.Select(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter degree'}), 'last_passing_institution_name' : forms.TextInput(attrs={'class':'form-control form-control-lg', 'placeholder':'Enter institution name'}), 'last_passing_year' : forms.DateInput(attrs={'class':'form-control form-control-lg', 'type':'date'}), }, ) Html: {% extends 'base/base.html' %} {% load static %} {% load crispy_forms_tags %} {% block content %} <div class="card"> <form class="form-horizontal" action="" method="post"> {% csrf_token %} <div class="card-body"> <div class="card-body"> <div class="form-horizontal"> {{ employAcademicFormSet.management_form … -
Docker and Django. django.db.utils.OperationalError: could not connect to server
I can't find solution, please help! I have Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app RUN pip install Django \ && pip install psycopg2 \ && pip install jinja2 \ && pip install Pillow COPY . /app/ And docker-compose.yaml version: "3" services: db: image: postgres environment: - POSTGRES_DB=folivora - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - 5432:5432 site: image: folivora:latest command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app depends_on: - db ports: - 8000:8000 And settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'folivora', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': '5432', } } And ERROR when run "docker-compose up" site_1 | django.db.utils.OperationalError: could not connect to server: Connection refused site_1 | Is the server running on host "db" (192.168.224.2) and accepting site_1 | TCP/IP connections on port 5432? When I edit docker-compose.yaml, change string command to: command: bash -c "python manage.py runserver 0.0.0.0:8000" all is fine. So, migration line broke my code, but i don't know why. I try to create empty django project to check the same config. On first "docker-compose up", all started and working fine, but from second start, all is broke again with the same error. Over … -
I want to load another view file after the url / but receiving an error saying page not found
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/music/2/ Using the URLconf defined in Analytic_practice.urls, Django tried these URL patterns, in this order: admin/ music/ [name='index'] music/ (?P<album_id>[0-9]+)/ [name='detail'] The current path, music/2/, didn't match any of these. Here is my code: **music.urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('(?P<album_id>[0-9]+)/', views.detail, name='detail'), ]** **views.py from django.http import HttpResponse # noinspection PyUnusedLocal def index(request): return HttpResponse("<h1>This will be a list of all Albums</h1>") # noinspection PyUnusedLocal def detail(request, album_id): return HttpResponse("<h2>Details for Album id: " + str(album_id) + "</h2>")** **Analytic_practice.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')), ]** -
Could not parse the remainder: '"base.html"' from '"base.html"'
I have searched everywhere can't seem to find what's wrong with this code. < html> <head><meta charset="utf-8"> <title></title> </head> <body> <p> {% extends &quot;base.html&quot; %} {% load static %} {% block title %} About {% endblock %} {% block content %} </p> <header>{% block nav %} {% include &#39;nav.html&#39; %} {% endblock nav %}</header> It keeps throwing this error Could not parse the remainder: '"base.html"' from '"base.html"' At times it work, some other time, it does not. What could be wrong? -
The current path, catalog/, didn't match any of these(Django)
in my django project when i make the basic project skeleton and try to run it, when i enter http://127.0.0.1:8000/ in my browser it jumps to url: http://127.0.0.1:8000/catalog/ which causes an error that 'The current path, catalog/, didn't match any of these. can anybody help me with this problem?? -
How to add a field many times in Django admin panel
what is the best way to add a field many times in Django admin panel i mean how i can add many names in admin panel i have this code in models.py : from django.db import models class Android(models.Model): name = models.CharField(max_length=50,default="") def __str__(self): return self.name any help -
SQL - which index will speed up the COUNT() query
I have a very simple Postgres database that looks like that (it's defined in Django but this doesn't matter): class Country: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # Not important # name = models.TextField(nullable=False) class City: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # name = models.TextField(nullable=False) country = models.ForeignKey(Country) class Street: id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # name = models.TextField(nullable=False) city = models.ForeignKey(City) # Just some boolean field is_big = models.BooleanField(nullable=False) I want to query the number of "big" streets in a country. This is done like that: SELECT COUNT(*) FROM Street INNER JOIN City ON Street.city_id = City.id WHERE Street.is_big = true AND City.country_id = 'xxxxxxx'::uuid There are a total of around ~20 countries, ~5000 cities and ~2 million streets in the database, which is not a lot, yet this query can take sometimes 1-2 seconds. What index should I add to make this query fast? -
Cannot change email subject prefix from [example.com] in production
I was able to change it in development, however, I am not able to change it in production for some reason. I did both: set ACCOUNT_EMAIL_SUBJECT_PREFIX = "[MyApp] " set the site's name to 'MyApp' (I even deleted the existing Site object and created a new one). What could I be missing? -
Applying highlighting effect to text(Django)
I am writing a custom template filter that highlights the keyword put into the search engine in the search results page, just like in Google search results. According to The other answer, the working code is below. custom.py from django import template from django.utils.safestring import mark_safe from django.utils.html import conditional_escape from django.template.defaultfilters import stringfilter register = template.Library() @register.filter(needs_autoescape=True) @stringfilter def highlight(value, search_term, autoescape=True): return mark_safe(value.replace(search_term, "<span class='highlight'>%s</span>" % search_term)) But I don't know how to apply this code to my django app. import this custom.py to template html file? Do I need to change views.py? Please teach me how to carry out this code. -
How to use a field from a user defined table type for a stored procedure in Django?
I have a stored procedure in which @productId is INT, and @subProductID is coming from a user defined table type. Now, I want to run the stored procedure on the basis of that @subProductID and get values for my function. How to do that? If I try hard coding subproductID as int or string, it gives an error.