Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
error with if else in html in django application
Good afternoon, i have django application where i have issue on main page there is header in base html, there is 1 button, but with 2 different values as link {% if roleworker %} <li><a href="/addservice/">Add</a></li> {% else %} <li><a href="/addpage/">Add</a></li> {% endif %} roleworker is value in database, here is model for it class Role(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='Пользователь') roleworker = models.BooleanField(default=False) when user opens index.html it equals True, when user opens indexworker.html(here is posts from worker) it equal false, i checked that functionality of value in db for user, it works good when user open some other page it must remember his value, for that there is that django model this is function that check value of roleworker for user def rolecheck(request, render): user = request.user role = Role.objects.get(user=user) roleworker = role.roleworker if roleworker == True: print('True') elif roleworker == False: print('False') return render(request, 'base.html', {'roleworker': roleworker}) but on html there is always "{% if roleworker %}" (it means == True) even when in django admin it equal False {% if roleworker %} <li><a href="/addservice/">Добавить (услуга)</a></li> {% else %} <li><a href="/addpage/">Добавить (статья)</a></li> {% endif %} Maybe someone know how to fix it, i will be very grateful … -
Python django paginator not displaying items correctly
I developed a simple web app. I have added the paginate_by property to the view. I'm able to show only the first 10 records retrived from the database. If i change the paginate_by property to 20 I always see 10 records in the list page of my models. Note that the number or records change in the top bottom left of the screenshot but I always see 10 records. Here the code: views.py: class DeviceList(LoginRequiredMixin, FilterView): model = models.Device filterset_class = filters.DeviceFilter context_object_name = "devices" paginate_by = 10 template_name = "device_list.html" def get_context_data(self, **kwargs): context = super(DeviceList, self).get_context_data(**kwargs) context["hist_devices"] = (models.Device.objects.filter(history_type=0)).count() context["active_devices"] = ( models.Device.objects.filter(history_type=1) ).count() context["available_devices"] = (models.Device.objects.filter(status=0)).count() context["unavailable_devices"] = ( models.Device.objects.filter(status=1) ).count() return context device_list.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% load pagination_tags %} <link rel="stylesheet" href="/static/css/style.css"> {% block title %} Device list {% endblock %} {% block content %} <h2>Device list</h2> <div class="row row-no-gutters"> <div class="col-md-6"> <div class="accordion accordion" id="accordionFlushExample"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne"> <h5>Filters</h5> </button> </h2> <div id="flush-collapseOne" class="accordion-collapse collapse" data-bs-parent="#accordionFlushExample"> <div class="accordion-body"> <form method="get"> {{ filter.form.as_p }} <button class="btn btn-primary" type="submit">Search</button> </form> </div> </div> </div> </div> </div> <div class="col-md-6"> <div class="card card-body"> <h5><i class="bi … -
Change record title in a StackedInline in Django
I am trying to either change or remove the title for each record in an inline, but have not been able to find a way to do it in the docs or by override get_formset. Specifically, I want to change or remove the title highlighted in the attached image. Any ideas how to do it please? Preferably without overriding CSS etc. -
drop box small files upload slowly
I have a free dropbox subscription and use it in conjunction with django. def upload_image(request): if request.method == 'POST': dbx = dropbox.Dropbox('') file_from = request.FILES['file'] file_to = '/chat/' + file_from.name # Upload the file dbx.files_upload(file_from.read(), file_to) # Create a shared link for the uploaded file shared_link_metadata = dbx.sharing_create_shared_link_with_settings(file_to) url = shared_link_metadata.url # Replace ?dl=0 with ?raw=1 in the URL url = url.replace('&dl=0', '&raw=1') # Create a new Image instance with the shared link new_image = Image(image_url=url) new_image.save() return HttpResponse("Image uploaded and saved successfully!") else: return HttpResponse("Method not allowed", status=405) I have read a lot that uploading large files can be slow however my current upload speed for a file for example ~2MB takes ~3 seconds. From what I've learnt dropbox has no speed settings and tries to upload as fast as possible. However maybe I am still missing something in the app settings? -
Django async acount takes forever to execute
Consider a django rest framework application which calls an async function like; class SomeViewSet(ListUpdateViewSet): @action( methods=["GET"], url_path=r"count-async", detail=False ) def get_count_async(self, request, *args, **kwargs): print('starting') t = asyncio.run(self.aget_count_async(request, *args, **kwargs)) print('ending') return Response(data={ }) async def aget_count_async(self, request, *args, **kwargs): print('before getting count') my_count = await User.objects.filter(id="1").acount() print('after getting count') return my_count However whenever I run the endpoint I notice the logs show "before getting count", yet minutes later it is still running and no "after getting count" is being shown. How can I debug this and what could possibly be the cause? -
Optimizing Complex Django ORM Queries Across Polymorphic Models with High Volume Data
I'm working on a Django 3.2 project with a PostgreSQL backend that involves a complex data model with polymorphic relationships managed by django-polymorphic. The project serves as a backend for a web application that displays a large set of interconnected data points to the users, requiring highly optimized queries for performance. Despite leveraging Django's ORM capabilities and PostgreSQL's indexing features, I'm encountering significant challenges in optimizing the query performance for one of the core functionalities of the application. Models Overview: BaseItem (polymorphic parent model) SubItem1, SubItem2, SubItem3 (child models of BaseItem, each with unique fields and large datasets) RelatedModel (has a ForeignKey to BaseItem) The application features a complex filtering interface that allows users to dynamically filter BaseItem records based on fields from SubItem1, SubItem2, SubItem3, and RelatedModel. The challenge arises when applying filters across these models, as the ORM generates suboptimal queries that result in full table scans or inefficient use of indexes. The Specific Challenge: Efficiently Filter Across Polymorphic Models: How can we structure queries or models in Django to efficiently filter BaseItem records by criteria that span across the polymorphic child models and related models? Avoid Full Table Scans: Given the volume of data, full table scans … -
I'm having trouble sending emails on Django using SMTP. Even after trying various tutorials and checking the documentation, nothing seems to work
Here are the possible things that may cause my problem. using django's live server instead of a domain. I know in gmail you can't no longer use less secure apps. I enabled two factor authentication and created an app with a unique password. This is what i used for the EMAIL_HOST_PASSWORD. For gmail I used this in my settings.py file DEBUG = True EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = "my email address" EMAIL_HOST_PASSWORD = "my app password" DEFAULT_FROM_EMAIL = "my email address" Then tried outlook with the same config except for EMAIL_HOST = "smtp-mail.outlook.com" EMAIL_HOST_USER = "outlook email address" EMAIL_HOST_PASSWORD = "outlook email address password" DEFAULT_FROM_EMAIL = "outlook email address" i never had a single success with any of them as I couldn't send out a single mail. Checked my spam folder, inbox folder and all mail folder of the mail recipient. -
Django 1.7 workaround to use drf-spectacular
I am trying to use drf-spectacular for annotating my existing python api, but i am currently using django-1.7 in my application, and this tool has a dependency of django-2.2 what can be done as quick solution or any suggetion?? -
After renaming my table in Django, items from the old table were not moved or deleted
My old table called Quiz was renamed to CarQuizz, the problem is that all items in the table with the old name were neither moved to the new name nor were they deleted. Here is the following log from my application: Log Models.py from django.db import models class CarQuizz(models.Model): name = models.CharField(max_length=255) url_image = models.URLField(default=None) name_quiz = models.CharField(max_length=255,default='Cars') def __str__(self): return f'{self.name} foi adicionado ao quizz' Urls.py from django.urls import path from . import views urlpatterns = [ path('quiz/solo', views.Quiz, name='quiz'), ] I've already restarted the Django server and also deleted the record of migrations made, but nothing has resolved it. Except when I rename it back to Quiz, the program works normally. -
Dynamic data in single send | Twilio SendGrid
I am creating a monthly digest for release logs with wagtail CMS as backend, essentially whenever a new post gets created in cms, it will trigger signals.py which inturn should create a mail in single send. Now the problem is i want to pass the data to dynamic templates. As per my knowledge marketing/single send api's doesn't support dynamic data api-docs dynamic_template_data = { "somevariable" :"John", } data = { "name": name, "send_to": {"list_ids": [list_id]}, "email_config": { "suppression_group_id": unsubscribe_suppression_group, "sender_id": sender_id, # "design_id": "d-14a0041239f34f5688c5f192c869b766", "design_id" : "758d5b87-8b6f-49d7-ba1f-4dad111b5197", "dynamic_template_data": dynamic_template_data, "editor": "code", } } return self.sgClient.client.marketing.singlesends.post(request_body=data) <!DOCTYPE html> <html> <head> <title>Your Order Details</title> </head> <body> <p>Hello {{somevariable}},</p> </body> </html> This is the payload passing, initially i tried to pass the dynamic template id which isn't supported, so i passed the design id. Also i used handlebars for html template Is there any other way to pass dynamic data for singlesend api? -
django custom datetime format not working with form fields
I'm working on a Django project where I wanted to add a date format for local usage. As per the documentation, I have updated the settings to use local date time format : Link Settings are as below: DATE_INPUT_FORMATS = [ "%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%b %d %Y", "%b %d, %Y", "%d %b %Y", "%d %b, %Y", "%B %d %Y", "%B %d, %Y", "%d %B %Y", "%d %B, %Y", '%d-%m-%Y', '%d/%m/%Y' ] DATETIME_INPUT_FORMATS = [ "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %H:%M:%S.%f", "%m/%d/%Y %H:%M", "%m/%d/%y %H:%M:%S", "%m/%d/%y %H:%M:%S.%f", "%m/%d/%y %H:%M", '%d-%m-%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S' ] But for the form fields, it's still using the default date time formats and not taking the date time formats added in the settings file > <project>/env/lib/python3.9/site-packages/django/forms/fields.py(384)to_python() -> for format in self.input_formats: (Pdb) self.input_formats ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y'] (Pdb) self <django.forms.fields.DateTimeField object at 0x128049c10> (Pdb) value '19-03-2024 17:25:17' (Pdb) Looking forward to suggestions or feedback. -
How to test exception handling in Django REST Framework action method when unable to trigger an Exception during testing?
I'm working on a Django REST Framework (DRF) viewset that includes exception handling to deal with unexpected errors. The viewset has an action method that retrieves pricing information for servers from a third-party API. Here's a simplified version of the code: from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import status from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt import logging logger = logging.getLogger(__name__) class MyViewSet(viewsets.ViewSet): @action(detail=False, methods=["get"], url_path="pricing", authentication_classes=[]) @method_decorator(csrf_exempt) # For testing purposes only def pricing(self, request, pk=None): """ List all pricing or a specific server """ try: server_type = request.query_params.get("server_type") location = request.query_params.get("location") # Case 1: returns the pricing list if not server_type or not location: pricing = self.hapi.pricing() return Response(pricing, status=status.HTTP_200_OK) # Case 2: returns the pricing of the provided server info prices = self.hapi.calculate_price(server_type, location) return Response(prices, status=status.HTTP_200_OK) except Exception as error: logger.critical(f"Error fetching server pricing: {error}", exc_info=True) return Response({"message": "Error fetching server pricing", "error": str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) I'm trying to test the except Exception part of the code, but I'm having trouble triggering the exception during testing. Since the code path leading to the exception is challenging to reproduce in a controlled testing environment, I'm not sure how to effectively test the exception … -
Status code was: 1 Service /usr/bin/chromedriver unexpectedly exited
i was using selenium , chrmoedriver to make screen short of the provided url in my django app. def take_url_screenshot(url): # Ensure the "screenshot" folder exists or create it if not available screenshot_folder = "screenshot" if not os.path.exists(f"{settings.MEDIA_ROOT}/{screenshot_folder}"): print(f"{settings.MEDIA_ROOT}/{screenshot_folder}") os.makedirs(f"{settings.MEDIA_ROOT}/{screenshot_folder}") # Create Chrome options chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--window-size=1920,1080") chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--ignore-ssl-errors=yes") chrome_options.add_argument("--ignore-certificate-errors") # Create an instance of Chrome webdriver with the headless option service = ChromiumService(executable_path=r"/usr/bin/chromedriver") driver = webdriver.ChromiumEdge(service=service, options=chrome_options) driver.get(url) time.sleep(5) # Take a screenshot and save it in the "screenshot" folder image_name = re.sub(r"[^\w\s]", "", url) screenshot_path = os.path.join( f"{settings.MEDIA_ROOT}/{screenshot_folder}/{image_name}.png" ) driver.save_screenshot(screenshot_path) # Close the browser driver.quit() return f"{screenshot_folder}/{image_name}.png" this is working fine in localhost, but when i deployed my django application this make exception : Service /usr/bin/chromedriver unexpectedly exited. Status code was: 1 version details: os : ubuntu 22.04 chromium-browser : 1:85.0.4183.83-0ubuntu0.20.04.3 chromedriver: ChromeDriver 122.0.6261.128 selenium: 4.12.0 i have checked ./chromedriver which is returning: Starting ChromeDriver 122.0.6261.128 (f18a44fedeb29764b2b5336c120fdd90ef1a3f5c-refs/branch-heads/6261@{#1057}) on port 9515 Only local connections are allowed. Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe. ChromeDriver was started successfully. i have tried in my localhost which is working fine. but the problem comes from the server -
Not getting Social Token when using SignIn with Slack
I am using django-allauth==0.61.1. I have added settings for Slack. I can successfully Signup/Login on my webapp using the SignIn with Slack. I get the email, slack_user_id, username from slack. But I don't get any social_token for that user. The user will be using my slack app with some commands. I need the token with expiry date to determine if the user is logged or logged out. I have checked the Oauth Scopes. I have the following User Token Scopes: email openid profile -
Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0011_alter_user_first_name_max_length.py')
When i run the command python manage.py runserver the error occurs as Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 1045, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2288.0_x64__qbz5n2kfra8p0\Lib\threading.py", line 982, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\core\management\base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\executor.py", line 18, in init self.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\loader.py", line 49, in init self.build_graph() File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\graph.py", line 195, in [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] ^^^^^^^^^^^^^^^ File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0011_alter_user_first_name_max_length.py') Every code was running without trouble earlier, suddenly the problem arises. I want a solution for this issue. -
Coverage expect me to test an @abstractmethod
As you can see in the picture below, coverage wants me to write a test case for the method inside the abc. But I dont know how to do it, I mean as far as I can see there is nothing to test. Code: from abc import ABC, abstractmethod class BaseVPS(ABC): @abstractmethod def create_server(self): ... I want to write a test case for the create_server -
Django - automating selections of manytomany fields from views
I've been building upon the basic polls project to create an application for my band. The goal is to have each member vote on a gig date request, and then for each member that has voted stating they're available, a nametag is then created which can be added to a gig card along with other information for the gig. I have the nametags being generated within the admin panel when each user votes in favour of the date. I have the gig cards being generated with all relevant information. If I go into the admin panel, I can select one, or many name tags and they will display on the cards as desired.. however, I would like for this to be automated from a views function to save manual selection. In the code, I've toyed with a set to collate all the users that voted 'yes'. I've searched for days and tried various different things but being new to django, (and programming) it's become quite overwhelming. I feel like it's probably something quite simple, but my lack of broader understanding has led me here for my first stack question. Thanks in advance and apologies if there are holes in my … -
How to include foregin key attribute in Elastic Search Django?
I have two models Products and VendorProducts model as follows : class Product(models.Model): brand = models.ForeignKey(BrandName,related_name="brand_products", on_delete=models.CASCADE) item_name_title = models.CharField(max_length=10000) class VendorProducts(BaseModel): product = models.ForeignKey(Product , on_delete=models.PROTECT , null=True ,related_name="vendor_products") vendor_selling_price = models.FloatField(default=0, null=True, blank=True) Now I want to add this VendorProduct model in ElasticSearch. And I have done something like this @registry.register_document class ProductDocument(Document): product = fields.ObjectField(properties={ "item_name_title" : fields.TextField()}) class Index: name = "vendor_products" class Django: model = VendorProducts fields = [ "id", ] related_models = [Product] def get_queryset(self): """Not mandatory but to improve performance we can select related in one SQL request""" return super(ProductDocument, self).get_queryset().select_related( 'product' ) First, this is how we add the foreign key model in Elastic search. Now the issue is I am not able to get any of the results. Although I can see the results in elastic search when I tryto access it by port 9200 I can see the search results. But when querying I am getting empty responses. This code I am using s = ProductDocument.search().query("match", description=search) -
Why Post has no field 'publish' as the app cache isn't ready yet so if this is an auto-created field, it won't be ready yet?
I am new to Django. I am doing a blogsite project. I am creating a datebase for the blog. But when I run the command 'python manage.py makemigrations blog', I get this error. The error is "FieldDoesNotExist(django.core.exceptions.FieldDoesNotExist: Post has no field named 'publish'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet.)". This is my blog.models.py file from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() published = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) class Meta: ordering = ['-publish'] indexes = [ models.Index(fields=['-publish']),] def __str__(self): return self. Title I don't know the problem. Can someone help me? -
ERROR : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email
I'm learning Django but I keep getting this error when I type : django.db.utils.IntegrityError: UNIQUE constraint failed: users_customuser.email I Have a Creating Superuser But I'm facing some Error till superuser run on Server. So, Give me A Solution of This Error. My models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db import models from .managers import CustomUserManager class CustomUser(AbstractUser): email = models.EmailField(unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) phone = models.CharField(max_length=10) cpassword = models.CharField(max_length=10) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ("email",) objects = CustomUserManager() -
Add to cart functionality using Django and HTMX
Hi can you please help me with this problem. I have this code: models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) class Cart(models.Model): products = models.ManyToManyField(Product, through='CartItem') @property def total_price(self): return sum(item.product.price * item.quantity for item in self.cartitem_set.all()) class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Product, Cart, CartItem def product_list(request): products = Product.objects.all() # Retrieve or create a cart ID in the session cart_id = request.session.get('cart_id') cart, created = Cart.objects.get_or_create(id=cart_id) # Pass the cart items to the template context cart_items = CartItem.objects.filter(cart=cart) total_items_in_cart = sum(item.quantity for item in cart_items) total_price = cart.total_price for item in cart_items: item.subtotal = item.product.price * item.quantity context = {'products': products, 'cart_items': cart_items, 'total_items_in_cart': total_items_in_cart, 'total_price': total_price} return render(request, 'product_list.html', context ) def add_to_cart(request, product_id): product = get_object_or_404(Product, id=product_id) cart_id = request.session.get('cart_id') cart, created = Cart.objects.get_or_create(id=cart_id) # Check if the product is already in the cart cart_item, item_created = CartItem.objects.get_or_create(product=product, cart=cart) if not item_created: # If the product is already in the cart, update the quantity cart_item.quantity += 1 cart_item.save() # Update session with cart ID request.session['cart_id'] = cart.id request.session.save() return render (request, 'cart_items_partial.html') … -
DRF-Spectacular with django-split-settings: AssertionError: Incompatible AutoSchema to generate Swagger
I am encountering an error when utilizing django-split-settings (version 1.3.0) and drf-spectacular (version 0.27.1) in my Django project. The error occurs when attempting to access the Swagger UI endpoint at api/schema/swagger-ui/. Here is the error message: AssertionError: Incompatible AutoSchema used on View <class 'drf_spectacular.views.SpectacularAPIView'>. Is DRF's DEFAULT_SCHEMA_CLASS pointing to "drf_spectacular.openapi.AutoSchema" or any other drf-spectacular compatible AutoSchema? To provide further context, here's a breakdown of my project structure: my_project | |_apps | |_settings | |---components | |------drf.py | |---environments | |---__init__.py The content of drf.py and init.py is as follows REST_FRAMEWORK = { ### some settings "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", } init.py content:: from split_settings.tools import include from my_project.settings.components.env import Environment _base_settings = ( # Load environment settings "components/env.py", # Here we should have the order because of dependencies "components/paths.py", "components/security.py", "components/apps.py", "components/middleware.py", # Load all other settings "components/*.py", # Select the right env: f"environments/{Environment}.py", ) # Include settings: include(*_base_settings) It's important to note that this error doesn't occur when using a single, traditional settings file in my Django project. Here's the relevant portion of my urls.py file for reference (just same as the drf-spectacular package): from drf_spectacular.views import SpectacularAPIView, SpectacularRedocView, SpectacularSwaggerView urlpatterns = [ # YOUR PATTERNS path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional … -
Debugging Django AJAX Cart Deletion: Items Not Updating on Removal
I am new in Stack overflow and I am getting problem during deleting product from cart In my cart.html: <button class="btn btn-sm btn-remove delete-item" data-item="{{product_id}}"><i class="fas fa-trash-alt" ></i></button> This is the delete button I created. Now also I created js for this button so in my cart.js: console.log("Hi"); $(document).on("click", '.delete-item' ,function(){ let this_val=$(this) var _pID=$(this).attr('data-item'); console.log(_pID); $.ajax({ url: '/delete-from-cart', data: { 'id': _pID, }, dataType: 'json', beforeSend: function(){ this_val.hide() }, success: function(response){ this_val.show() $(".cart-items-count").text(response.totalcartitems) $("#cart-list").html(response.data) } }) }) for the js file when i am clicking on the delete button I am getting product ids as output I also created a views for it. So, In my views.py: def delete_item_from_cart(request): product_id=str(request.GET['id']) if 'cart_data_obj' in request.session: if product_id in request.session['cart_data_obj']: cart_data=request.session['cart_data_obj'] del request.session['cart_data_obj'][product_id] request.session['cart_data_obj'] = cart_data cart_total_ammount=0 if 'cart_data_obj' in request.session: for p_id, item in request.session['cart_data_obj'].items(): cart_total_ammount += int(item['qty']) * float(item['price']) context= render_to_string("core/async/cart_list.html", {"products":products}, {"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) return JsonResponse({"data": context, 'totalcartitems': request.session['total_cart_items'] ,'cart_total_ammount':cart_total_ammount}) and then In urls.py: path("delete-from-cart/", delete_item_from_cart,name="delete-from-cart"), this is my url Note: At last I would say that I made a cart page where all the products are displaying which are sellected. and I connected cart-lsit.html with cart.html by main tag with id you can see this in the … -
Filtering nested models using generic foreign keys in django
class Complaint(models.Model): complaint_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True) user_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='complaint_user') user_id = models.PositiveIntegerField() user_object = GenericForeignKey('user_type', 'user_id') complaint_date = models.DateTimeField(auto_now_add=True) complaint_time = models.TimeField(auto_now_add=True) complaint_message = models.CharField(max_length=1000, editable=True) type_of_complaint = models.CharField(editable=True, default='public') status = models.CharField(editable=True, default='pending') complaint_title = models.CharField(max_length=100, editable=True) # Should be able to assign to multiple models such as Counsellor, ClassTeacher, HOD content_type = models.ForeignKey(to=ContentType, on_delete=models.CASCADE, related_name='complaint_owner') object_id = models.PositiveIntegerField() assigned_to = GenericForeignKey('content_type', 'object_id') escalated_to = models.ForeignKey(to=EscalationStructure, on_delete=models.CASCADE) I am trying to access a field in the user_object model, the is nested as user_object.user.username. I am accessing the username in this search vector def search(request): query = request.GET.get('query', '') vector = SearchVector('complaint_title', 'complaint_message', 'status', 'complaint_time', 'complaint_date', 'counsellor_complaints', 'user_object__user__username') results = Complaint.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.001).order_by('-rank') return render(request, 'complaint_administration/view_complaints.html', {'complaints': results}) It throws an error saying Field 'user_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. I'm not accessing a reverserelation right. I am accessing through the complaint it self ?? -
RelatedObjectDoesNotExist at /profile/social/add ProfileSocialMedia has no profile
I'm trying to use the clean method of a model in my project, but I get the error: RelatedObjectDoesNotExist at /profile/social/add ProfileSocialMedia has no profile. I've tried a lot of different things, but I still can't figure out what I'm doing wrong Another detail is that it works correctly until it reaches the limit, when it reaches the limit I wanted it to generate a raise forms.ValidationError, but in fact it generates this error on the django yellow screen Below is my code class ProfileSocialMedia(models.Model): profile = models.ForeignKey(Profile, related_name="medias", on_delete=models.CASCADE) social_media = models.ForeignKey(SocialMedia, on_delete=models.CASCADE, blank=False) identification = models.CharField("Identification", max_length=3000) def __str__(self): return f"Profile Owner: {self.profile.user.first_name} / Social Media: {self.social_media.name}" class Meta: verbose_name = 'Profile Social Media' verbose_name_plural = 'Profile Social Medias' def clean_social_media(self): if self.social_media is None: raise ValidationError("Por favor, selecione uma rede social") print(self.profile) def clean_identification(self): if self.social_media.is_link == False: validate_number(self.identification) else: validate_url(self.identification) def clean_socials(self): limit = 6 socials = self.profile.medias.all() if socials.count() >= limit: raise ValidationError("Você atingiu o limite(6) de redes socias que podem ser adicionadas, altere ou exclua uma rede social existente.") def clean(self): self.clean_identification() self.clean_social_media() self.clean_socials() def save(self, *args, **kwargs): if self.social_media.is_link: if not re.match(r'^https?://', self.identification): self.identification = f'https://{self.identification}' self.full_clean() super().save(*args, **kwargs) class AddSocialMediaForm(forms.ModelForm): social_media = …