Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Im not sure I understand why Django wont let me do asynchronous database transactions
I am trying to create a function that will get_or_create a user record for my discord bot in my django User model as soon as someone runs the !home command - but I am encountering an issue that (as far as I understand) is a normal part of django's existing model wherein it disallows asynchronous database transactions. I've tried using the built in sync_to_async method but it raises similiar issues. Is there something I can change in my settings file or something that I havent been able to find online that would be able achieve this functionality here? Here is my home command that is invoked by the command: @bot.command(name="home", description="Displays the character sheet of your character in Oblivion After you have already created your guy") async def home_async(ctx): user_instance, created = await sync_to_async(User.objects.get_or_create( discord_id=discord_user_id, defaults={'username': ctx.author.name} )) if created: character = Character.objects.create(name=f"New Character for {ctx.author.name}") user_instance.character = character user_instance.save() view = HomePageView(user=user_instance) await ctx.send(f"Welcome {ctx.author.display_name}! Manage your character and inventory here.", view=view) Currently this is the issue that I am encountering this error: Traceback (most recent call last): File "/mnt/m/ZocPy/OblivionAlchemy/OblivionAlchemy/venv/oblivion/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke await ctx.command.invoke(ctx) File "/mnt/m/ZocPy/OblivionAlchemy/OblivionAlchemy/venv/oblivion/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1029, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File … -
How to master React-Django in depth provide me the resources
can someone tell me how and from where i should lean about Django-react integration and how they both work simultaneously in depth i have basic knowledge of them both. i wanna learn Django and react integration in depth but cant get it all -
Quill rich text editor style is not wroking for my django blog
i have wrote a blog using quill editor. and everything was fine.. but after extracting the whole blog in the string form.. i wanted to display the whole blog in their respected pages.. {{% blog.content | safe %}} whole style of quill is not working for my blog... all the style went blank(not-working) and all the content comes at left side.. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.css" integrity="sha512-OQDNdI5rpnZ0BRhhJc+btbbtnxaj+LdQFeh0V9/igiEPDiWE2fG+ZsXl0JEH+bjXKPJ3zcXqNyP4/F/NegVdZg==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <!-- Include stylesheet --> <link href="https://cdn.jsdelivr.net/npm/quill@2.0.0-rc.5/dist/quill.snow.css" rel="stylesheet" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> <script src="https://cdn.jsdelivr.net/npm/quill@2.0.0-rc.5/dist/quill.js"></script> quill style and js are working fine for rich text editor but it is not working for the blog page. -
Why when i try to get an array of data that i send from axios, the list split into multiple values (views.py)
I try to send a list of data from frontend via axios and recieve it in views.py with django . the style of a data that i send : [{ nameDetail: "1", valueDetail: "3" }, { nameDetail: "2", valueDetail: "4" }] and this is when i console.log when i pass the value of details into axios: Array(2) 0 : {nameDetail: 'Size', valueDetail: '2oz'} 1 : {nameDetail: 'Color', valueDetail: 'White'} length : 2 [[Prototype]] : Array(0) Request with axios: const { data } = await axios.post( http://localhost:8000/api/products/product/add/, { name: name, brand: brand, category: category, description: description, badge: badge, price: price, discount: discount, countInStock: countInStock, images: images, details: details, <===== this is the data that i have a problem with }, { headers: { "Content-Type": "multipart/form-data", Authorization: Bearer ${userLogin.token}, }, } ) but when i fetch it in views.py with print(request.data) the data transform: <QueryDict: {'name': ['Electronic'], 'brand': ['ez'], 'category': ['Juices'], 'description': ['azea'], 'badge': ['promos'], 'price': ['22'], 'discount': ['2'], 'countInStock': ['2'], 'details[0][nameDetail]': ['Size'], 'details[0][valueDetail]': ['2oz'], 'details[1][nameDetail]': ['Color'], 'details[1][valueDetail]': ['White'], 'images[]': [<InMemoryUploadedFile: S33ef534d442d4a1d82ce7f52821f391aX (1).webp (image/webp)>]}> why this is happened and how i can pass a list of data to the backend and loop through it. thank you. why this is happened and how … -
Is this possible in Django ORM? I want to query on reverse foreign key relation ship. I need quite a few queries from the database
What I have? I have models as below. class Product(models.Model): title = models.CharField(max_length=500) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) amount = models.DecimalField(decimal_places=2, max_digits=6) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Basically I want to track a price of a product. Each product has one current price and it may have previous price history. I need quite a few things. What I need? I need products with prices but ordered by price. What I did? I did the following thing. queryset = Product.objects.all() queryset = queryset.prefetch_related( Prefetch("price_set", queryset=Price.objects.all()) ) queryset = queryset.order_by("price__amount") Is this correct? Or there is a more efficient way of doing this? What I need? I need to sort products by number of price changes. For example, if product A's price is changed 5 times in last 10 days, and product B's price is changed 6 times in last 10 days, then product B should be first and product A should be second in the queryset? I have no idea how to do this. Please help me out with these two questions. Any help will be greatly appreciated. Thank you. What I tried is as above. -
"ModuleNotFoundError: No module named 'mysite'" error, without `mod_wsgi-express` installed
There is another question for this error, but that questioner's setup is different, I do not have mod_wsgi-express installed. However I still tried the answers there with no resolution. I have installed Django 4.0.4 and Python 3.9.18 in a virtualenv on a Mac running Sonoma 14.4.1. Django is functioning fine generally, the localhost is showing the base template that I have modified. When I run this command in zsh: python manage.py makemigrations I get this error: Traceback (most recent call last): File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/core/management/base.py", line 455, in execute self.check() File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/core/management/base.py", line 487, in check all_issues = checks.run_checks( File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/core/checks/caches.py", line 17, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/Applications/MAMP/htdocs/flashcards/flenv/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/opt/homebrew/Cellar/python@3.9/3.9.18_2/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
Gateway Timeout - The gateway did not receive a timely response from the upstream server or application
I was able to run other Django apps using these same settings but when I installed Django CMS these settings no longer worked. Yes, the other app is running on Python 3.7 and I'm using 3.8 for Django CMS. Below is the error log and other settings. Please any help would be greatly appreciated. Error log: Traceback (most recent call last): File "/home/siteuser/public_html/core/wsgi.py", line 12, in from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' mod_wsgi (pid=13800): Failed to exec Python script file '/home/siteuser/public_html/core/wsgi.py'. mod_wsgi (pid=13800): Exception occurred processing WSGI script '/home/siteuser/public_html/core/wsgi.py'. Traceback (most recent call last): File "/home/siteuser/public_html/core/wsgi.py", line 12, in from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' mod_wsgi (pid=13800): Failed to exec Python script file '/home/siteuser/public_html/core/wsgi.py'. mod_wsgi (pid=13800): Exception occurred processing WSGI script '/home/siteuser/public_html/core/wsgi.py'. Traceback (most recent call last): File "/home/siteuser/public_html/core/wsgi.py", line 12, in from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' Timeout when reading response headers from daemon process 'siteuser.net': /home/siteuser/public_html/core/wsgi.py Timeout when reading response headers from daemon process 'siteuser.net': /home/siteuser/public_html/core/wsgi.py Timeout when reading response headers from daemon process 'siteuser.net': /home/siteuser/public_html/core/wsgi.py, referer: https://siteuser.net/ Timeout when reading response headers from daemon process 'siteuser.net': /home/siteuser/public_html/core/wsgi.py wsgi.py import os from django.core.wsgi import get_wsgi_application sys.path.append('/home/siteuser/public_html/') sys.path.append('/venv/lib/python3.8/site-packages') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') … -
Django forms doesn't save to Admin
I have this Django project where we are supposed to have a page with a form that we are supposed to fill in the info and store it to the admin. HTML (form) <form action="{% url 'add_movies' %}" method="POST" anctype="multipart/form-data"> {% csrf_token %} <!--{{form}}--> <div class="textboxes"> <div class="formbox1"> <div class="text1"> <label for="input-box">Movie Title:</label> </div> <div class="box1"> <input type="text" id="input-box" placeholder="Title here" name="title"> </div> </div> <div class="formbox2"> <div class="text2"> <label for="input-box">Description:</label> </div> <div class="box2"> <textarea rows="10" cols="30" name="description"> </textarea> </div> </div> <div class="formbox3"> <div class="text3"> <p>Image:</p> </div> <div class="box3"> <input type="file" name="image" id="image" name="image"> </div> </div> <div class="formbox4"> <div class="text4"> <p>Category:</p> </div> <div class="box4"> <select name="categoria" id="category" name="category"> <option value="1">ACTION</option> <option value="2">DRAMA</option> <option value="3">CRIME</option> <option value="4">HORROR</option> <option value="5">SCI-FI</option> <option value="6">MYSTERY</option> <option value="7">FAMILY</option> <option value="8">COMEDY</option> <option value="9">FANTASY</option> </select> </div> </div> <div class="formbox5"> <div class="text5"> <p>Classification:</p> </div> <div class="box5"> <select name="classification" id="classification" name="classification"> <option value="1">1/10</option> <option value="2">2/10</option> <option value="3">3/10</option> <option value="4">4/10</option> <option value="5">5/10</option> <option value="6">6/10</option> <option value="7">7/10</option> <option value="8">8/10</option> <option value="9">9/10</option> <option value="10">10/10</option> </select> </div> </div> <div class="formbox6"> <div class="text6"> <p>Release Date:</p> </div> <div class="box6"> <input type="date" name="date" id="date" name="date"> </div> </div> <div class="formbox7"> <div class="text7"> <p>Actors:</p> </div> <div class="box7"> <textarea name="actors" rows="10" cols="30" name="actors"> </textarea> </div> </div> <div class="formbox8"> <div class="text8"> <p>Producer:</p> … -
Dynamic form wizard: 'TypeError: issubclass() arg 1 must be a class'
I'm trying to work with Django Form Wizard to allow an end user to paste certain text (a menu) in a TextArea, and present the parsed data in the 2nd form for verification/adjustments in a dynamic formset (based on the text pasted), before saving everything the database. class MenuAddWizard(LoginRequiredMixin, SessionWizardView): template_name = "menu_add.html" def get_form(self, step=None, data=None, files=None): form = super().get_form(step, data, files) if step is None: step = self.steps.current if step == '1': step_0_data = self.storage.get_step_data('0') parsed_menu = [] for line in step_0_data['0-content'].splitlines(): (Some logic to get to parsed_menu; skipped here) DayMenuFormSet = formset_factory(form=DayMenuForm, min_num=1, extra=0) formset = DayMenuFormSet(initial=parsed_menu) self.form_list[step] = formset form = formset return form def done(self, form_list, **kwargs): # This code isn't reached... pass The error I get: File "C:\venv\python312\Lib\site-packages\formtools\wizard\views.py", line 297, in post form = self.get_form(data=self.request.POST, files=self.request.FILES) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\proj\views.py", line 1547, in get_form form = super().get_form(step, data, files) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\venv\python312\Lib\site-packages\formtools\wizard\views.py", line 424, in get_form if issubclass(form_class, (forms.ModelForm, forms.models.BaseInlineFormSet)): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: issubclass() arg 1 must be a class My problem seems to be related to self.form_list[step] = formset: if I drop this, I no longer get the error message, but I do get the same page again upon submitting the form. No error messages … -
gunicorn.service: Failed at step CHDIR spawning */fresh_env/bin/gunicorn: No such file or directory
gunicorn.service cannot open WorkingDirectory and the gunicorn executable. I think it's about permissions but I don't know how I can solve it. ** sudo systemctl status gunicorn:`** `Apr 12 23:57:08 2818479-qd78506.twc1.net systemd[1]: gunicorn.service: Main process exited, code=exited, status=200/CHDIR` `Apr 12 23:57:08 2818479-qd78506.twc1.net systemd[1]: gunicorn.service: Failed with result 'exit-code'.` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[78132]: gunicorn.service: Changing to the requested working directory failed: No such file or directory` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[78132]: gunicorn.service: Failed at step CHDIR spawning /var/www/web_app/fresh_env/bin/gunicorn: No such file or dir>` `Apr 12 23:57:53 2818479-qd78506.twc1.net systemd[1]: Started gunicorn.service.` ** /etc/systemd/system/gunicorn.service: ** [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target` `[Service]` `User=root` `WorkingDirectory=/var/www/web_app/webapp ` `ExecStart=/var/www/web_app/webapp/fresh_env/bin/gunicorn --access-logfile = --workers 5 --bind unix:/run/gunicorn.sock webapp.wsgi:application` `[Install]` `WantedBy=multi-user.target` I've tried a lot of methods but no one could help me How to solve it? -
How to print out data into a certain html DOM element in Django templates?
I am printing out a list of deeds in template in a todo-list app. It works fine, but I would like block <p>No deeds here yet</p> to be outside of the ul list since it doesn't need to be in a list because it's a logically separate block. Also it gets a margin that I don't want there. How to place that paragraph element outside of the ul list? {% extends "todo_lists/base.html" %} {% block content %} <h2>Deeds of a {{list_title}} list</h2> <ul> {% for deed in deeds %} <li>{{deed.title}}</li> {% empty %} <p>No deeds here yet</p> {% endfor %} </ul> {% endblock content %} -
images from media file wont get displayed in React Native
I want to display the image on my React Native Post.js component but it just showing a white it consume the space of the style I made to the image settings.py STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' models.py from django.db import models from django.conf import settings class Item(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='items') name = models.CharField(max_length=100) description = models.TextField() category = models.CharField(max_length=50, choices=[ ('electronics', 'Electronics'), ('furniture', 'Furniture'), ('clothing', 'Clothing'), ('appliances', 'Appliances'), ('books', 'Books'), ('other', 'Other'), ]) condition = models.CharField(max_length=50, choices=[ ('new', 'New'), ('like_new', 'Like New'), ('used', 'Used'), ]) image = models.ImageField(upload_to='item_images', blank=True, null=True) available = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) reserved = models.BooleanField(default=False) reserved_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='reserved_items', null=True, blank=True) Post.js import React, { useState, useEffect } from "react"; import { View, Text, Image, StyleSheet } from "react-native"; import fetchUserData from "../Reusable Component/FetchUserData"; import { COLORS } from "../constants"; import DynamicPostTime from "../Reusable Component/DynamicPostTime"; export default function Post({ listing }) { const [userData, setuserData] = useState({ firstName: "Loading...", lastName: "Loading...", email: "loading...", }); useEffect(() => { const loadUserData = async () => { setuserData(await fetchUserData()); }; loadUserData(); // console.log(listing.user); }, []); return ( <View style={styles.post}> <View style={styles.header}> <Image source={{ uri: userData.email … -
Can't use selenium with multithread in python - Digital Ocean server
i'm trying to scrap using a multiple threads to optimize. When I run the project on my pc it works nice, but when I deploy it on my Digital Ocean server it doesn't work throwing Timed out receiving message from renderer: 60.000. The server is a classic django server and the scraper runs in django views module after a POST request. My PC: macOS Sonoma 14.2.1 MacBook Air M2 8 gb RAM Digital Ocean Droplet: Ubuntu 23.10 x64 1 AMD vCPU 1 GB RAM 25 GB Disk + 10 GB Relevant code: from pathlib import Path from multiprocessing import Manager from multiprocessing.pool import ThreadPool from .scrapers.scraper_onu_odc import scrap_from_onu_odc from .scrapers.scraper_peps import scrap_from_senaclaft_peps from .scrapers.scraper_bcu import scrap_from_bcu_infractores_cheques from .scrapers.scraper_onu_scs import scrap_from_onu_scs from .scrapers.scraper_ofac import scrap_from_ofac from .scrapers.scraper_google import scrap_from_google from .scrapers.scraper_yahoo import scrap_from_yahoo from .scrapers.scraper_bing import scrap_from_bing from .scrapers.scraper_wikipedia import scrap_from_wikipedia from .scrapers.scraper_fincen import scrap_from_fincen BASE_DIR = Path(__file__).resolve().parent.parent.parent def scrapping_pool(scraper): scraper[0](*scraper[1]) def get_search_results(info, uuid): paths = { 'screenshots_path' : BASE_DIR / f'searcher/screenshots/{uuid}/', 'certificate_path' : str(BASE_DIR / 'searcher/ssl_certificates/bcu.pem') } manager = Manager() results = manager.dict() person_to_search = info['person_to_search_name'] + ' ' + info['person_to_search_surname'] params = (person_to_search, results, paths) scrapers = [ (scrap_from_onu_odc, params), (scrap_from_senaclaft_peps, params), (scrap_from_bcu_infractores_cheques, params), (scrap_from_onu_scs, params), (scrap_from_ofac, params), (scrap_from_fincen, … -
Django upload_to from ImageField not working
I have a model where i want to store a cover image for a publication, this is the code for the field in models.py: cover = models.ImageField(upload_to="covers/") I have in my settings.py: MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media') and in the root of the project I have media/covers/: folder structure the way I'm saving the model is the following: views.py title = request.POST["title"] description = request.POST["description"] initial_bid = int(request.POST["initial_bid"]) category = request.POST["category"] cover = request.POST["cover"] save_auction(title, description, initial_bid, category, cover, User(request.user.id)) def save_auction(title, description, initial_bid, category, cover, author): auction = Auction( title=title, description=description, initial_bid=initial_bid, category=category, status=0, cover=cover, author= author, winner = None ) auction.save() The model gets saved in the database but I don't get the image saved in the desired folder. I tried defining a function like this def user_cover_path(instance, filename): return 'user_{0}/covers/{1}'.format(instance.user.id, filename) cover = models.ImageField(upload_to=user_cover_path) but didn't work -
Django and Sanity
Can Sanity be used as a database backend to Django when used in a dynamic ERP system? How would this work in practive, API calls with JSON data transfer? Would this be a good solution, or is it better to use a relational database like MySql/ Postgres/ SQLite? I am planning on making an ERP system, and have started coding in Django, and would like to know more about the dastabase connection before moving on. -
Error when trying to install wagtail from source
11:36 I'm new to Wagtail and want to learn to contribute. But after many manipulations, when I do setup.py, there appears an error stack with at the end : string or bytes expected. Here is the full message : Traceback (most recent call last): File "/mnt/d_drive/var_docs_complements/open-source-contribs/wagtail/./mysetup.py", line 81, in <module> setup( File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 102, in setup _install_setup_requires(attrs) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 70, in _install_setup_requires dist = MinimalDistribution(attrs) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/__init__.py", line 52, in __init__ super().__init__(filtered) File "/home/ainaf/.local/lib/python3.10/site-packages/setuptools/dist.py", line 297, in __init__ for ep in metadata.entry_points(group='distutils.setup_keywords'): File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 1021, in entry_points return SelectableGroups.load(eps).select(**params) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 459, in load ordered = sorted(eps, key=by_group) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 1018, in <genexpr> eps = itertools.chain.from_iterable( File "/usr/lib/python3.10/importlib/metadata/_itertools.py", line 16, in unique_everseen k = key(element) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 943, in _normalized_name or super()._normalized_name File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 622, in _normalized_name return Prepared.normalize(self.name) File "/usr/lib/python3.10/importlib/metadata/__init__.py", line 871, in normalize return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') File "/usr/lib/python3.10/re.py", line 209, in sub return _compile(pattern, flags).sub(repl, string, count) TypeError: expected string or bytes-like object Thanks. I did some searchs. Also, I tried using github codespace and got very different results. I expect to be able to build and run it from source in my local computer. Thanks. -
Django queryset not filtering correctly in ListView with complex lookup
I'm trying to build a Django application where I have a ListView that displays a list of objects based on complex filtering criteria, but I'm encountering issues with the queryset not filtering correctly. Here's a simplified version of my code: models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) category = models.CharField(max_length=100) stock_quantity = models.IntegerField() class Sale(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) quantity_sold = models.IntegerField() sale_date = models.CharField() views.py from django.views.generic import ListView from .models import Product, Sale class ProductListView(ListView): model = Product template_name = 'product_list.html' def get_queryset(self): queryset = super().get_queryset() return queryset.filter(category='Electronics', stock_quantity__gte=10, sale__sale_date__month=4) product_list.html {% extends 'base.html' %} {% block content %} <h1>Products</h1> <ul> {% for product in object_list %} <li>{{ product.name }}</li> {% endfor %} </ul> {% endblock %} I expect this ProductListView to display a list of products that belong to the 'Electronics' category, have a stock quantity of at least 10, and have had sales in the current month (April). However, when I visit the page, it displays an empty list, even though I know there are products that meet these criteria. I've tried debugging by printing the queryset in the get_queryset method, and it seems to be filtering correctly. I'm … -
create a Q variable in django orm
I want to actuate this query as one Q variable In [55]: Practitioner.objects.filter(query).filter(query10).distinct() Out[55]: <QuerySet [<Practitioner: Mohsenibod, Hadi>]> I used this methods but they do not correct: In [53]: Practitioner.objects.filter(query & query10).distinct() Out[53]: <QuerySet []> In [54]: Practitioner.objects.filter(query , query10).distinct() Out[54]: <QuerySet []> -
Django, htmx delete record and update
So I have a list in a partial Django template. <div class="col"> <div class="row pb-2" id="rowcolor"> <div class="col border-bottom"> pk:{{ color.pk }} / name:{{ color.description|title }} </div> <div class="col-auto"> <button hx-delete="{% url 'delete-color' pk=color.pk %}" hx-target="#rowcolor" hx-swap="outerHTML" class="btn btn-outline-secondary btn-sm float-end" type="button">Delete</button> </div> </div> </div> When deleting the pk149/name3: the pk147 / name1 disappears. When refreshing it is correct. pk:149 is gone. The view looks like this: @require_http_methods(["DELETE"]) def delete_color(request, pk): if request.htmx: Color.objects.get(pk=pk).delete() return HttpResponse("") I have been trying to read the htmx documentation. But I do not understand. Can anyone please point me in the right direction here? -
ModuleNotFoundError: No module named 'apps' - How to make Django find my app?
I'm a Django beginner, also a new SO user, and want to register my app in settings.py. Software version: Python 3.11.9 Django 4.2.11 I created my app (named: Portal) following this guide: startapp with manage.py to create app in another directory Here's the project tree: C:. ├───media │ ├───book-covers │ └───users ├───static │ └───admin │ ├───css │ ├───fonts │ └───js └───project ├───apps │ ├───auth │ ├───portal │ │ ├───media │ │ ├───migrations │ │ │ └───__pycache__ │ │ ├───static │ │ │ └───portal │ │ │ ├───css │ │ │ ├───icons │ │ │ ├───images │ │ │ └───js │ │ ├───templates │ │ │ └───catalog │ │ └───__pycache__ │ └───users ├───plugins │ └───tinymce ├───static └───__pycache__ However, when I register my Portal app, Django raised an error: ModuleNotFoundError: No module named 'apps' apps.py from django.apps import AppConfig class PortalConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'apps.portal' settings.py INSTALLED_APPS = [ '', 'apps.portal', '', ] I know this might be a duplicate question, but still I can't manage to solve this issue. What should I do to make Django find my app? Please be as specific as possible because I'm totally new. Thanks for your time. I've tried steps here: Proper way … -
Problem with getting model instances in specific order
I have a list of passport data of users. I need to get users queryset in the same sequence as their passport data ordered in the list. Here is the list with passport data: lst = ['AA1111111', 'AD2222222', 'AA3333333', 'AA4444444', 'АВ5555555'] I tried to do something like this: empty_queryset = Users.objects.none() for passport_number in lst: user = Users.objects.filter(passport_number__exact=passport_number) empty_queryset |= user I was expecting this: <QuerySet [<Users: AA1111111>, <Users: AD2222222>, <Users: AA3333333>, <Users: AA4444444>, <Users: АВ5555555>]> But it came in chaotic order: <QuerySet [<Users: АВ5555555>, <Users: AA1111111>, <Users: AD2222222>, <Users: AA3333333>, <Users: AA4444444>]> Then I tried this: Users.objects.filter(passport_number__in=[i for i in lst]) But still did not work -
Python Django OSError: [Errno 99] Address not available
I am creating an app with Django Rest Framework and struggling with a weird problem which occures when sending email with Djoser. When I try to reproduce this error on my host machine inside Docker container in production environment I do not have any errors, all email messages are sent succesfully, however when I try to do it on production server under Docker I get OsError, here is the full traceback: Traceback (most recent call last): File "/usr/local/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/contextlib.py", line 81, in inner return func(*args, **kwds) ^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc ^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/rest_framework/mixins.py", line 19, in create self.perform_create(serializer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/djoser/views.py", line 140, in perform_create settings.EMAIL.activation(self.request, context).send(to) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/templated_mail/mail.py", line 78, in send super(BaseEmailMessage, self).send(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/django/core/mail/message.py", line 298, in … -
How do I effectively filter locations in my database without having to loop through it manually?
In my DRF project, I have a model structured like this class ServiceLocation(models.Model): ''' Represents a location where an internet service is offered ''' SERVICE_TYPES = [ ("wifi", 'wifi'), ("fibre", "fibre"), ("p2p/ptmp", "p2p/ptmp") ] id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False, blank=False) description = models.TextField() # Location address = models.CharField(max_length=150, null=False, blank=False) latitude = models.DecimalField(max_digits=18, decimal_places=15) longitude = models.DecimalField(max_digits=18, decimal_places=15) # Service service = models.CharField( max_length=10, choices=SERVICE_TYPES, null=False, blank=False) speed = models.IntegerField() def __str__(self): return f"{self.service} by {self.operator}" and I'm trying to filter this instances of this model with their relative proximity to given coordinate. My view is structured like this class CloseServiceLocations(View): def get(self, request): lat = request.GET.get('lat', 6.748134) lng = request.GET.get('lng', 3.633301) distance = request.GET.get('distance', 10) # Default distance to 10 if not provided # if lat is None or lng is None: # # return JsonResponse({'error': 'Latitude and Longitude are required parameters.'}, status=400) try: lat = float(lat) lng = float(lng) distance = float(distance) except ValueError: return JsonResponse({'error': 'Invalid latitude, longitude, or distance provided.'}, status=400) # Create a Point object representing the provided latitude and longitude user_location = Point(lng, lat, srid=4326) # Calculate the distance in meters (Django's Distance function uses meters) distance_in_meters = distance * 1000 close_service_locations = … -
Filter deep nested related_set in Django
There are two models: class Subject(Model): categories = ManyToManyField(Category, related_name='subjects') class Category(Model): parent = ForeignKey('self', related_name='subcategories') This supposed to be translated into the following rest output: [ { ..., "categories": [ {"subcategories": [{}, {} ... {}]}, {"subcategories": [{}, {} ... {}]} ], }, { ..., "categories": [ {"subcategories": [{}, {} ... {}]}, {"subcategories": [{}, {} ... {}]} ], } ] The problem is to have set of subcategories for each category, subcategories that are in many to many relation with ancestor subject. So far I think that queryset should be something like: Subject.objects.prefetch_related( Prefetch( lookup="categories", queryset=Category.objects.filter(parent__isnull=True) .prefetch_related( Prefetch( lookup="subcategories", queryset=Subquery( Category.objects.filter( parent__pk=OuterRef("pk"), subjects__id__in=OuterRef(OuterRef("pk")), ) ) ) ) .distinct(), ), ) But this gives the error: AttributeError: 'Subquery' object has no attribute '_chain' What is wrong with the queryset. What would be the correct way of doing that? -
How to test external fetch API function with connectionerror exception Django
My code snippet fetches data from an external API. It works fine and I tested the results when I don't have any issues with the connection. However, I'm interested on testing my try except block that handles any connection problem during the function execution. I'm using python 'requests' library and I don't have any complain about it but I feel testing a connection issue will reassure my code does throw the exception. This is the closest StackOverflow answer for python only, I couldn't implement it in my code though. Also, I found another answer that suggested using Httpretty but I don't that's the approach to this question. Does anyone know how to simulate failures for external API data fetching? views.py def fetch_question(request): handler = APIHandler() match request.POST["difficulty"]: case "easy": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple&token=" + handler.token ) case "medium": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=medium&type=multiple&token=" + handler.token ) case "hard": url = ( "https://opentdb.com/api.php?amount=1&category=9&difficulty=hard&type=multiple&token=" + handler.token ) try: response = requests.get(url) except ConnectionError: # Want to test this exception response.raise_for_status() else: return render_question(request, response.json()) test_views.py from django.test import TestCase, Client client = Client() class QuestionTest(TestCase): def test_page_load(self): response = self.client.get("/log/question") self.assertEqual(response["content-type"], "text/html; charset=utf-8") self.assertTemplateUsed(response, "log/question.html") self.assertContains(response, "Choose your question level", status_code=200) def test_fetch_question(self): …