Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django uWSGI + Nginx failed (104: Connection reset by peer) while reading upstream, client:
I have an issue uploading files to media. The files size is about 500M to 1GB. Configuration is Django + uWSGI + NGINX. Upload is restarting and restarting and finally cancelled. Error message is: failed (104: Connection reset by peer) while reading upstream, client:... For File-Upload I am using: django-file-form 3.1.0. Does anybody can help? Thx. -
Reverse for url with arguments '('',)' not found, but only on a certain machine
I deployed using Gunicorn and Nginx, and am seeing this error in one machine that's using my app, but not in the rest, so I'm starting to think it is an issue on the machine the error is displaying but not in the app. When doing the exact same actions to replicate the error in other machines, the app works just fine. The template form that causes the error: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_quantity"></label> <input data-toggle="touchspin" type="number" value="1" required id="id_quantity" name="quantity" data-bts-button-down-class="btn btn-danger" data-bts-button-up-class="btn btn-primary"> <input type="hidden" name="override" value="False" id="id_override"> </div> <button type="submit" class="btn btn-secondary"> <i class="uil-plus-circle"></i> Add to order </button> </form> urls.py: from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('', views.cart_detail, name='cart_detail'), path('add/<int:product_id>', views.cart_add, name='cart_add'), path('remove/<int:product_id>', views.cart_remove, name='cart_remove'), path('clear/', views.cart_clear, name='cart_clear'), ] Again, in other machines it is working just fine. -
Filtering on related fields in Django
I have two models in my Django project: ModelA(models.Model): name = models.CharField(max_length=20) ModelB(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) date = models.DateField() There is a one-to-many relationship between models A and B, with around 50 instances of model A and 100,000 entries for model B. In the problem that I'm having, I have a specific queryset of ModelB, and from this queryset I want to know, for each date, how are these ModelB's distributed among the different ModelA. The data structure that I require is as follows: [ { "date": date_1, "num": num_1, "bins": [ { "name_A": model_A_1, "num": num_A_1_1 }, { "name_A": model_A_2, "num": num_A_1_2 } ] }, { "date": date_2, "num": num_2, "bins": [ { "name_A": model_A_1, "num": num_A_2_1 }, { "name_A": model_A_2, "num": num_A_2_2 } ] } ] where date_1 is one of the existing dates in Table B, num_1 is the total number of ModelB with date date_1. bins contains the distribution of ModelB among the different ModelA's, e.g. num_A_1_1 corresponds to the number of ModelB with date date_1 and Foreign key model_A_1, etc. Here's what I have tried: date_bins = initial_modelB_queryset.values("date").order_by("date").distinct() output = [] for bin in date_bins: B_A_queryset = ModelA.objects.filter(modelB__in=initial_modelB_queryset, modelB__date=bin["date"]) B_num = B_A_queryset.count() bins = … -
How to do a translator?
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): phrase = request.POST.get('text', 'translation') translation = phrase context = { 'translation': translation } return render(request,self.template_name, context) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
Cannot connect to test database after upgrading to django 3.1
I am trying to migrate a django app from 3.0.11 to 3.1. I can run the app without any issues. But I cannot run tests anymore. The following error is thrown when running python manage.py test django.db.utils.ConnectionDoesNotExist: The connection e doesn't exist This is from my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config("DB_NAME", default='postgres'), 'USER': config('DB_USER', default='postgres'), 'PASSWORD': config('DB_PASSWORD', default='postgres'), 'HOST': config('DB_HOST', default='postgres'), } } Full stacktrace: Creating test database for alias 'default'... Destroying test database for alias 'default'... Traceback (most recent call last): File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/db/utils.py", line 172, in ensure_defaults conn = self.databases[alias] KeyError: 'e' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 23, in run_from_argv super().run_from_argv(argv) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/commands/test.py", line 53, in handle failures = test_runner.run_tests(test_labels) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 698, in run_tests self.run_checks(databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/test/runner.py", line 636, in run_checks call_command('check', verbosity=self.verbosity, databases=databases) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/usr/local/Caskroom/miniconda/base/envs/mysite/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = … -
Previewing images using Django
I have a html,css and js app that I ported to Django and I want to preview an image before upload. A dropdown form allows users to select an option that will then display the image onto the screen before upload. I did this through javascript by setting img src = "" to empty and then when the user selected an option from the dropdown menu, javascript set the img src path i.e if user selected car from menu then js would set img src=images/car.png and display it. function displayImage(imgValue){ if (imgValue == 'car') { previewImage.setAttribute("src", "images/car.png"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; } else if (imgValue == 'location') { previewImage.setAttribute("src", "images/newyork.jpg"); previewDefaultText.style.display = "none"; previewImage.style.display = "block"; .... .... } The issue is that the JS isn't setting the path of the img src in Django. Can I do this through JS or will it require to rewrite in a more Django/pythonic way? Note: w/o the use of ajax. -
Convert multiple texts with python markdown in django views
I have a blog that uses markdown. I am trying to convert it to HTML in views.py with python markdown. For individual posts, this code works: def detail_view(request, slug): md = markdown.Markdown() post = get_object_or_404(Post, slug=slug) postcontent = md.convert(post.md_text) context = {...} return render(request, 'details.html', context) However, applying the same logic to a view meant to show multiple posts fails: def home_view(request): posts = Post.objects.order_by('-id') md = markdown.Markdown() for markdown in posts: postcontent = md.convert(posts.md_text) context = {...} return render(request, 'home.html', context) What would I need to change to convert the text_md field(s) of my Post model in this view? Thanks in advance! -
Saving form data in the database
Hello I am new in Django and I have created an available house posting form but I cannot store the entered data in the database. I used if form.is_valid and form.cleaned_data please I need help my code: views.py def public(request): form = PublicationForm() if request.method == 'POST': form = PublicationForm(request.POST, request.FILES) if form.is_valid(): first_name=form.cleaned_data['first_name'] last_name=form.cleaned_data['last_name'] agency_name=form.cleaned_data['agency_name'] city=form.cleaned_data['city'] categories=form.cleaned_data['categories'] status=form.cleaned_data['status'] phone_number_1=form.cleaned_data['phone_number_1'] phone_number_2=form.cleaned_data['phone_number_2'] description=form.cleaned_data['description'] image_one=form.cleaned_data['image_one'] pub = Publication.objects.create( first_name=first_name, last_name=last_name, agency_name=agency_name, city=city, categories=categories, status=status, phone_number_1=phone_number_1, phone_number_2=phone_number_2, description=description, image_one=image_one ) pub.save() return HttpResponse("Publication réussie") else: form = PublicationForm() return render(request, 'pub/public.html', {'form':form}) This is my template views I used the django-crispy-form module public.html <form method="POST" enctype="multipart/form-data " class="form-block "> {% csrf_token %} {{ form.non_field_errors }} <div class="form-row"> <div class="col-md-4 mb-3"> {{ form.first_name.errors }} <label for="{{ form.first_name.id_for_label }} "></label> {{ form.first_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.last_name.errors }} <label for="{{ form.last_name.id_for_label }} "></label> {{ form.last_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.agency_name.errors }} <label for="{{ form.agency_name.id_for_label }} "></label> {{ form.agency_name|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.city.errors }} <label for="{{ form.city.id_for_label }} "></label> {{ form.city|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.categories.errors }} <label for="{{ form.categories.id_for_label }} "></label> {{ form.categories|as_crispy_field }} </div> <div class="col-md-4 mb-3"> {{ form.status.errors }} <label for="{{ form.status.id_for_label }} "></label> … -
How Retrieving a full tree data in Django Self Foreign Key?
I insert 3 records Electronics Null Mobile 1 Iphone 2 class Category(models.Model): name = models.CharField(max_length=160) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) if i search Iphone how to get all related data Example: Category.object.filter(name='Iphone') Result want all parent data ex: Electronics Mobile Iphone -
Linking ParentalKey to Abstract class and all subclasses in Wagtail
I am setting up a website in Wagtail. I have Author snippets which include author information. Each page (BlogPage) can be related to multiple Authors (via an AuthorOrderable). I am now trying to add a new Page type, so I have created an abstract superclass for Authors to link to, however I get the following error: AttributeError: type object 'BlogPage' has no attribute 'author_orderable' class AbstractPage(Page): class Meta: abstract = True author_panels = [ InlinePanel('author_orderable', label="Authors"), ] class BlogPage(AbstractPage): #Some fields- authororderable is not listed here class AuthorOrderable(Orderable, models.Model): page = ParentalKey('AbstractPage', on_delete=models.CASCADE, related_name='author_orderable') author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='+') @register_snippet class Author(models.Model): #Some fields -
Django to Heroku error: ModuleNotFoundError
I keep getting this error when deploying a Django app to Heroku via the Heroku CLI gunicorn the_weather.wsgi Traceback (most recent call last): File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\MARTIN KALAX\AppData\Local\Programs\Python\Python38-32\Scripts\gunicorn.exe_main.py", line 4, in File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\wsgiapp.py", line 9, in from gunicorn.app.base import Application File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\app\base.py", line 11, in from gunicorn import util File "c:\users\martin kalax\appdata\local\programs\python\python38-32\lib\site-packages\gunicorn\util.py", line 9, in import fcntl ModuleNotFoundError: No module named 'fcntl' -
Can you explain easily what is the function of misaka in django?
I'm a beginner at Django. I want to learn about the function of misaka in Django. -
How to get the authentication token from http header in Python Django Project deployed in Windows Server 2019 IIS using httpPlatformHandler?
An internal Python Django project was deployed successfully at IIS using wfastcgi.py. Referring to Authentication using REMOTE_USER, this application can get the log-in domain user information using REMOTE_USER available in the request.META attribute. According to An unknown FastCGI error occurred: Python 3.7 +Djangorestframework #6216, Microsoft/PTVS had stopped supporting wfastcgi.py and recommended to use httpPlatformHandler, my project is migrated to IIS using HttpPlatformHandler v1.2 in Windows Server 2019. Application migration is success except the MIT Kerberos authentication part. With references to HttpPlatformHandler Configuration Reference, when forwardWindowsAuthToken is set to true, the token will be forwarded to the child process listening on %HTTP_PLATFORM_PORT% as a header 'X-IIS-WindowsAuthToken' per request. I have no ideas about how to get this header and its key of Windows Authentication Token. Also with references to How to get the authenticated user name in Python when fronting it with IIS HTTP PlatformHandler and using Windows auth?, I tried to test the program example in both Flask and Django, however, I still cannot figure out how to get the request.headers.key() in Python properly. Could someone provide any hints or advise on this matter please? -
Can we run both Socket Server and Socket Client on the same Django Server?
I have a Django Server work as 2 role: Socket Server and Socket Client. 1/ As a Socket Server, it work on local side, so some clients in same network can connect and receive event. 2/ As a Socket Client, it will connect (using Socket) to another Remote Server to receive events and forward that events to all local clients But when Socket Client receive events then emit to local clients by Socket Server, nothing happen (local clients can't receive that events). If I just emit, my local clients can receive the message. It seem Socket Server and Client can't working together. Here is some sample of my code: // Receive event from Remote Server self.__client__.on("event_msg", self.onEvent) // Forward event to local Clients def onEvent(self, package): self.__socketServer__.emitEvent(event="event_msg", data=package, to=None, room="123") The __socketServer__ is just an instance of SocketServer class, and it can work if just simple send/receive message in local network (not put in socket client event) I'm using python-socketio for both Server+Client -
how to find the no of identical items in a table?
i am developing a web app in Django,using python.i have two classes one for item and other one for item details.i would like to count the similar models in item details table and display it as total quantity for that model in item table. -
How can I use fixtures in tests when using multiple databases in Django?
I am trying to get my Unit Tests to work in Django, in combination with fixtures in a context with multiple databases. What works currently is both Unit Tests with fixtures and Unit Tests using multiple databases, but when I am using both in the same Unit Test, Django doesn't do anything and is stuck at loading the fixture. Code in Unit Test: class MyUnitTestCase(APITestCase): fixtures = (os.path.join(FIXTURE_DIR, "data.json"),) databases = {"default", "datamarts"} DB Router: from django.conf import settings class DBRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label in settings.DATABASE_APPS_MAPPING.keys(): return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) return "default" def db_for_write(self, model, **hints): if model._meta.app_label in settings.DATABASE_APPS_MAPPING.keys(): return settings.DATABASE_APPS_MAPPING.get(model._meta.app_label) return "default" def allow_migrate(self, db, app_label, model_name=None, **hints): return True def allow_relation(self, obj1, obj2, **hints): """ Mostly used to run the tests for the data marts database """ return True Note that fixtures is a very small file that normally loads within a second. When using both multiple databases and fixtures, it takes over an hour - and is still loading. It could possibly be something related to the DB Router, as a breakpoint in db_for_write keeps showing the same model over and over again. -
ReactJS Imports not working blank webpage
I am a beginner learning ReactJS and was trying to make a full-stack quiz web application using DjangoRestFramework+ReactJS and I am not seeing anything rendering to my webpage when I try using imports. I am not getting any error, but my web page is blank. Here is my App.JS. import { render } from "react-dom"; import HomePage from "./HomePage"; import GameJoinPage from "./GameJoinPage"; export default class App extends Component { constructor(props) { super(props); } render() { return ( <HomePage /> ); } } const appDiv = document.getElementById("app"); render(<App />, appDiv); My Index.html <! DOCTYPE html> <html> <head> <meta charset="UTF-9"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Quiz App</title> {% load static %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" /> <link rel="stylesheet" type="text/css" href="{% static "css/index.css" %}" /> </head> <body> <div id="main"> <div id="app"> </div> </div> <script src="{% static "frontend/main.js" %}"></script> </body> </html> And my HomePage file import React, { Component } from "react"; import GameJoinPage from "./GameJoinPage"; import CreateRoomPage from "./CreateGamePage"; import { BrowserRouter as Router, Switch, Route, Link, Redirect} from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render(){ return ( <Router> <Switch> <Route exact path="/"><p>This is the home page</p></Route> <Route path="/join" component={GameJoinPage} /> <Route path="/create" component={CreateGamePage} /> </Switch> … -
Authenticaton Postgres error while using Docker Compose, Python Django and Gitlab CI
I use Gitlab CI to make pipeline with building Docker image with my Django app. I saved some .env variables to Gitlab variables. They are succesfully calling and working, but there is psycopg2.OperationalError: FATAL: password authentication failed for user I have checked all passwords and variables, they are correct. .gitlab-ci.yml image: docker:stable services: - docker:18.09.7-dind before_script: - apk add py-pip python3-dev libffi-dev openssl-dev gcc libc-dev make - pip3 install docker-compose stages: - test test: stage: test script: - docker build -t myapp:$CI_COMMIT_SHA . - docker-compose -f docker-compose.test.yml run --rm myapp ./manage.py test - docker-compose -f docker-compose.test.yml run --rm myapp ./manage.py check - docker-compose -f docker-compose.test.yml down -v -
Constantly get an error "no such table" whatever I do
I am pretty new to django and database management as well, therefore there is certainly a possibility that I do not understand some crucial things about them. I've been trying to solve this error by myriads of ways for a few days (It occured as a result of a declaration of a new field in existing model called Habit), I tried: resetting database with reset_db (django-extensions) flushing it with native django flush command (now I do understand that it was a wrong method) recreating a whole app in another virtual environment with creation of fresh databases faking migrations with --fake (out of desperation basically) manually changing fields in a db with sql browser deleting sqlite database manually and making migrations Here are my models: from django.db import models from django.utils import timezone from datetime import timedelta import datetime # Create your models here. class Day(models.Model): # Creating table for this model didn't cause any trouble date = models.DateField(auto_now_add=True) def __str__(self): return str(self.date) class Habit(models.Model): name = models.CharField(max_length=200) targ_init_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time()) targ_term_time = models.TimeField(auto_created=False, auto_now_add=False, default=datetime.time()) true_init_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time()) true_term_time = models.TimeField(auto_created=False, auto_now_add=False, blank=True, default=datetime.time()) is_completed = models.BooleanField(default=False) day = models.ForeignKey(Day, on_delete=models.CASCADE, related_name='habits') # --That New … -
Trying to configure Gunicorn and Django settings, getting this error: [curl: (52) Empty reply from server]
I'm setting up my production Django app on Ubuntu. First time doing so, I've already troubleshooted and solved my way out of previous errors, however when I test the socket for activation via CURL using this command curl --unix-socket /run/gunicorn.sock localhost, I receive this an error: curl: (52) Empty reply from server. I've tried adding flags -L -vv , doesn't seem to help my case here. gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Here is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=andres Group=www-data EnvironmentFile=/home/andres/alpha/env_var WorkingDirectory=/home/andres/alpha/stockbuckets ExecStart=/home/andres/alpha/stockbuckets/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ stockbuckets.wsgi:application [Install] WantedBy=multi-user.target status of gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-11-25 15:39:48 UTC; 17min ago Triggers: ● gunicorn.service Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Nov 25 15:39:48 sb-django systemd[1]: Listening on gunicorn socket. Given how Gunicorn is up and running, I want to make sure everything works before moving onto the next production stages. Hopefully I could get some advice on how solve for curl: (52) Empty reply from server. When I check the logs for Gunicorn, seems like everything is working a-okay? Please let me know … -
Django debug testpage when application is active in a subpath
In the Django tutorial, a quick way to check if setup of the django application was successful is by visiting the debug testpage. If I create a django application on my server under a subpath instead of on the main url, this page does not seem to work. The url this testpage seems to function on is '/', and my server configuration strips the application name '/demo/', including the slash, resulting in ''. (which causes a 404, empty path not found) It's easy to create a custom testpage on an empty path instead of on slash like so: path('', views.index, name='index'), However, does the missing slash in my application configuration indicate an issue that should be solved? Or is the empty url path for my testpage a logical choice in this situation? -
Problems with data from django to html
My goal is to have the sum of elements in lista [] but gives me this error. Lista[] is composed of decimal numbers ValueError at / argument must be a sequence of length 3 My code : views.py def Home(request): assets = Post.objects.filter(Asset="BTC", Utente="1").values_list('Quantit') lista = [] for asset in assets: lista.append(asset) somma = sum(Decimal(lista)) return render(request, 'porttrack/home.html', {'lista': lista}) models.py from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): Utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Asset = models.CharField(max_length=3) Quantit = models.DecimalField(max_digits=19, decimal_places=11) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) by printing out only lista[] without "somma", it's show a list like that: [(Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('0.01000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),), (Decimal('1.00000000000'),)] Thanks for helping me -
Django-dsl-drf Exclude phrase query
I am working on integrating Elastic Search in my existing Django REST application. I am using the django-dsl-drf module provided in the link below: https://django-elasticsearch-dsl-drf.readthedocs.io/ In their documentation 'exclude' query param is provided. But the query only when we provide the full field value. search-url?exclude=<field-value For eg: If I have a value 'Stackoverflow' in field 'name'. I'll have to provide query param a ?name__exclude=Stackoverflow to exclude records having 'Stackoverflow' as name in the result. I would like to implement a search in such a way that when I provide 'over', I need to exclude these records, similar to ?name__exclude=over I checked the above tutorial, but I couldn't find it. Is there any work around so that I can exclude records, fields containing terms instead of providing full field value, which is also case-insensitive. Thanks a lot. -
Django annotate a Boolean if field value is into an external list
Imagine I have this Django model: Class Letter(models.Model): name = models.CharField(max_length=1, unique=True) and too this list: vowels = ['a', 'e', 'i', 'o', 'u'] I want to make a query over Letter annotating a boolean field, which will be True if name value is in vowels list, and False otherwise I made next query: from django.db.models import Value, F, BooleanField letters = Letter.objects.annotate(is_vowel=Value(F('name') in vowels, output_field=BooleanField())) However no matter what letters I analyze, the result is ALWAYS False What am I doing wrong in my query, and what is the correct way to achieve the desired result? Thanks in advance. -
How to pass database object id which initiated Django post save signal
I am trying to solve the following problem. I have django view which provide functionality to save object in database. After view will save the object i want to proccess some logic on saved object at once (e.g check similarity of some fields with another objects) I hear about django signals specially about post_save signal which i think will appropriate for my usecase. But for my usecase i need to pass object id which initiated execution of post_save signal. Is in django signals any built-in solution to extract this object id to futher passing it to receiver of signal function Hope will my pseudo code will give more ckarification app_view(receive and save data as django model object) post_save signal(receiver, id_of_object_initiated_execution)