Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to aggregate nested manytomany relationships in django orm
Given the pseudo definitions: class User: name: string class Account: owner: foreignkey(User, related_name="accounts") class Transactions: type: Enum(1,2,3) account: foreignkey(Account, related_name="transactions" value: Int How do I write this query using django ORM? SELECT user.id, type, AVG(value) as type_average FROM user JOIN account ON account.owner = user.id JOIN transactions ON transactions.account = account.id GROUP BY user.id, type -
How to use postgres' ARRAY in django orm
In postgresql, I am able to combine two columns into one into an array like so SELECT id, ARRAY[address,zip] as address_array FROM user Is there a way to do this using django's orm? Why? I want to be able to transform it into a dict mapping like users = dict(User.objects.values("id", "address").all()) Gives me a mapping of: { 1: "Address 1", 2: "Address 2", ... ... } And ultimately I want: { 1: ["Address 1", "Zip 1"], 2: ["Address 2", "Zip 2"], } I am looking for a solution using django's orm, not python. I know I can do this by using python code after looping through the queryset. -
Is there a way to get a user instance in template with async view?
I need to get user instance in my templates using async view {{ request.user }} or {{ request.auser }}/ Of course i can user something like this: async def view(request): user = await request.auser() return render(request, 'template.html', {'user': user} but is there a other way to get it? -
Managing SSO for Multi-Domain and Local Deployments in a Django Application?
I am developing a Django application that will be offered in a marketplace. Each customer will have a unique domain, differentiated at least by prefixes. I have integrated Single Sign-On (SSO) for authentication. I have two specific questions regarding SSO management in this multi-domain setup: Domain Registration with SSO Providers: For each new customer, do I need to manually register each new domain with the SSO provider, or is there a method within Django or the SSO provider's services that can automate this process? Local Deployment SSO Configuration: I plan to allow customers to optionally run the application locally. I've noticed that SSO providers differ in their local testing configurations, with Google using 127.0.0.1 and Microsoft using localhost. How can I accommodate these differences in a seamless manner? Thanks in advance👍 For now I don't have any extra domains, so it is working properly...so just wanted to know about this when I try out. -
Django NoReverseMatch error: Reverse for 'vendor_pannel1' with arguments '('prdbececfaabd',)' not found
I'm getting a NoReverseMatch error in my Django project, and I'm not sure how to fix it. Here's the error message: NoReverseMatch at /vendorpannel/edit_product/prdbececfaabd Reverse for 'vendor_pannel1' with arguments '('prdbececfaabd',)' not found. 1 pattern(s) tried: ['vendorpannel/vendor_pannel1/\\Z'] Here's my code: views.py: @login_required def edit_product(request, pid): product = get_object_or_404(Product, pid=pid) if request.method == "POST": form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user # assuming there is a user field in the Product model new_form.save() form.save_m2m() # Save many-to-many relationships return redirect("vendorpannel:vendor_pannel1",product.pid) else: # Print form errors for debugging print(form.errors) else: form = AddProductForm(instance=product) context = { "form": form, "product": product, } return render(request, "vendorpannel/edit-product.html", context) urls.py: from django.urls import path from vendorpannel import views app_name = 'vendorpannel' urlpatterns = [ path('vendor_pannel1/', views.vendor_pannel1, name='vendor_pannel1'), path('vendor_signup/', views.vendor_signup, name='vendor_signup'), path('login_view/', views.login_view, name='login_view'), path('vendor_shop/', views.vendor_shop, name='vendor_shop'), path('vendor_tickets/', views.vendor_tickets, name='vendor_tickets'), path('vendor_user/', views.vendor_user, name='vendor_user'), path('vendor_settings/', views.vendor_settings, name='vendor_settings'), path('add_product/', views.add_product, name='add_product'), path('edit_product/<str:pid>', views.edit_product, name='edit_product'), ] in html template: <form method="POST" enctype="multipart/form-data" action="{% url 'vendorpannel:edit_product' product.pid %}"> Additional context: 1.I'm using Django 3.2.5 2.I've checked my URL patterns and views, and they seem to be correct 3.I've tried reversing the URL with and without the vendorpannel: namespace prefix Any help would be appreciated! -
How to pull out the most similar words in DRF and Postgres?
My backend server consists of drf and postgres. What I want to do is, if any keyword comes from the client, the result is the B field value in the A table that is most similar to it. Therefore I wanted to use trigram_similar and it worked, but I can't use pg_trgm anymore because the service has to support Korean. How do I resolve this? -
How to run Django test names verbosely without displaying too much logging
I would like to run the tests in my Django project, displaying the test names, but without displaying the logging output of the database migrations. If I do not pass the -v 2 flag, then I don't get to see the test names, which I want to see: $ python manage.py run test Found 1 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). . ---------------------------------------------------------------------- Ran 1 test in 0.053s OK Destroying test database for alias 'default'... However, if I pass the flag -v 2 to increase the verbosity level, then I see both the test names and the logging information from the database migrations: $ python manage.py test -v 2 Found 1 test(s). Creating test database for alias 'default' ('test_projectname')... Operations to perform: Synchronize unmigrated apps: allauth, django_browser_reload, django_extensions, forms, google, hijack, hijack_admin, messages, runserver_nostatic, simple_deploy, staticfiles Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0001_initial... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK # ... cut for brevity System check identified no issues (0 silenced). test_hello (projectname.test_login.LoginTest.test_hello) ... ok ---------------------------------------------------------------------- … -
django.db.utils.DatabaseError: DPY-4027: no configuration directory to search for tnsnames.ora in my dockerized django application
I am trying to connect my django application with an oracle database in vain. I added the TNS_ADMIN environment variable but the problem persists. Here is the content of my tnsnames.ora file: # tnsnames.ora Network Configuration File: C:\app\HP\product\21c\homes\OraDB21Home1\NETWORK\ADMIN\tnsnames.ora # Generated by Oracle configuration tools. XE = (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = xxx)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = XE) ) ) LISTENER_XE = (ADDRESS = (PROTOCOL = TCP)(HOST = xxx)(PORT = 1521)) ORACLR_CONNECTION_DATA = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521)) ) (CONNECT_DATA = (SID = CLRExtProc) (PRESENTATION = RO) ) ) It should be noted that I use SQL developer. My database configuration in django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': os.environ.get("DB_NAME"), 'USER': os.environ.get("DB_USER"), 'HOST': os.environ.get("DB_HOST"), 'POSRT': os.environ.get("DB_PORT"), 'PASSWORD': os.environ.get("DB_PASS") } } docker-compose.yml file: version: '3' services: backend: container_name: bdr-backend build: context: . command: > sh -c "python manage.py makemigrations --noinput && python manage.py migrate --noinput && python manage.py runserver 0.0.0.0:8000" ports: - 8000:8000 volumes: - ./backend:/backend env_file: - .env environment: - DEBUG=1 - DB_HOST=${DB_HOST} - DB_NAME=${DB_NAME} - DB_USER=${DB_USER} - DB_PASS=${DB_PASS} depends_on: - redis redis: image: redis:7.0.5-alpine container_name: redis2 expose: - 6379 I use docker docker desktop … -
django {% url "home" %} name conflict, why? It shouldn't
In a new django project I came a cross a conflict of names in the url when intheory shouldn't be. the path of the two urls are different, but the name the same. It is easy to fix, changing the name, but I would like to understand why there is conflict when to me it shouldn't. The problme is in the {% url 'home' %}. <a class="navbar-brand" href="{% url "home" %}">CRM</a> urls.py of the project: urlpatterns = [ path('admin/', admin.site.urls), path('',views.home, name='home'), <---------'localhost:8000/' path('CRMapp/', include('CRMapp.urls')), ] urls.py of app: urlpatterns = [ path('', views.home, name='home'), <---------'localhost:8000/CRMapp/' path('hello/', views.hello, name='hello') ] views.py of app: (in theory triger when localhost:8000/CRMapp/ def home(request: HttpRequest): return render(request,'home.html',{}) views.py of project deliver when localhost:8000/: def home(request: HttpRequest): # return HttpResponse('home') return render(request,'home.html',{}) html of the nav: Both {% url "home" %} deliver localhost:8000/CRMapp/, when they should deliver localhost:8000/ <a class="navbar-brand" href="{% url "home" %}">CRM</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="{% url "home" %}">Home</a> here the order list of routes that django-extentions show: / djangoCRM.views.home home /CRMapp/ CRMapp.views.home home /CRMapp/hello/ CRMapp.views.hello hello /admin/ django.contrib.admin.sites.index … -
How can i "add" additional Data (Classification-Codes) to an existing Field
I have build a model which should representate our Products at work. Our products are different sorts of luminaires. Some of these with different variations like different colour-temperature, different housing-colour, different power, sensors or dimmable. at the moment my model looks (a little shortend) like this class ProductID(models.Model): product_id = models.CharField(max_length=100, unique=True) base_model = models.BooleanField(default=True) active = models.BooleanField(default=True, choices=CHOICES) possible_as_option = models.BooleanField(default=False, choices=CHOICES) product_variant_data = models.ForeignKey('ProductVariantData', on_delete=models.PROTECT) ... class ProductVariantData(models.Model): short_text = models.CharField(max_length=300, null=True, blank=True) packaging_unit = models.IntegerField(validators=[MinValueValidator(1)]) guarantee = models.IntegerField() product = models.ForeignKey('Product', null=True, on_delete=models.PROTECT) ... class Product(models.Model): enec = models.BooleanField(default=False) ce = models.BooleanField(default=True) min_ambient_temperature = models.IntegerField() max_ambient_temperature = models.IntegerField() ip_code = models.ForeignKey(IPCode, on_delete=models.PROTECT) ik_code = models.ForeignKey(IKCode, on_delete=models.PROTECT) dimensions = models.ForeignKey(Dimensions) cutout_dimensions = models.ForeignKey(CutoutDimensions, null=True) product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT) .... class LEDData(models.Model): led_changeable = models.BooleanField(default=True) average_lifespan = models.IntegerField(null=True, blank=True) dimmable = models.BooleanField(default=False) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class LEDData(models.Model): average_lifespan = models.IntegerField() dimmable = models.BooleanField(default=True) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class Luminaire(models.Model): product = models.OneToOneField(Product, primary_key=True) control_gear_included = models.BooleanField(default=True) external_control_gear = models.BooleanField(default=True) control_gear_changeable = models.BooleanField(default=True) control_gears = models.ManyToManyField('ControlGear', through='LuminaireControlGearDetails') led_data = models.ForeignKey(LEDData) lighting_technology = models.CharField(max_length=15, choices=LightingTechnology, default=LightingTechnology.LED) ... class … -
Nginx not loading django static files
I'm having difficulties making a minimal nginx+gunicorn+django static files work properly, here are further details: Here's the nginx site config: server { listen 80; server_name SERVER_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias PATH/TO/PROJECT/static/; } location / { include proxy_params; proxy_pass http://SERVER_IP:8000; } } I run django with gunicorn using gunicorn -c gunicorn.conf.py WSGI_FILE using this config: command = 'PATH/TO/PROJECT/venv/bin/gunicorn' pythonpath = 'PATH/TO/PROJECT' bind = 'SERVER_IP:8000' workers = 3 Also to note I've added proper STATIC variables to django settings.py and did collectstatic. Seems like to be nginx config problem but couldn't find anything online yet. I've also tried giving group access to nginx(user www-data) for the static files. But I still believe it could be problem of similar type. -
Django View: `DoesNotExist` error when trying to edit a product
I'm trying to create an edit product feature in my Django application, but I'm running into a DoesNotExist error when I try to access the edit product page. Here's my view function: @login_required def edit_product(request, pid): product = Product.objects.get(pid=pid) if request.method == "POST": form = AddProductForm(request.POST, request.FILES, instance=product) if form.is_valid(): new_product = form.save(commit=False) new_product.user = request.user # assuming there is a user field in the Product model new_product.save() form.save_m2m() # Save many-to-many relationships return redirect("vendorpannel:dashboard") else: # Print form errors for debugging print(form.errors) else: form = AddProductForm(instance=product) context = { "form": form, "product": product, } return render(request, "vendorpannel/edit-product.html", context) When I try to access the edit product page, I get the following error: DoesNotExist at /vendorpannel/edit_product/11 Product matching query does not exist. I've checked my database, and the product with the specified pid exists. I'm not sure what's causing this error. Can anyone help me identify the issue and suggest a solution? if you need my template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Edit Product</title> <!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <style> body { padding-top: 50px; } .container { max-width: 600px; margin: auto; } .form-group label { font-weight: bold; } .form-actions { text-align: right; … -
Django Summernote image URL issue
I'm using Summernote in my Django project. The editor works fine. The image loads in the editor and appears in the media folder, but after saving the image disappears and an empty img tag appears. I made a few attempts looking for solutions but without success. models.py; from django.db import models from django.utils.translation import gettext_lazy as _ from unidecode import unidecode from django_summernote.fields import SummernoteTextField from django.urls import reverse from articles.models.category_model import ArticleCategory from django.utils.text import slugify import re from PIL import Image import os from django.conf import settings from meta.models import ModelMeta from datetime import datetime class Article(ModelMeta, models.Model): title = models.CharField(_('Title'), max_length=255) category = models.ForeignKey(ArticleCategory, verbose_name=_('Category'), on_delete=models.CASCADE, related_name='articles') slug = models.SlugField(_('Slug'), max_length=255, unique=True, blank=True) featured_image = models.ImageField(_('Featured Image'), upload_to='articles/', blank=True, null=True) meta_description = models.CharField(_('Meta Description'), max_length=160, blank=True) content = SummernoteTextField(_('Content')) created_at = models.DateTimeField(_('Created At'), auto_now_add=True) updated_at = models.DateTimeField(_('Updated At'), auto_now=True) created_by = models.ForeignKey('users.CustomUser', verbose_name=_('Created By'), on_delete=models.CASCADE, related_name='articles') hashtags = models.ManyToManyField('Hashtag', related_name='hashtag_articles', blank=True) is_published = models.BooleanField(_('Is Published'), default=True) publish_date = models.DateTimeField(_('Publish Date'), default=datetime.now) is_featured = models.BooleanField(_('Is Featured'), default=False) is_trending = models.BooleanField(_('Is Trending'), default=False) is_sponsored = models.BooleanField(_('Is Sponsored'), default=False) _metadata = { 'title': 'title', 'description': 'meta_description', 'image': 'image_url', } _schema = { 'type': 'Article', 'name': 'title', 'description': 'meta_description', 'image': 'image_url', … -
is there is anyone who can help me fix this django error?
im getting this error while running python manage.py runserver in terminal, pls help to fix this {C:\Users\sumit\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'C:\Users\sumit\PycharmProjects\pythonProject1\manage.py': [Errno 2] No such file or directory(.venv) PS C:\Users\sumit\PycharmProjects\pythonProject1> cd projectintern(.venv) PS C:\Users\sumit\PycharmProjects\pythonProject1\projectintern> python manage.py makemigrationsTraceback (most recent call last):File "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\manage.py", line 22, in <module>main()File "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\manage.py", line 18, in mainexecute_from_command_line(sys.argv)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_lineutility.execute()File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management_init_.py", line 436, in executeself.fetch_command(subcommand).run_from_argv(self.argv)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argvself.execute(*args, **cmd_options)File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 454, in executeself.check()File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\management\base.py", line 486, in checkall_issues = checks.run_checks(^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checksnew_errors = check(app_configs=app_configs, databases=databases)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\urls.py", line 14, in check_url_configreturn check_resolver(resolver)^^^^^^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\core\checks\urls.py", line 24, in check_resolverreturn check_method()^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 519, in checkfor pattern in self.url_patterns:^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\utils\functional.py", line 47, in getres = instance.dict[self.name] = self.func(instance)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 738, in url_patternspatterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\utils\functional.py", line 47, in getres = instance.dict[self.name] = self.func(instance)^^^^^^^^^^^^^^^^^^^File "C:\Users\sumit\PycharmProjects\pythonProject1.venv\Lib\site-packages\django\urls\resolvers.py", line 731, in urlconf_modulereturn importlib._bootstrap>", line 488, in _call_with_frames_removedFile "C:\Users\sumit\PycharmProjects\pythonProject1\projectintern\myapp\urls.py", line 5, in <module>path('', views.index())^^^^^^^^^^^^^TypeError: index() missing 1 required positional argument: 'render'} solution of this error -
How to Create a New Database and Run Migrations Dynamically in Django?
I have an application where I need to create a new database and run migrations to create tables. Here is my current implementation: def create_database(db_name): with connection.cursor() as cursor: try: cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name}") return True except Exception as e: print(f"Error creating database {db_name}: {str(e)}") return False The code above successfully creates the database. def run_migrations(db_name, app_names): new_db_settings = copy.deepcopy(settings.DATABASES['default']) new_db_settings.update({ 'NAME': db_name, }) settings.DATABASES['default'] = new_db_settings try: with TemporaryOverrideSettings({'default': new_db_settings}): call_command('makemigrations', app_names) call_command('migrate', app_names, database=db_name) except Exception as e: # Handle potential errors gracefully print(f"Error encountered while checking migrations: {e}") The run_migrations function is intended to run the migrations. The makemigrations command runs successfully, but the migrate command does not work for the new database. My requirement is to always create the database and run migrations on each request. However, since there might not be new changes, the migrations might not need to run every time. Issue: The migrate command does not work as expected for the new database after running makemigrations. Questions: How can I ensure that the migrate command runs correctly on the new database? Is there a better approach to handle dynamic database creation and migrations in Django? Any help or suggestions would be … -
Get "RuntimeError: Event loop is closed" while running pytest in django channels
I wrote a test for my websocket connection. Here is my pytest code. import pytest from channels.testing import WebsocketCommunicator from django.contrib.auth import get_user_model from rest_framework_simplejwt.tokens import AccessToken from dashboard.token_auth import TokenAuthMiddleware from channels.routing import URLRouter from django.urls import path from dashboard.consumers import DashboardConusmer UserModel = get_user_model() @pytest.fixture @pytest.mark.django_db def access_token(): user = UserModel.objects.create_user(email='hello@hello.com', password='hello@hello1') access = AccessToken.for_user(user) return str(access) @pytest.fixture(autouse=True) @pytest.mark.django_db def set_channel_layer(settings): settings.CHANNEL_LAYERS = {"default": {"BACKEND": "channels.layers.InMemoryChannelLayer"}} @pytest.mark.django_db @pytest.mark.asyncio class TestDashboard: pytestmark = pytest.mark.django_db async def test_connection(self, access_token): application = TokenAuthMiddleware( URLRouter([path("ws/dashboard/", DashboardConusmer.as_asgi())])) url = f"ws/dashboard/?token={access_token}" communicator = WebsocketCommunicator(application, url) connected, _ = await communicator.connect() assert connected await communicator.disconnect() It shows RuntimeError: Event loop is closed Error code is Task was destroyed but it is pending! task: <Task cancelling name='Task-2' coro=<ProtocolTypeRouter.__call__() running at /usr/local/lib/python3.10/site-packages/channels/routing.py:62> wait_for=<Future finished result=None>> Exception ignored in: <coroutine object ProtocolTypeRouter.__call__ at 0x7f139df44f20> Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/channels/routing.py", line 62, in __call__ File "/home/app/web/dashboard/token_auth.py", line 37, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/routing.py", line 132, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/consumer.py", line 94, in app File "/usr/local/lib/python3.10/site-packages/channels/consumer.py", line 58, in __call__ File "/usr/local/lib/python3.10/site-packages/channels/utils.py", line 55, in await_many_dispatch File "/usr/local/lib/python3.10/asyncio/base_events.py", line 753, in call_soon File "/usr/local/lib/python3.10/asyncio/base_events.py", line 515, in _check_closed RuntimeError: Event loop is closed Task was destroyed but it is … -
is there a way in django to select data from tables when one is a backwards link?
I've got tables as shown below. I know I can do the following: value = Zero.objects.select_related('one').select_related('two') three = value.two.three_set.all() But that results with the data spread across two queries. is there a way to combine all that into one statement? I could probably do it with raw sql but I'd rather not. -
I am having an issue uploading an image with Django
I am currently working my way through a django project and am having trouble working with MEDIA and uploading an graph image. Inside settings.py, I have added the below code. MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media')` HomePage.html: <img src="{{ MEDIA_URL }}image.png" alt="Uploaded Image" style="max-width: 100%; height: auto;"> HomePage->urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Relative Path from the html file to the image: media/graph/upload/image.png I get the error Not Found: /graph/upload/image.png. Main Project --App ----settings.py --HomePage ----HomePage.html ----urls.py --media ----graph ------upload --------image.png Thank you for all your help! Let me know if you need anymore of the code, I just didn't want to make this super long if this is a simple error. I've also tried hardcoding the path to the directory and that did not work either so I think I am misunderstanding something with Django. -
dividing aggregate expressions (Count / Count) results to zoro, no matter what
here's a code snippet of the problem #multiplication works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) * Count('orders', distinct=True) ) * 100 , ) #addition works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) + Count('orders', distinct=True) ) * 100 , ) #subtraction works fine drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) - Count('orders', distinct=True) ) * 100 , ) #diving not working (returns 0) drivers.annotate( completed_orders_percentage=( Count('orders', filter=Q(orders__rejected=False), distinct=True) / Count('orders', distinct=True) ) * 100 , ) i couldnt find anything useful in the docs, i thought that it might be due to type of the return so i tried to wrappe it in ExeprisionWrapper with output_field=FloatField() but still the same! -
Celery Worker Fails with AttributeError: 'NoneType' object has no attribute 'Redis' in Django Project
I'm working on a Django project where I need to send periodic emails using Celery. My environment is set up on Ubuntu, and I have Redis installed both on my system and within my virtual environment. Command: celery -A main worker -l info However, when I try to run the Celery worker, I encounter the following error: Traceback (most recent call last): File "/home/osama/Projects/send_email_with_celery/.venv/bin/celery", line 8, in <module> sys.exit(main()) ^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) ^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/celery.py", line 236, in main return celery(auto_envvar_prefix="CELERY") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/click/decorators.py", line 33, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/base.py", line 135, in caller return f(ctx, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/bin/worker.py", line 348, in worker worker = app.Worker( ^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/worker/worker.py", line 98, in __init__ self.setup_instance(**self.prepare_args(**kwargs)) File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/worker/worker.py", line 119, in setup_instance self._conninfo = self.app.connection_for_read() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/app/base.py", line 821, in connection_for_read return self._connection(url or self.conf.broker_read_url, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/osama/Projects/send_email_with_celery/.venv/lib/python3.11/site-packages/celery/app/base.py", line … -
Django Nested Serializers witj Foreign Field
I am trying to post this json request through postman { "name":"Someones order", "date_due": "2024-06-23T15:52:59Z", "customer":3, "orderItem":[{ "item":1, "count":1 }] } I have implemented my models like so. class Item(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=6, decimal_places=2) bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='items') def __str__(self): return f'{self.name}' class Order(models.Model): name = models.CharField(max_length=255) bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='orders') customer = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='orders') date_created= models.DateTimeField(auto_now_add=True) date_due = models.DateTimeField() date_updated = models.DateTimeField(auto_now=True) #order_item = models.OneToOneField(OrderItem, on_delete=models.CASCADE,related_name='item_orderitems') def __str__(self): return f'{self.name}' class OrderItem(models.Model): bakery = models.ForeignKey(Bakery,on_delete=models.CASCADE,related_name='order_items') count = models.IntegerField() item = models.ForeignKey(Item, on_delete=models.CASCADE,related_name='item_orderitems') order = models.OneToOneField(Order, on_delete=models.CASCADE,related_name='orderitems') def __str__(self): return f'{self.name}' Serializer is implemented as class OrderItemCreateSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['item','count'] class OrderCreateSerializer(serializers.ModelSerializer): orderItem=OrderItemCreateSerializer(many=True) class Meta: model = Order fields = ("name","date_due","customer","orderItem") def create(self, validated_data): print("create") print(validated_data) itemid=validated_data.pop("orderItem") print(itemid) bakery=self.context['request'].user.bakery customer=validated_data.pop("customer") print(customer) print("validated_data") print(validated_data) order=Order.objects.create(bakery=bakery,customer=customer,**validated_data) print("create 4") for items in itemid: print("create 5") OrderItem.objects.create(bakery=bakery,order=order,**items) print("create 6") print("returning") return order When I make the post request i get Got AttributeError when attempting to get a value for field orderItem on serializer OrderCreateSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Order instance. Original exception text was: 'Order' object has no attribute 'orderItem'. I understand that Order model do not … -
Django view to redirect to same url with different parameter?
I've got django app with a views (urls), that show different lists for different locations: path('ItemList/<int:locationId>/', views.ItemList, name="ItemList"), path('SomethingList/<int:locationId>/', views.SomethingList, name="SomethingList"), and then in a template I've got a menu, when I can switch between locations, ie. being in -- ItemList/2/ I can switch to location with different Id or being in SomethingList/4/ I can switch to location with different Id To switch location, I've got a method (which obviusly is incorrect): def setLocation (request, newLocationId): return redirect(request.META['HTTP_REFERER'], locationId = newLocationId) but how can I do it, to get the current location url like: ItemList/2/ and redirect it to ItemList/4/ (ie. to different id?) -
How can I link user input data from one field in a Django model, to another field in the same model?
Apologies if this is a stupid question or if my terminology is not quite right. I'm very new to Django and programming! I'm looking to build a quoting tool for my website, which will basically be a form that clients fill in, which will create an instance of a "quote" model, and the actual quote value will be automatically calculated and stored as part of the model instance, based on the data input by the user. I've looked around online but I'm really struggling to find a simple explanation of how a model field can be validated and/or automatically calculated and stored, based on data inputs from earlier fields. My first hurdle is below: class Quote(models.Model): total_plots = models.IntegerField(default=1) total_types = models.IntegerField(default=(total_plots),validators=[MinValueValidator(1),MaxValueValidator(total_plots)]) So what I'm trying and failing to do here is initially set the default value for total_types, to the same as what the user has input for total_plots. I want to then allow the user to change the value of total_types, but it can't be greater than what they have entered for total_plots, so I need to grab the value they enter for total_plots and use it to restrict what they are able to enter for total_types. The … -
Why raising serializers.ValidationError() is causing UnicodeDecodeError?
I am creating a django rest API(with a ImageField) and it is working fine. But I want to add some validations to some CharFields fields. I noticed some unicodeDecoderError while added a validator or simply raising a validation error. Spent quite a lot of time trying to solve it. Any help will be appreciated. Here is my serializers.py file from rest_framework import serializers from .models import * def validate_phone(phone_number: str): print(phone_number) if not (phone_number.startswith(("6", "7", "8", "9"))): raise serializers.ValidationError( {"phone": "phone number must startwith digits from 6-9 !!!"}) if not phone_number.isnumeric(): raise serializers.ValidationError( {"phone": "phone number should contain digits only !!!"}) if len(phone_number) != 10: raise serializers.ValidationError( {"phone": "phone number must contain only 10 digits !!!"}) class StudentSerializer(serializers.ModelSerializer): start_date = serializers.DateField(format='%d %B %Y') phone = serializers.CharField(max_length=10, validators=[validate_phone]) class Meta: model = Student fields = '__all__' Raising a validation error is resulting a UnicodeDecoderError. Working fine otherwise. This is my models.py file from django.db import models class Student(models.Model): ... phone = models.CharField(max_length=10) ... start_date = models.DateField() profile_picture = models.ImageField(upload_to='profile/', blank=True) ... I am sending the data using javascript fetch API with FormData() which handles the file formatting and encoding. Here is the javascript file: const form = document.querySelector("form"); form.addEventListener("submit", (e) => … -
How to show/hide a bootstrap spinner on a button WITHOUT jQuery?
How can I show spinner on a button after clicking, disabled the button after clicking? I am using Django templates. I do not want to use jQuery at all. Looked at many other posts, most of them depend on jQuery. <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/bootstrap.bundle.min.js' %}"></script> Template submit button <!-- Submit button --> <div class="d-grid gap-2 col-6 mx-auto"> <input type="submit" value="Sign in" class="btn btn-primary btn-block mb-4" /> </div> Bootstrap example <button class="btn" type="button"> <span class="spinner-border spinner-border-sm" role="status"></span> Loading... </button>