Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NewsAPI not able to fetch news of a given city
So, I'm basically trying to make a website that brings information about cities when you input a city name. Right now all I'm able to, successfully, display is the weather report of a city. I'm trying to bring some news headlines as well. I tried this code. And this, as far as I know about the language, should have worked. views.py from django.shortcuts import render import requests import json from datetime import datetime def index(request): try: if request.method == 'POST': API_KEY = '#################################' city_name = request.POST.get('city') url = f'https://api.openweathermap.org/data/2.5/weather?q={city_name}&appid={API_KEY}&units=metric' response = requests.get(url).json() current_time = datetime.now() directives, it will take this format Day, Month Date Year, Current Time formatted_time = current_time.strftime("%A, %B %d %Y, %H:%M:%S %p") information in one dictionary city_weather_update = { 'city': city_name, 'description': response['weather'][0]['description'], 'icon': response['weather'][0]['icon'], 'temperature': 'Temperature: ' + str(response['main']['temp']) + ' °C', 'country_code': response['sys']['country'], 'wind': 'Wind: ' + str(response['wind']['speed']) + 'km/h', 'humidity': 'Humidity: ' + str(response['main']['humidity']) + '%', 'time': formatted_time } else: city_weather_update = {} context = {'city_weather_update': city_weather_update} return render(request, 'index.html', context) except: return render(request, 'error.html') def news(request): try: if request.method == 'POST': API_KEY = '#################################' city = request.POST.get('city') url = f'https://newsapi.org/v2/top-headlines?q={city}&apiKey={API_KEY}' response = requests.get(url) data = response.json() articles = data['articles'] else: articles = {} … -
Vagrant was unable to connect to the virtual machine VirtualBox
I can't connect to the virtual machine. Could you help me with my problem? Here is the log from GitBash: py@cpython MINGW64 ~/courses/profiles-rest-api (master) $ vagrant up Bringing machine 'default' up with 'virtualbox' provider... ==> default: Box 'ubuntu/bionic64' could not be found. Attempting to find and install... default: Box Provider: virtualbox default: Box Version: ~> 20200304.0.0 ==> default: Loading metadata for box 'ubuntu/bionic64' default: URL: https://vagrantcloud.com/ubuntu/bionic64 ==> default: Adding box 'ubuntu/bionic64' (v20200304.0.0) for provider: virtualbox default: Downloading: https://vagrantcloud.com/ubuntu/boxes/bionic64/versions/20200304.0.0/providers/virtualbox.box Download redirected to host: cloud-images.ubuntu.com default: ==> default: Successfully added box 'ubuntu/bionic64' (v20200304.0.0) for 'virtualbox'! ==> default: Importing base box 'ubuntu/bionic64'... ==> default: Matching MAC address for NAT networking... ==> default: Checking if box 'ubuntu/bionic64' version '20200304.0.0' is up to date... ==> default: Setting the name of the VM: profiles-rest-api_default_1685446821258_41886 Vagrant is currently configured to create VirtualBox synced folders with the SharedFoldersEnableSymlinksCreate option enabled. If the Vagrant guest is not trusted, you may want to disable this option. For more information on this option, please refer to the VirtualBox manual: https://www.virtualbox.org/manual/ch04.html#sharedfolders This option can be disabled globally with an environment variable: VAGRANT_DISABLE_VBOXSYMLINKCREATE=1 or on a per folder basis within the Vagrantfile: config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false ==> default: Clearing any previously set … -
Is there a way to fetch and serialize only a portion of data on demand/onclick in Django to improve performance?
I want to fetch a portion of the data and display it on demand/onclick when a user requests for it from django and serialize it. At the moment, I fetch all data to the client which could cause performance issues as the application scales. How can I achieve that using my get code snippet below. It would be great if anybody could help me out with what I am trying to solve. Thank you so much in advance. def get(self, request, hashid=None, lang=None): try: if hashid: pk_id = settings.LKC_HASH.decode(hashid)[0] disease = Disease.objects.get(pk=pk_id) serializer = CategoriesSerializer(disease) else: diseases = Disease.objects.values('id', 'translations__subcategory', 'translations__name').all() serializer = CategoriesSerializer(diseases, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Disease.DoesNotExist: return Response({'error': 'Disease Does Not Exist!'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: capture_exception(e) return Response({'error': 'There was an error while fetching the diseases!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) -
How to Properly Use "Sign In With Google" Button on Django Web App using Django all-auth
In my Django web app(Currently not in production), i want to use all-auth for signing in users with their Google account and that is working by using the below form for social account. //templates/socialaccount/login.html {% extends "socialaccount/base.html" %} {% load i18n %} <h1 class="display-4">{% blocktranslate with provider.name as provider %}Sign In Via {{ provider }}{% endblocktranslate %}</h1> <p>{% blocktranslate with provider.name as provider %}You are about to sign in from {{ provider }}.{% endblocktranslate %}</p> {% endif %} <form method="post"> {% csrf_token %} <button class="btn btn-outline-info" type="submit">{% translate "Sign In" %}</button> </form> after clicking on sign in button it is opening the new url like - https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?client_id=5649........apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Faccounts%2Fgoogle%2Flogin%2Fcallback%2F&scope=profile&response_type=code&state=ch...kO&access_type=online&service=lso&o2v=2&flowName=GeneralOAuthFlow that's asking me to choose the Google account, after i select my account it signs me in and redirect to the django app's homepage. which is working as expected, But after reading the Google Brand Guidelines, i came to know we should use the sign in with google button that comply their guidelines like in their documentation - https://developers.google.com/identity/gsi/web/guides/personalized-button So how can i use that button that will comply Google's guidelines for signing in and does not disturb the login and authentication flow. i create the button with Google button generator for sign … -
Django static files not loading, all settings seemingly correct
I've setup several django sites in the past, I'm not new to django by any means. I just setup a new site a few hours ago, and frustratingly I can not get any static files to load when accessing the site through a browser. It's a default django install, almost nothing has been changed except a new app made and a few core changes to settings.py relevant settings are: STATIC_ROOT = "/home/jake/apps/mysite-static/" STATIC_URL = '/static/' I've also tried STATIC_URL = 'https://example.com/static/' In my static dir, I have a file test.txt, so the path is /home/jake/apps/mysite-static/test.txt, which means I should be able to access that file in a browser via https://example.com/static/test.txt Error log reports Not Found: /static/test.txt, and error page in browser with Debug=True shows django going through my urls.py and failing to find a match. I have other django sites already running with basically the exact same settings (just different paths because of different project names), so I'm very confused why this simple setup isn't woring here. What am I missing? -
Common method for DRF model Viewset
I have multiple model viewsets that overrides perform_create as below. def perform_create(self, serializer): user=self.request.user instance = serializer.save(user=self.request.user) I am inserting this codes for every modelviewsets I am creating. Is there any way to make this more structured instead of inserting codes everytime? -
Getting '502 Bad Gateway nginx/1.18.0 (Ubuntu)' error on AWS EC2 instance while deploying Django app
My Django App deploy on AWS EC2 instance There I install nginx server this in nginx.conf file` user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens of proxy_read_timeout 300; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip Settings ## gzip on; # gzip_vary on; # gzip_proxied any; # gzip_comp_level 6; # gzip_buffers 16 8k; # gzip_http_version 1.1; # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } #mail { # # See sample authentication script at: # # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript # # # auth_http localhost/auth.php; # # pop3_capabilities "TOP" "USER"; # # imap_capabilities "IMAP4rev1" "UIDPLUS"; # # server { # listen localhost:110; # protocol pop3; # proxy on; # } # # server { # listen localhost:143; # protocol imap; # proxy on; # … -
Can I input any character value to form which is defined as ForeignkeyField?
First, This is my first question in stack overflow, please bear with me. Using Django. I want to input a character value to form defined as Foreignkey field (in this case, it's category form). I appreciate giving me a solution for this, also telling me which is best idea to input a character value as someone want to input to category form or only input value> to category form. models.py class Category(models.Model): # id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=15) def __str__(self): return f"{self.name}" class Listing(models.Model): id = models.BigAutoField(primary_key=True) title = models.CharField(max_length=15) description = models.CharField(max_length=100) starting_bid = models.IntegerField() image = models.ImageField(upload_to='images', null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, related_name="category_name") def __str__(self): return f"{self.id}: {self.title}: {self.description}: {self.starting_bid}: {self.image}: {self.category}" forms.py class ListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "starting_bid", "image", "category"] views.py def create_listing_view(request): if request.method == "POST": form = ListingForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('listings')) else: form = ListingForm() return render(request, 'auctions/create.html', {'form': form}) create.html {% block body %} <h1>create</h1> <form action="{% url 'create' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <br><br> <button type="submit" value="Submit">Create</button> </form> {% endblock %} this image is present condition I tried to do this myself, but I couldn't do as I … -
Overriding LoginView has no effect in the registration template
I tried to add some classes to my projects login template via overriding the LoginView as described here, but I seem to miss something obvious: views.py: class CustomLoginView(LoginView): # template_name = "registration/login.html" # standard form = UserLoginForm forms.py: class UserLoginForm(AuthenticationForm): username = forms.CharField(label = "", widget = forms.TextInput(attrs = {"class": "test", "placeholder": "username or email",})) password = forms.CharField(label = "", widget = forms.PasswordInput(attrs = {"placeholder": "",})) project.urls.py: from myapp.views import CustomLoginView urlpatterns = [ path("home/", RedirectView.as_view(url = "/")), path("admin/", admin.site.urls), path("", include("myapp.urls")), # path("", include("django.contrib.auth.urls")), path("login/", CustomLoginView.as_view(), name = "login"), ] login.html: <form action="" method="post" novalidate> {% csrf_token %} {{ form }} <button type="submit" value="login">login</button> </form> But when I open the login/ url I can't see the placeholder or the class I added, which makes me think, that my customized form is not being used at all - I just don't understand why. I tried excluding path("", include("django.contrib.auth.urls")) in the urls.py but that had no effect. Login works fine by the way. -
How Django runs tests parallelly?
I'm curious how django runs test parallelly with python manage.py test --parallel. Would someone please explain the what happens under the hood and and the the life cycle of test with an example. -
Django translation - PO file is missing the msgstr, it is appearing as an empty in PO file
Here, we are trying to translate the text, however, the PO file is appearing msgstr as "" #: frontend/languages/management/commands/translate.txt:302 msgid "Available Actions" msgstr "" Is there any solution to get the translated msgstr? -
Tips for making Django project responsive with Bootstrap and Sass?
I have 2 question about incorporating bootstrap, sass and django together. (1) I just completed a django course and the project we built along the line is not responsive enough. How can I incorporate bootstrap and sass into the project, and i prefer npm installation with bootstrap and sass. I don't want to use CDN in my projects (2) As an upcoming Backend developer with django, how should I start my web projects with: Pip virtualenv Pip django Npm Bootstrap 5 Npm Sass etc Pls i need details explanation I don't mind a YouTube video link or an article. Thanks Bootstrap Sass Django -
Why does clicking on a brand checkbox in Django and Ajax result in displaying another HTML page?
I am trying to filter products by brand name through checkboxes using django, ajax jquery, but while clicking on the checkbox I am having another products html page within the running html page including all the products. But while printing in console, i can see that unique brand name is being selected while checking a checkbox field. Views.py `def list_products(request): ordering = request.GET.get('ordering', "") search = request.GET.get('search', "") brands = set(Product.objects.values_list('brand', flat=True)) colors = Product.objects.values_list('color', flat=True).distinct() selected_brands = request.GET.getlist('brand') selected_colors = request.GET.getlist('color') filtered_products = Product.objects.all() if selected_brands: filtered_products = filtered_products.filter(brand__in=selected_brands) if search: filtered_products = filtered_products.filter(Q(title__icontains=search) | Q(brand__icontains=search)) if ordering: filtered_products = filtered_products.order_by(ordering) context = { 'brands': brands, 'colors': colors, 'selected_brands': selected_brands, 'selected_colors': selected_colors, 'products': filtered_products, } return render(request, "products/listproducts.html", context)``` ` HTML Code block ` All Brands {% for brand in brands %} <input class="custom-control-input brand-checkbox" type="checkbox" id="brand-{{ brand }}" name="brand" value="{{ brand }}" {% if brand in selected_brands %}checked{% endif %}> {{ brand }} {% endfor %} ` JavaScript Code block: `$(document).ready(function() { console.log("Document ready!"); // Handle checkbox change event $(document).on('change', '.brand-checkbox', function() { // Get the selected checkbox values var selectedBrands = $('input[name="brand"]:checked').map(function() { return this.value; }).get(); // AJAX request to update filtered products $.ajax({ type: "GET", url: … -
Share and save a contact with click on link in browser
I have a query? I want to save contact. when i click on the link which is mention in website. how to do? Its work on mobile application( QR. Code Scanner). When i scan a Qr code of contact.after that the scanner open a contact app and ask to save a contact. it work both android and IOS(Apple device). The same process,i want to without scan a code. when i click a link in browser contact app open and ask me to save a contact in mobile device. I am doing this functionality in Python with Django Framework. what is do to do that? How Work on mobile device. Step 1. First a QR code of contact with this website. Qr code generator Step 2. then i select a VCARD , fill the form and submitted. Step 3. after that it will generate a QR image code. Step 4. then i open a mobile scanner app to scan this code. Step 5. it will redirect and open a contact app to save this contact. I am doing this functionality in Python with Django Framework. what is do to do that? #django #python #QRcode #VCARD #Conact #Javascipt #Share -
Why am I getting 'pg_config executable not found' when deploying my web app using Vercel?
I'm trying to use Psycopg2 with Railway to connect django to postgres using this tutorial: https://dev.to/dennisivy11/easiest-django-postgres-connection-ever-with-railway-11h6. However, I got "pg_config executable not found" when trying to deploy my django web app to Vercel. This is what I get from Vercel: Error: Command failed: pip3.9 install --disable-pip-version-check --target . --upgrade -r /vercel/path0/workout_log/requirements.txt error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [35 lines of output] /tmp/pip-build-env-wf1ju6t6/overlay/lib/python3.9/site-packages/setuptools/config/setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg` !! ******************************************************************************** The license_file parameter is deprecated, use license_files instead. By 2023-Oct-30, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! parsed = self.parsers.get(option_name, lambda x: x)(value) running egg_info writing psycopg2.egg-info/PKG-INFO writing dependency_links to psycopg2.egg-info/dependency_links.txt writing top-level names to psycopg2.egg-info/top_level.txt Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the … -
Is there a convention for returning an empty template in Django when making HTMX calls?
There are cases where I would like to not return any HTML in my view. Is there a good way to do it apart from returning a blank html file? Here is what I have currently: views.py def get_suites(request): address = request.GET.get('address') rental_units = Rental_Unit.objects.filter(address__address=address).order_by('suite') # return empty html requests if len(rental_units) > 1: return render(request, 'suite_list.html', {'rental_units': rental_units}) else: return render(request, 'empty.html') suite_list.html <label for="suite">Suite</label> <select name="suite" id="suite"> <option value="all">All</option> {% for rental_unit in rental_units %} <option value="{{rental_unit.suite}}">{{rental_unit.suite}}</option> {% endfor %} </select> main.html <label for="address">Address</label> <select name="address" id="address" hx-get="/get_suites" hx-target="#suite-wrapper"> <option value="all">All</option> {% for address in addresses %} <option value="{{address}}">{{address}}</option> {% endfor %} </select> <div id="suite-wrapper" style="display:inline"></div> -
How can I fix an 'invalid response' when using Django session and AJAX for ecommerce platform?
I am currently building an ecommerce platform and using Django session and AJAX. All I am trying to get is the response from the endpoint but it seems to be giving me an 'invalid response'. Below is my code. I will be glad if I am able to get help. var addToCart = document.getElementsByClassName("add-to-cart"); Array.from(addToCart).forEach(function (btn) { btn.addEventListener("click", function () { var product_id = btn.dataset.product; var action = btn.dataset.action; console.log(product_id, action); if (user === "AnonymousUser") { // Apply a flas message here in future console.log( "You need to be a registered user before you can buy a product" ); } else { updateUserOrder(product_id, action); } }); }); function updateUserOrder(product_id, action) { var url = "add/add_product/"; data = { 'product_id': product_id, 'action': action, } console.log(data); fetch(url, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify(data), }) .then((response) => { return response.json(); }) .then((data) => { console.log("data:", data); }); }``` view def add_to_cart(request): cart = Cart(request) if request.POST.get('action') == 'add': product_id = request.POST.get('productId') product = get_object_or_404(Product, product_id=product_id) cart.add(product=product) response = JsonResponse({'test': "this is a test data"}) return response return JsonResponse({'message': 'invalid data'}) Add To Cart I tried ensuring that the namings are okay but that didnt work. Please, what … -
Streaming Chat completion using langchain and websockets
I am not sure what I am doing wrong, I am using long-chain completions and want to publish those to my WebSocket room. Using BaseCallbackHandler, I am able to print the tokens to the console, however, using AsyncCallbackHandler is a challenge, basically, nothing seems to be happening, I tried printing stuff, but after the print message on init, nothing seems to be happening. async def send_message_to_room(room_group_name, message): print("sending message to room", room_group_name, message) channel_layer = get_channel_layer() await channel_layer.group_send( room_group_name, { "type": "chat_message", "message": message, } ) class MyCustomHandler(AsyncCallbackHandler): def __init__(self, room_group_name): self.channel_layer = get_channel_layer() self.room_group_name = room_group_name print("MyCustomHandler init") async def on_llm_new_token(self, token: str, **kwargs): print(token) await send_message_to_room(self.room_group_name, token) def generate_cited_answer_stream(roomname, question=question, texts=texts, responsetype="Simple and Pedagogical" , system_message_with_response_type=system_message_with_response_type , human_message_with_response_type=human_message_with_response_type): handler = MyCustomHandler(room_group_name=roomname) chat = ChatOpenAI(temperature=0, streaming=True, callbacks=[handler]) system_message_with_response_type = SystemMessagePromptTemplate.from_template(system_message_with_response_type) human_message_prompt = HumanMessagePromptTemplate.from_template(human_message_with_response_type) chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt]) prompt_value = chat_prompt.format_prompt(question=question, texts=texts, responsetype=responsetype) chat(prompt_value.to_messages()) -
User defined user permissions
I'm not even sure how to fully ask this question so my googles haven't turned up much. So I have users, (obv) and they have an entity they're gonna be able to populate called a wallet. A user should have read write and delete permissions on a waller they create Naturally superadmins should have access to everything. But I want the users to be able to give other users read and / or write access. But regular staff should also have access. Do I just create a foreign key on the wallet populated with the user id's and boolean for read, write and delete access? Assuming I do that how do I handle Staff and super admin access? Do I like set up a view for a list of wallets that checks to see if you're an admin or staff and if not then checks if you have access and only displays those? And then only allow you to edit or delete if you have those boolean set? Does that make sense? -
openai module not found but can be clicked while importing in ide to go to its library
I am trying to create a chat bot with openai on django. But it shows that it doesnt exist in the IDE. I click on 'openai' and it takes me to its library. When i type "pip show openai" , it gives : Name: openai Version: 0.27.7 Summary: Python client library for the OpenAI API Home-page: https://github.com/openai/openai-python Author: OpenAI Author-email: support@openai.com License: Location: /Users/user/PROJECTS/chatbot_project/env_chat/lib/python3.9/site-packages Requires: aiohttp, tqdm, requests Required-by: the python and pip have version 3.9 i dont understand that if i am able to click on the 'openai' while importing it and it dont even red underline it so why it tells the module dont exist. import openai my python interpreter is linked with the env i created in the project i.e. env_chat i am a bit new, so help me out on this. -
some html files load in just fine and others don't work at all even tho they have the same code and are in the same folder
my problem is i have multiple files in my project that use basically the same code but with some files it does work and with others not. and all the files are in the same folder. i have tried troubleshooting and looking at the Debugging Tool on browsers and even asked chatgpt i don't get it this code works. {% extends "base.html"%} {% block subheader%} <div class="sub-header"> <div class="sub-middel"> <button class="sub-bu" onclick="window.location.href='{% url 'projects_unity' %}'">unity</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_websites' %}'">websites</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_construct' %}'">construct</button> <button class="sub-bu" onclick="window.location.href='{% url 'projects_godot' %}'">godot</button> <!-- {% for program in post.programs.all%}--> <!-- <button class="sub-bu">{{program}}</button>--> <!-- {% endfor %}--> </div> </div> {% endblock subheader %} {% block content %} {% for post in posts_websites %} <div class="posts"> <h1> {{post.title}} </h1> <!-- Slideshow container --> <div class="slideshow-container"> <!-- Full-width images with number and caption text --> {% for image in post.image.all %} <div class="mySlides"> <div class="numbertext" ><p id="currentnummer"></p><p id="imagesnummer"></p> </div> <img src="{{ image.image.url }}" alt="{{ image.image.name }}" style="width:100%" height = "348" > <div class="text">{{image.CaptionText}}</div> </div> {% endfor %} <!-- Next and previous buttons --> <a class="prev" onmouseenter="changemouseicon(true)" onmouseleave="changemouseicon(false)" onclick="changeSlide(-1)">&#10094;</a> <a class="next" onmouseenter="changemouseicon(true)" onmouseleave="changemouseicon(false)" onclick="changeSlide(1)">&#10095;</a> </div> <p> by {{ post.author }} on {{post.date_posted}} </p> <p … -
Why does the built-in "with" template tag in django result in duplicate queries
In the django docs for the "with" template tag, it says that this tag.. is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times. However, when I use it in my own template, I've observed (using django debug toolbar) that each time I call the variable that I create using the "with" template tag, it results in duplicate queries to the database if I perform an operation on that variable within another template tag. Why is this the case? Shouldn't I be able to do things to that variable without it querying the database? Below is my abridged and simplified code. Background I have three models: ## models.py class Contributor(models.Model): name = models.CharField(max_length=100) class Contribution(models.Model): contributor = models.ForeignKey( Contributor, on_delete=models.RESTRICT, related_name='contributions' ) class ROLE_CHOICES(models.TextChoices): A = 'AUTHOR', _('Author') C = 'COAUTHOR', _('Co-Author') E = 'EDITOR', _('Editor') V = 'VOICE', _('Voice Actor') S = 'AUDIO', _('Audio Engineer') role = models.CharField(max_length=10, choices=ROLE_CHOICES.choices) class Scenario(models.Model): title = models.CharField(max_length=200) contributions = models.ManyToManyField( Contribution, related_name='contributions' ) The template is associated with a class-based detail view: ## views.py class ScenarioDetailView(generic.DetailView): model = Scenario Here is my custom template tag code: ## custom_tags.py @register.filter def only_role(scenario, test_role): return scenario.contributions.filter(role=test_role) Here is my … -
How do I combine multiple sorting/filtering logic in Django in efficient way?
I am trying to make a site that supports searching/sorting/filtering at the same time. I did it in the 'if/elif' logic and it works! But it doesn't seem to be so efficient (from perspective of copying the code many times and inability to change something fast). As you can see in code examlpe below, I just specify these conditions for each possible case, such as: "with filter1, but without filter2 and filter3"; "with filter1 and filter2, but without filter3" and so on. As you can imagine, adding filters 4 and 5 sounds like a nightmare now, to be able to redo all this logic. Can you please share your thougths on how to do in a better way? I'm new to Django, so looks like I'm doing something wrong here Here is how my main view inside views.py looks like: class ResultsView(LoginRequiredMixin, ListView): model = Ads paginate_by = 9 template_name = 'library.html' #GET SEARCH def get_queryset(self): query_search = self.request.GET.get('search') query_sort = self.request.GET.get('sort_by') query_filter = self.request.GET.get('filter_by_language') query_search_username = self.request.GET.get('search_username') #search=YES, sort=NO, filter=NO if query_search and not query_sort and not query_filter: object_list = self.model.objects.filter(Q(headline__icontains=query_search) or Q(promoted_url__icontains=query_search)) elif query_search_username: #and not query_sort and not query_filter: object_list = self.model.objects.filter(Q(username__iexact=query_search_username)) #search=YES, sort=NO, filter=YES elif query_search … -
Accessing OneToOneRel object in Django to perform search
currently I am working on a Django project, where we have created many relations between objects. In general - everything is working fine, expect - Frazesearch. Below I paste my model classes: Students.py from django.db import models from degreeCourse.models import DegreeCourse from studentFinances.models import StudentFinances from studentLoggingData.models import StudentLoggingData from studentPersonalData.models import StudentPersonalData # Create your models here. # Part already after refactor class Student(models.Model): personalStudentData = models.OneToOneField( StudentPersonalData, on_delete=models.CASCADE, default=None ) loggingStudentData = models.OneToOneField( StudentLoggingData, on_delete=models.CASCADE, default=None ) financesStudentData = models.ManyToManyField( StudentFinances ) STUDENTS_UPLOAD_TO = "students/" image = models.ImageField( null=True, blank=True, upload_to=STUDENTS_UPLOAD_TO ) def __str__(self): return f"{self.personalStudentData.name} {self.personalStudentData.surname}" StudentPersonalData.py from django.db import models # Create your models here. class StudentPersonalData(models.Model): name = models.CharField( max_length=40, null=False, unique=False ) surname = models.CharField( max_length=50, null=False, unique=False ) personalIdNumber = models.CharField( max_length=11, null=False, unique=True ) phoneNumber = models.CharField( max_length=20, null=False, unique=True ) email = models.CharField( max_length=50, null=False, unique=True ) streetAddress = models.CharField( max_length=40, null=True, unique=False ) houseNumber = models.CharField( max_length=4, null=False, unique=False ) flatNumber = models.CharField( max_length=4, null=True, unique=False ) zipNumber = models.CharField( max_length=6, null=False, unique=False ) country = models.CharField( max_length=40, null=False, unique=False ) isActive = models.BooleanField( default=True, null=False ) def __str__(self): return f"{self.name} {self.surname}" The problem is in views.py file for Student, … -
Elasticsearch Highlight result missing string
I am trying to use Elasticsearch's highlighting feature to highlight certain words from a text field. The text can be short or long (over 300 chars sometimes). Here is the highlight field passed to search function: def search(self): highlight = { "fields": { "content": { "type": "plain", "number_of_fragments": 0, } } } s = super(FacetedCustomSearch, self).search() return s.extra(highlight=highlight) As you can see below, the highlighted text is missing the - 1 POUND BAG string at the end. This usually happens when the text is over ~100 chars and sometimes with special characters like ! or / or - content: YOUR OFFICEKITCHEN - TASTING KITCHEN - SWEET CHILI HABANERO - GOURMET HANDMADE CRAFT MEAT SNACK - 1 POUND BAG highlighted content: YOUR OFFICEKITCHEN - TASTING KITCHEN - SWEET CHILI HABANERO - <em>GOURMET HAND</em><em>MA</em>DE CRAFT MEAT SNACK So far, I have tried to tweak the number_of_fragments (setting it to 0) and fragment_size and set the type to plain. Nothing seems to fix this issue. Any suggestions? Using elasticsearch-dsl 7.4.0