Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display data in carousel card - bootstrap
I use bootstrap 5.0 and I try display title of book on the card but not effective. My carousel in html {% block content %} <div id="carouselExampleIndicators" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner" style="background:gray; color:white; height:300px; position:relative"> <div class="carousel-item active"> <div class="container" style="position:absolute; right:0; padding-top:150px; padding-bottom:50px"> {% for book in obj %} <h1>{{book.title}}</h1> <p>Some first text to test</p> <a href="#" class="btn btn-lg btn-primary">Read more</a> {% endfor %} </div> <img src="/assets/media/book_images/BookDefault.png" class="d-block w-100" alt="..."> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> {% endblock %} and my example method def display_book(request): obj = Book.objects.get(1) return render(request, 'templates/carousel_1.html', {'obj': obj}) Everything in the for loop is not displayed. My project structure: WebBook |-accounts |-books |--views.py with method |-templates |--carousel_1.html with my carousel I looked in many places but none of the methods worked. Could you help? -
How to return all the message between two Users - Django/Python/Chat Building
I'm building a simple chat with Django-Rest-Framework in Python. I created a GET/POST methods for Users and Chat. MODEL from django.db import models from django.db.models.base import Model class User(models.Model): class Meta: db_table = 'user' user_firstname = models.CharField(max_length=200) user_lastname = models.CharField(max_length=200) class Chat(models.Model): class Meta: db_table = 'chat' from_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') message = models.CharField(max_length=1000) to_message = models.ForeignKey(User, on_delete=models.CASCADE, related_name='+') SERIALIZERS from rest_framework import serializers from .models import User, Chat class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' class ChatSerializer(serializers.ModelSerializer): class Meta: model = Chat fields = '__all__' URLS from django.urls.conf import re_path from . import views urlpatterns = [ re_path(r'^users/$', views.UserList.as_view(), name='users-list'), re_path(r'^chat/$', views.ChatList.as_view(), name='chat-get-list'), re_path(r'^chat/(?P<from_id>.+)&(?P<to_id>.+)/$', views.ChatList.as_view(), name='chat-list'), ] VIEWS from rest_framework import generics, serializers from .models import User, Chat from .serializers import ChatSerializer, UserSerializer class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer def get_queryset(self): queryset = User.objects.all() return queryset class ChatList(generics.ListCreateAPIView): queryset = Chat.objects.all() serializer_class = ChatSerializer def get_queryset(self): queryset = Chat.objects.all() from_id = self.request.query_params.get('from_id') to_id = self.request.query_params.get('to_id') if from_id is not None and to_id is not None: queryset = Chat.objects.filter(from_message=from_id,to_message=to_id) #Probably my error is here, because I'm specifying the messages. I need to add something like 'to_message=to_id or from_id return queryset THE PROBLEM: When I … -
django deleteview edit performance
I'm new in Django, I'm learning class based view and all works fine, what I'm trying to do is to edit the DeleteView performance, this just delete de object but what im looking is to edit the object instead of delete class borrar(DeleteView): model = Usuario template_name = "usuario_confirm_delete.html" success_url = '/alta/' I would like to edit but I do not know how to achieve this. Usuario.objects.filter(id=23).update(activo='False') Any idea ? -
Django search and display results in chart on refresh
am creating a search Web for psql database I have. Am having a few issues with django, my app draw a chart for results and print them. On refresh results change and chart disappear! -
CSRF token missing or incorrect - using auto-complete light in Django
Running into CSRF_Token missing or incorrect in my Django-app, don't really understand what the issue is as I've included the {% csrf_token %} in any possible form being rendered by my template. I suspect it may have to do with the ajax requests that are done within the form to retrieve area-names and more, maybe someone can tell me what the issue is. I'm using autocomplete-light for retrieving some data from my DB, don't know if that can play a part in this. I've tried searching around online but haven't found a solution that seems to apply to my problem. Views.py Class BreedAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): if not self.request.user.is_authenticated: return DogBreeds.objects.none() qs = DogBreeds.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class AdListTakeMyDog(generic.ListView): model = Advertisement context_object_name = 'ads' template_name = 'core/advertisement_list_take.html' def get_queryset(self): queryset = Advertisement.objects.filter(is_offering_own_dog=True) return queryset class AdListGetMeADog(generic.ListView): model = Advertisement context_object_name = 'ads' template_name = 'core/advertisement_list_get.html' def get_queryset(self): queryset = Advertisement.objects.filter(is_offering_own_dog=False) return queryset class NewAdTakeMyDog(CreateView): model = Advertisement form_class = NewAdTakeMyDogForm success_url = reverse_lazy('view_ads_take_my_dog') template_name = 'core/advertisement_form_take.html' def form_valid(self, form): form.instance.author = self.request.user form.instance.is_offering_own_dog = True return super().form_valid(form) class NewAdGetMeADog(CreateView): model = Advertisement form_class = NewAdGetMeADogForm success_url = reverse_lazy('ad_changelist') template_name = 'core/advertisement_form_get.html' def form_valid(self, form): form.instance.author = … -
what is the best architecturefor multi website (url) Django web server?
I would like to build a multi web platform which is based on Django (Python) + WSGI. The webs will have one database, exactly same backend and only the different frontend/url. What is the best Architecturefor such plateform, docker or simply congfigure different Apps? Any suggestions -
Django Countries - unable to pre-select the right country in an edit form
Consider this model: class Address(models.Model): line1 = models.CharField(max_length=255, db_index=True, blank=True, null=True) city = models.CharField(max_length=255, db_index=True, blank=True, null=True) state = models.CharField(max_length=255, db_index=True, blank=True, null=True) postcode = UppercaseCharField(max_length=64, blank=True, db_index=True, null=True) country = CountryField(db_index=True, blank=True, null=True) I'm trying to populate this model using data that comes in through webhook call. I'm having trouble populating the country in two cases: When the country is "United States" (this is what the webhook returns, I have no control over it) - django_countries does not recognize this, so I added an if condition to change "United States" to USA before creating a new Address object but, when the country is not United States, for example "Panama", I populate it directly into the model by doing this: country = request.POST.get('country') # returns something like "Panama" Address.objects.create(line1=line1, city=city, state=state, country=country) This works fine, except when I try to edit the Address form, the country field is blank, it isn't pre-selecting "Panama" from the options. I know the country field of this Address instance is a country object because I can do address_form.instance.country and it outputs Pa, if I do address_form.instance.country.name it outputs Panama. So why isn't the country field in the form pre-selecting the right Country, why does … -
Azure Hosted ASGI Django Server Bottleneck When Handling Over a Dozen Simultaneous Requests
I'm new to working with ASGI and I'm having some performance issues with my Django API server so any insight would be greatly appreciated. After running some load tests using JMeter it seems that the application is able to handle under 10 or so simultaneous requests as expected, but any more than that and the application's threads seem to lock up and the response rate vastly diminishes (can be seen in sample #14 and up on the 'Sample Time(ms)' column in the screenshot provided). It's as if requests are only being processed on 1-2 threads after that point as opposed to the configured 4. Here is my startup.sh config: gunicorn --workers 8 --threads 4 --timeout 60 --access-logfile \ '-' --error-logfile '-' --bind=0.0.0.0:8000 -k uvicorn.workers.UvicornWorker \ --chdir=/home/site/wwwroot GSE_Backend.asgi I am aware that the individual API responses are quite slow. That is something I want to address. However, is there perhaps something I am doing wrong on the ASGI level here? Thanks. -
DRF serializer data property not overridden
I have a the following serializer where I need to override the data property but for some reason it does not seem to be overridden at all. class ShopItemListSerializer(AvailabilitySerializerFieldMixin, serializers.ModelSerializer): is_aggregation_product = serializers.BooleanField() price = MoneyField(allow_null=True) discount_price = serializers.SerializerMethodField() is_favorite = serializers.SerializerMethodField() categories = ShopItemCategorySerializer(many=True) price_effect = ProductPriceEffectSerializer(source="aggregation_product.price_effect") special_information = serializers.CharField() @property def data(self): logging.error("I should be overridden") ret = super().data return_dict = ReturnDict(ret, serializer=self) if self.context.get("include_unavailable", False) is True: """ remove products that are not available """ for product in return_dict.copy(): if product["availability"] and product["availability"]["is_available"] is True: return_dict.remove(product) return return_dict I am using viewsets like the following: class ProductViewSet(StorePickupTimeSerializerContextMixin, ReadOnlyModelViewSet): queryset = ShopItem.app_visibles.prefetch_related("pictures").distinct() permission_classes = [IsCustomer] filter_backends = (filters.DjangoFilterBackend, SearchFilter, OrderingFilterWithNoneSupport) filterset_class = ShopItemFilter search_fields = ["name", "number", "categories__name"] def get_serializer_class(self): if self.action == "list": return ShopItemListSerializer return ShopItemProductDetailSerializer I would appreciate any insights explaining the reason behind this behavior. -
Return value if not exist
Within my template, I have a number of values being presented from data within the database. {{ fundamentals.project_category }} But when no data exists it throws an error matching query does not exist. i think because the no data is being returned in the query set within the fundamentals model. fundamentals = project.fundamentals_set.get() within my view im trying: if project.fundamentals_set.get().exists(): fundamentals = project.fundamentals_set.get() else: #what should i put here? Im assuming an if statment is requried along with exists(): but this isn't working and im not sure what i should put in the else statement to return something like nothing exists when no data exists within the fields? -
(553, b'Relaying disallowed as webmaster@localhost')
I'm trying to send a password reset email on Django web app using the Zoho SMTP but it keeps throwing this error when I use Gmail. Below are some snippets Views.py def post(self, request): name = request.POST['Name'] email = request.POST['Email'] phone = request.POST['Phone'] message = request.POST['Message'] email_msg = EmailMessage( subject='New Enquiry', body=message + phone, from_email='noreply@domain.com', to=['support@domain.com'], ) email_msg.send() settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.zoho.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = '' EMAIL_HOST_PASSWORD = '' -
Specific problem while migrating Django models
Attempt to migrate just default models in Django app with python manage.py migrate returns following annoying error: Traceback (most recent call last): File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 199, in get_new_connection connection = Database.connect(**conn_params) File "/home/stepski/anaconda3/lib/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: fe_sendauth: no password supplied The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/management/base.py", line 438, in check all_issues = checks.run_checks( File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/core/checks/model_checks.py", line 34, in check_all_models errors.extend(model.check(**kwargs)) File "/home/stepski/anaconda3/lib/python3.8/site-packages/django/db/models/base.py", line 1307, in … -
hot reload of Django development in Docker is delayed
The hot reload is delayed by 1 cycle. So for example, if I have print("Hi"), nothing changes, but then if I have print("Hello"), then print("Hi") appears on the screen. If I have a third command print("Goodbye"), then print("Hello") appears. So it is always delayed by a cycle. How can I fix the code below so it is not delayed by 1 cycle but the update happens instantly. Here is my dockerfile. ########### # BUILDER # ########### # pull official base image FROM python:3.9.9-slim-bullseye as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.9.9-slim-bullseye # installing netcat (nc) since we are using that to listen to postgres server in entrypoint.sh RUN apt-get update && apt-get install -y --no-install-recommends netcat && \ apt-get install ffmpeg libsm6 libxext6 -y &&\ apt-get autoremove -y && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* # install dependencies COPY --from=builder /usr/src/app/wheels /wheels COPY --from=builder /usr/src/app/requirements.txt . RUN pip install --no-cache /wheels/* # set work directory WORKDIR /usr/src/app # copy our django … -
different between title and title_icontains in model filter django
what is diffrent between title and title_icontains in django ? from .model import product product.objects.filter(title='blah') product.objects.filter(tite__icontains='blah') -
ArrayField in djongo models, i get json response like these
[ { "id": 10, "table_name": "cars", "columns": "[{"column_key": "paul", "display_key": "paul@mail.com", "column_type": "text", "char_limit": "0"}, {"column_key": "tus", "display_key": "tus@mail.com", "column_type": "text", "char_limit": "1"}]" }, { "id": 26, "table_name": "comics", "columns": "[{"column_key": "ben-10", "display_key": "ben@mail.com", "column_type": "text", "char_limit": "5"}]" } ] -
Django: Changing of value of particular fields in previous instances of model if particular instance occurs
I' m creating small django project. Is any way to change value of particular fields in previous instances of particular model? class Fruit (models.Model): name=models.CharField(max_length=40) amount=models.IntegerField() So far for example i have three instances of my model. [0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}}, 1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Apple", "amount": "2"}}, 2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Mango", "amount": "1"}}] And i decided that fourth instance will be Orange in amount 3. [0 Object{ "model": "Fruit","pk": 1,"fields": {"name": "Banana", "amount": "2"}}, 1 Object{ "model": "Fruit","pk": 2,"fields": {"name": "Orange", "amount": "2"}}, 2 Object{ "model": "Fruit","pk": 3,"fields": {"name": "Orange", "amount": "1"}} 3 Object{ "model": "Fruit","pk": 4,"fields": {"name": "Orange", "amount": "3"}}] As you see my goal is to change all previous names of fruits to Orange in case of creating of instance with Orange as name until Banana occurs so banana remains unchanged. Is there any way to do something like that? -
Problema no GET python Django
Probably something simple I did not notice: <h1> WRITE YOUR TEXT: </h1> <form method="" action="counter"> <textarea name= "words" rows="25" cols="65"></textarea><br> <input value="submit" type="submit"/> </form> from typing import Counter from django.urls import path from . import views urlpatterns = [ path('', views.index, name = 'index'), path('counter', views.counter, name = 'counter'), ] from django.shortcuts import render from django.http import HttpResponse # Create your views here def index(request): return render(request, 'index.html') def counter(request): words = request.GET['words'], return render(request, 'counter.html', words) and the error is: https://i.stack.imgur.com/U7pNy.png -
What attributes are allowed on custom django admin field methods?
I've noticed in some Django project that uses Django admin methods on model-admin that look like this: def some_field(self, obj): return calculate_something(obj) some_field.short_description = "Some description" And then it's used in field-set as normal field. It gets somehow magically recognized by name. Where can I find documentation about the short_description and what other things I can set? -
Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory
I have a problem with gunicorn. I followed this guide to run website hosting on my raspberry on debian. But I got this error: gunicorn.service: Failed at step EXEC spawning /var/www/loveIt/env/bin/gunicorn: No such file or directory I don't understand why it don't create gunicorn. I watched a lot of guides but no one helped me. Here is my gunicorn.service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=anton Group=www-data WorkingDirectory=/var/www/loveIt ExecStart=/var/www/loveIt/env/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn.sock \ lulu.wsgi:application [Install] WantedBy=multi-user.target And this is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target What I need to do to solve this problem? -
django application not working after i add watchtower logging
import boto3 boto3_logs_client = boto3.client("logs", region_name=AWS_REGION_NAME) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'root': { 'level': logging.ERROR, 'handlers': ['console'], }, 'formatters': { 'simple': { 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, 'aws': { # you can add specific format for aws here 'format': "%(asctime)s [%(levelname)-8s] %(message)s", 'datefmt': "%Y-%m-%d %H:%M:%S" }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' }, 'watchtower': { 'level': 'DEBUG', 'class': 'watchtower.CloudWatchLogHandler', 'boto3_client': boto3_logs_client, 'log_group_name': AWS_LOG_GROUP, 'log_stream_name': AWS_LOG_STREAM, 'formatter': 'aws', }, }, 'loggers': { 'django': { 'level': 'INFO', 'handlers': ['watchtower'], 'propagate': False, }, # add your other loggers here... }, } Here i implemented watchtower logging in my django app My server is running but when i view http://127.0.0.1:8000/ This site can’t be reached what can be the error ? am i missing something please take a look. please take a look how can i fix this -
IntegrityError : null value in column of relation " violates not-null constraint
'm building a small webstore , in the product page i put the order form using FormMixin and TemplateView, when i submit the order i get a " null value in column "customer_id" of relation "products_order" violates not-null constraint DETAIL: Failing row contains (21, null)." error : models.py class Product(models.Model): name = models.CharField(max_length=255) description = models.TextField() nominal_price = models.PositiveIntegerField(verbose_name='prix normal',) reduced_price = models.PositiveIntegerField(blank=True, null=True) quantity = models.PositiveIntegerField(default=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products') photo = models.ImageField(upload_to="img/products/", default="img/products/user_default.png") def __str__(self): return self.name class Customer(models.Model): full_name = models.CharField(max_length=150) address = models.CharField(max_length=1500, null=True) phone = models.IntegerField() city = models.CharField(max_length=100) email = models.EmailField(null=True) def __str__(self): return self.full_name class Order (models.Model): product = models.ManyToManyField(Product, through='OrderProduct') customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class OrderProduct(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) views.py : class ProductDetailView(FormMixin, TemplateView): model = Product template_name = 'product.html' form_class = OrderForm def get_success_url(self): return reverse('index') def post(self, request, *args, **kwargs): context = self.get_context_data() form = OrderForm(request.POST) if context['form'].is_valid(): product = get_object_or_404(Product, name=self.kwargs['product_name']) customer = form.save() Order.objects.create(customer=customer) instance= Order.objects.create() instance.product.set(product) return super(TemplateView, self) def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) context['product'] = Product.objects.get(name=self.kwargs['product_name']) context['form'] = self.get_form() return context -
i couldn't find out this script at all in django-form
would you please explain this scripts? why we used **def init(self, *args, kwargs): AND **super(ProfileForm, self).init(*args, kwargs) ? *from django import forms from django.forms import fields from .models import User class ProfileForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(ProfileForm, self).__init__(*args, **kwargs) self.fields['username'].help_text = None self.fields['username'].disabled = True self.fields['email'].disabled = True self.fields['special_user'].disabled = True self.fields['is_author'].disabled = True class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'special_user', 'is_author' ] thanks.* -
SMTPAuthenticationError at /members/register after deployment in heroku ut works in local host
I am getting the below error when I aam trying to send an email to user. It is wroking fine in localhost, but after deploying it to heroku I am getting this error. My less secure app is turned on. SMTPAuthenticationError at /members/register (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt\n5.7.14 iREvsLOCGsSdIvQozvsLAI32usRkAKeN9zrVcpG8_5BPTE8Cid59meSrouoFeVL7uexVM\n5.7.14 9BeaQ5gSKAKohzILe4Nqyrn_p3OJhBZJVuJ3Nb36rtmD2h_Rb7TCpJRB6xMw87Ow>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 n7sm3256692wro.68 - gsmtp') settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'password' SERVER_EMAIL = EMAIL_HOST_USER -
How to intersect two query sets in django?
I have two queries. One of them has sold product id and sale amount, other one has product id and product price. query_product = Model1.objects.filter(...).values_list('ProductID', 'ProductPrice') query_sale = Model2.objects.filter(...).values_list('SaleProductID', 'ProductAmount') I want to calculate IF SaleProductID = ProductID, Sum(F('ProductPrice')*F('ProductAmount'). However, I could not find how to do that with query. Note: Model2 has foreign key to Model1. Do you have any suggestions? Thank you! -
FormData and Django: How to pass empty array
I have email_list field in my form If there are no emails entered as Json payload i can send it as: { email_list: [] } Where as with FormData how to send it. I am thinking something like this if (data["email_list"].length === 0) { formData.append("email_list", []); } data["email_list"].forEach((item) => { formData.append("email_list", item); }); Am i doing the right way I checked the data i recieved in the django backend print(request.POST.getlist('email_list')) it prints [""] i want it to be []