Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-import-export package post_save signal called twice
I am using the django-import-export package to import data from a model from the admin site. This model has a function for sending email that is executed with the post_save signal. The problem is that when the preview is generated (import confirmation) the function associated with the post_save is executed and then when I confirm the import, it is executed again, that is, the mail is sent twice. How to solve this problem? The following is the function with the @receiver decorator that uses the post_save signal @receiver(models.signals.post_save, sender=MiModel) def send_email(sender, instance, **kwargs): ..... server.sendmail(....) I am using Python==3.6.5, Django==3.0.5, django-import-export==2.5.0 -
Apache Django Internal Server Error (Ubuntu 18.04)
I have a Django wagtail application. I can run it in debug and I can run it on a django server but if I try to run it on my Ubuntu 18.04 server using Apache2 WSGI I get "Internal Server Error". Apache log: [Mon Jan 18 23:29:23.673557 2021] [mpm_event:notice] [pid 92324:tid 140613127453760] AH00491: caught SIGTERM, shutting down Exception ignored in: <function BaseEventLoop.__del__ at 0x7fe301c1fc10> Traceback (most recent call last): File "/usr/lib/python3.8/asyncio/base_events.py", line 654, in __del__ NameError: name 'ResourceWarning' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined Exception ignored in: <function Local.__del__ at 0x7fe301b95040> Traceback (most recent call last): File "/home/user/wow/lib/python3.8/site-packages/asgiref/local.py", line 96, in __del__ NameError: name 'TypeError' is not defined [Mon Jan 18 23:29:24.194636 2021] [mpm_event:notice] [pid 92749:tid 139932982541376] AH00489: Apache/2.4.41 (Ubuntu) OpenSSL/1.1.1f mod_wsgi/4.6.8 Python/3.8 configured -- resuming normal operations [Mon Jan 18 23:29:24.194764 2021] [core:notice] [pid 92749:tid 139932982541376] AH00094: Command line: '/usr/sbin/apache2' [Mon Jan 18 23:29:31.468972 2021] [wsgi:error] [pid 92750:tid 139932932445952] WSGI without exception my wsgi … -
Django objects.get(): The QuerySet value for an exact lookup must be limited to one result using slicing
I'm trying to check if a user exists in the database based on email address, so I get the email and if that email exists, I want to return the username of that user alongside with some other data. I'm using objects.get() method to do so but I keep getting this error. Did some search on it, a couple of solutions were suggesting to do a filter and return the .first() object or instead of email=email, suggested to put email=email[0], but both of these approaches ended up giving me an empty array in response. Here's my Views.py: class CheckEmailView(APIView): permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = CheckEmailSerializer(data=request.data) serializer.is_valid(raise_exception=True) email = Account.objects.filter(email=serializer.data['email']) if email.exists(): username = Account.objects.get(email=email) return Response({'is_member': True, 'username': username}) else: return Response({'is_member': False}) -
Django admin keeps loading the wrong template
Admin app keeps loading the wrong template "user/welcome.html". I've reinstalled django, confirmed that 'django.contrib.admin' is inside INSTALLED_APPS, switched 'APP_DIRS', inside TEMPLATES, to True and I've also checked the templates folder inside admin and confirmed that the correct index.html is there. If I delete user/welcome.html in order to throw an error the traceback is as follows: Request Method: GET Request URL: http://localhost:8000/admin Django Version: 3.1.5 Python Version: 3.8.5 Installed Applications: ['common_balance', 'users', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\common_balance\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\users\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\contrib\admin\templates\users\welcome.html (Source does not exist) * django.template.loaders.app_directories.Loader: C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\contrib\auth\templates\users\welcome.html (Source does not exist) Traceback (most recent call last): File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\users\views.py", line 11, in welcome return render(request, "users/welcome.html") File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\jeron\Documents\Programacao\Projetos\UoMe\env\lib\site-packages\django\template\loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) Exception Type: TemplateDoesNotExist at /admin … -
Join onto other table where there is no foreignkey relationship
I have one Django model with with "some_id" and many other models with "some_id" as primary key. class ModelA(models.Model): name = models.CharField(max_length=150) some_id = models.PositiveIntegerField() [...] # more fields class ModelB(models.Model): some_id = models.PositiveIntegerField(primary_key=True) [...] # more fields class ModelC(models.Model): some_id = models.PositiveIntegerField(primary_key=True) [...] # more fields How can I annotate a ModelA queryset with a boolean field if a row exists in ModelB/ModelC etc ------------------------------------------ | name | some_id | has_b | has_c | ----------------------------------------- | John | 1 | True | False | ------------------------------------------ Do I need to use ".extra()"? or some database expression I cant change the model/table to add the foreign key relationship. -
UNIQUE constraint failed: auth_user.username when trying to save the form
Whenever I try to register an account this error jumps out in the form.save() on the views.py code. I've tried some things but didn't work out. I don't know if it is because of verifiying problems or what. The problem is that I've tried many things to sort this out but can't find a definite solution. Thank you! views.py: from django.shortcuts import render from .scrapper import EmailCrawler from django.http import HttpResponse from celery import shared_task from multiprocessing import Process from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from asgiref.sync import sync_to_async from django.shortcuts import redirect from .forms import CreateUserForm from rest_framework.decorators import APIView from rest_framework.response import Response from leadfinderapp import serializers from django.contrib import messages def register(request): if request.user.is_authenticated: return redirect('login') else: form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Account was created for' + user) return redirect('login') context = {'form':form} return render(request, 'leadfinderapp/register.html', context) models.py: from django.db import models from django.contrib.auth.forms import UserCreationForm from django import forms # Create your models here. class User(models.Model): first_name = models.CharField(max_length=40000) last_name = models.CharField(max_length=40000) email = models.EmailField(max_length=40000) password1 = models.CharField(max_length=40000) password2 = models.CharField(max_length=40000) class Emails(models.Model): name = models.CharField(max_length=40000) urls = models.URLField(max_length=200) emails = models.TextField() def __str__(self): return self.name forms.py: from … -
Is there a way to avoid CORS error while in production in NuxtJS?
I have been using NuxtJS locally alongside Django Rest Framework and there have been no issue. However, after deployment on Netlify I started getting CORS error - although, I have axios proxy set. I had to rerun npm run generate and run the generated file locally for which I get the same error. I later found out that proxy doesn't work with statically generated NuxtJS app. I have searched Google tirelessly but I can't seem to get a direct solution. I have to deploy this app on Netlify without having access to Nginx or Apache server. Please can anyone suggest a simple solution to avoid CORS error 405. The repository containing the code is located here -
Data from form doesn't save at database ( can't validate )
Always, whni I try to add some content with my post form I'l always have an validation error I don't correctly understand how to use checkbox validation All data print at console with csrf token, but can't save at db models.py class Film(models.Model): title = models.CharField('Название фильма', max_length=255) #slug = models.SlugField(unique=True, max_length=55) description = models.TextField('Описание фильма', null=True) main_image = models.ImageField('Постер', upload_to='images/film_poster') image1 = models.ImageField('Первое изображение', upload_to='images/') image2 = models.ImageField('Второе изображение', upload_to='images/') image3 = models.ImageField('Третее изображение', upload_to='images/') image4 = models.ImageField('Четвёртое изображение', upload_to='images/') image5 = models.ImageField('Пятое изображение', upload_to='images/') trailer_link = models.URLField('Ссылка на трейлер') two_d = models.BooleanField('2Д',default=False) three_d = models.BooleanField('3Д',default=False) i_max = models.BooleanField('I_MAX', default=False) duration = models.CharField('Длительность фильма', max_length=55) first_night = models.DateField(verbose_name='Дата премьеры', null=True) There is my view's: views.py def film_page(request): error = '' if request.method == 'POST': form = FilmForm(request.POST) if form.is_valid(): form.save() return redirect('film_list') else: error = 'Что-то пошло не так' form = FilmForm() data = { 'form': form, 'error': error, } return render(request, 'adminLte/film/film_page.html', data) That's mine Html-file {% extends 'adminLte/base.html' %} {% block film %} <li class="nav-item"> <a href="{% url 'film_list' %}" class="nav-link active"> <i class="fas fa-film"></i> <p> Фильмы </p> </a> </li> {% endblock %} {% block content_title %} <h1 class="m-0">Форма добавления фильма</h1> {% endblock %} {% block main_content … -
How do I iterate dictionary with lists as values in Django template?
I have a dictionary with lists as values (truncated to give you an example): imageFiles {'R01': ['02secparking27.jpg', '10-2017-ff-detail-1200x627.jpg', '1200x820.jpg', '12539233_web1_180704-VMS-parking-lot.jpg', '16.12.01-519196006.jpg',], 'R02': ['asdasd.jpg','12131asad.jpg','asdasdasd.jpg']} In the template, I am trying to access the image names by iterating but I am getting no values. {% for keys,values in imageFiles %} {% for x in values %} <p> {{X}} </p> {% endfor %} {% endfor %} getting error "Need 2 values to unpack in for loop; got 9." I also tried imageFiles.items as suggested in other posts and it doesn't seem to work. What am I doing wrong? Wracking my brain here. -
How to correctly write the location of the template file in settings (Django)
Issue: I cannot find the reason why the app cannot find the HTML page. I believe it`s in the way how the settings templates are coded. Possible solutions: I have tried to change the Directory of the templates files, but it didn`t change anything. views.py from django.shortcuts import render from .models import Chantier, Backup, Asset, Note, Issue from django.contrib.auth.decorators import login_required @login_required(login_url="/login/") def index_site(request): return render(request, 'chantiers/index_site.html') urls.py from django.conf.urls import include, url from django.urls import path from . import views from django.contrib import admin from django.conf import settings admin.autodiscover() from django.conf.urls.static import static app_name = 'chantiers' urlpatterns = [ url(r'^index_site$', views.index_site, name='index_site'), ] settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = Path(__file__).parent CORE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(CORE_DIR, "core/templates") # ROOT dir for templates TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls import url # add this urlpatterns = [ path('admin/', admin.site.urls), # Django admin route path("", include("authentication.urls")), # Auth routes - login / register path("", include("app.urls")), path("sites/", include("chantiers.urls")), ] In the core/templates folder, I am creating a … -
Django Add to a field in Models.py
I have this code in models.py like so: class Post(models.Model): likes = models.PositiveIntegerField(default=0) I also have this template called home.html: {% extends "blog/base.html" %} <p>Like!</p> <!-- onclick of p above, add one to likes at models.py --!> {% endblock content %} So how would I actually implement this? I want, on the click of the paragraph, to add one to the likes field in the post model. I am beginner. -
Django Update Class form (delete form imput title)
I have : class CompanyUpdateView(LoginRequiredMixin, UpdateView): model = UserCompany template_name = 'panel/admin/company.html' fields = [ "name", "phone_number", "address", "city", "region", "legal_document", ] success_url ="/panel" and HTML: <div class="col-6"> {{ form.name|as_crispy_field }} </div> and return : enter image description here How i change the input title "name" -
Django multidb with router not inserting during test
I have a multiple databases application and a DB router, but somehow insert is not working during test. here is my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__db', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'default_replica': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__db_replica', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'reporting': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__reporting', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, 'reporting_replica': { 'ENGINE': 'django.db.backends.mysql', # HOST, PORT, NAME, USER, PASSWORD 'TEST': { 'NAME': 'test__reporting_replica', 'CHARSET': 'utf8', 'COLLATION': 'utf8_general_ci', } }, } my router.py: class Router: def db_for_read(self, model, **hints): if model._meta.label_lower in settings.DB_REPORTING_MODELS: return 'reporting_replica' if model._meta.label_lower in settings.DB_FORCE_READ_MODELS: return 'default_replica' return 'default' def db_for_write(self, model, **hints): if model._meta.label_lower in settings.DB_REPORTING_MODELS: return 'reporting' return 'default' def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name is None: return None model_id = f'{app_label}.{model_name}' if db == 'reporting' and model_id in settings.DB_REPORTING_MODELS: return True elif db == 'default': return True return None my test function: def insert(): a = ModelName.objects.create(value='test') return a and my test: def test_insert(self): assert not ModelName.objects.exists() a = … -
AWS Cognito in react js with django rest framework?
I want to integrate third party authentication with AWS Cognito in my webapp. I have a React JS app with a django backend. I found this tutorial but I dont really get how this will work with an existing frontend application rather than how to implement it. if a user logs into the frontend and is authenticated via cognito (other question: is a backend in Amplify necessary?), can the token be passed to the django API - does cognito then need to be called again in django? this step is not yet completely clear to me. Any help is appreciated. Are there no examples for react + DRF? -
Loading aws s3 lamda generated files in Django
Whats working I have a Django website application form that takes an image from a user and uses django-storages to save the uploaded images to a AWS S3 bucket: <bucket>/private/images/file_name.jpg On upload, I have an AWS SNS triggered that executes a Lambda function to filter the users image and store it in the same S3 bucket <bucket>/private/filtered_images/file_name.jpg; the SNS is only triggered on the images folder in order to avoid recursive Lambda evaluations. Whats the problem I want a good way to reference the Lambda generated filtered images in my Django application. Currently, my django image model is: class Image(models.Model): title = models.CharField(max_length=200) image_owner = models.ForeignKey(image_owner, on_delete=models.CASCADE, null=True) # image owner has multiple images source_image = models.ImageField(storage=PrivateMediaStorage(), upload_to="images/", null=True, blank=True) def get_absolute_url(self): return reverse('image-detail', args=[str(self.id)]) def get_update_url(self): return reverse('image-update', args=[str(self.id)]) def get_delete_url(self): return reverse('image-delete', args=[str(self.id)]) where class PrivateMediaStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_MEDIA_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False It would be ideal if I could somehow add a filtered_image field to the Image model upon the creation of Image, even though the processing for the filtered_image would only start when source_image is uploaded (due to the nature of the s3 -> lambda trigger I have set). Is this … -
Only able to add two child objects in Django using a ModelForm and inline_formsets
I'm making a recipe application in Django. Each user has their own OneToOne RecipeBook object, which in turn can hold as many recipes as needed, as each Recipe has a ForeignKey relationship to the RecipeBook object. There are also Ingredient and Direction objects that each have a FK relationship to the Recipe object. I am trying to make a form that allows the user to create a Recipe, and then dynamically add/remove Ingredient/Direction objects as needed. I'm using Class Based Views, ModelForms, and inlineformsets_factory to accomplish this, as well as using the django-dynamic-formset jQuery plugin, and I've been following this guide. My issue is that I am only able to create two child Ingredient/Direction objects for each recipe. I want to make it so users can create as many Ingredient/Direction objects as they like. Previously I was only able to add one instance of each child object, but through some changes I don't recall, I am now able to add two. I previously thought that I would need to iterate over each object in my view to allow multiple objects, but since I can now create two I'm not sure if that is the case. So my question is, what … -
In django, what is the optimal way to access data in a OnetoMany relationship to output to template?
I'm working in django and my objective is to output to a template a table consisting of all my customers and a corresponding amount equal to the total amount they have spent. I have the classes/models Customers and Transactions with a OneToMany relationship. Every time a customer makes a purchase, the transaction is recorded as is the amount they spent (tx_amount). I have the following set a code that works but I believe is not optimal since its running in O(x * y) time, i.e., running a full loop over Transactions for every customer. Q1: What is the optimal way for accomplishing this task? When I originally tried to get my template to work, instead of using local_customer, I was using setattr(customer[x],"value",tx_amount) which worked in the django shell but did not work in the template. My workaround was to create a local class which I would use to population my context variable. Q2: When combining data models to output in a template, is it necessary to use some sort of local class like my local_customer implementation below or is there a better way? Pseudo-code below: models.py: class Customers(models.Model): name = models.CharField(max_length=70) def __str__(self): return self.name class Transactions(models.Model): customers = models.ForeignKey(Customers, … -
How do i specify a variable in side of django template file
So I am trying to declare a variable inside of my django templates file {% with object = "2" %} {% for detail in details %} {% if detail.post.id == {{object}} %} {{detail.name}} {% endif %} {% endfor %} {% endwith %} I know that with is used to this job, but when i run this code it shows me this error: 'with' expected at least one variable assignment Please help me. Thank You -
I can't seem to get a Docker-Nginx-Django app to refresh the static files
I currently have a Django website that runs on a server using Nginx an Docker. Every time I update my main css file and deploy it, nothing changes, despite hard refreshing the site. When new static files are added, they end up working, but modified files don't seem to change. This led me to believing that nginx or Docker was caching the file. I've tried the following: Clearing the cache in the nginx container, setting the lines expires -1 and sendfile off, rebuilding the containers, with no luck. The last time I had this problem, I believe I had to delete the volume for it to refresh, which I don't think is a good solution. Can someone explain what I am doing wrong? Settings: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] nginx configuration: upstream my_server { server web:80; } server { listen 80; server_name mywebsite.com; location / { proxy_pass http://my_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $Host; proxy_redirect off; return 301 https://$host$request_uri; } location /.well-known/acme-challenge/ { root /var/www/certbot; } location /static/ { alias /code/staticfiles/; expires -1; } } server { listen 443 ssl; server_name mywebsite.com; ssl_certificate /etc/letsencrypt/live/mywebsite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mywebsite.com/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; … -
Django download csv from model database
I don't know why this is so difficult but I want to download a csv file that has already been saved to my database for users to look at on their own PCs. Here are my models and views: models.py class datasheet(models.Model): file_name = models.FileField(upload_to = 'upload', max_length = 100) def __str__(self): return 'File id: {}'.format(self.id) views.py def download(request): csvfile = datasheet.objects.get(id = 1) return (csvfile as a downloaded attachment) Any ideas? -
Django Admin action different names then function names
Is possible to have action display in Django Admin with a different name than its function name? for example: def an_action(): pass class AdminPanel(admin.ModelAdmin): actions = [ an_action] In the Django admin panel an_action would display as "An action". Could I made this display something arbitrary like "Best Action Ever" instead of "An Action"? -
Django Rest Framework: changing output format of annotated field in queryset
Hello StackOverflow community, I am currently struggling with specifying an output format in my views.py. I have a column "date" which is using following format: 2021-01-14. In my response, I would like to change the date format so that it only shows the year 2021. I already tried it with Cast but it seems like this is not the right approach. For this view, I do not use a Serializer, hence adding it there would not be an option. views.py class FilterParams(generics.ListAPIView): model = Variants queryset = Variants.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min('date')).annotate(max_year=Max('date')).order_by('model') return Response(data= {'ModelsByYears':ModelsByYears}) What I tried: class FilterParams(generics.ListAPIView): model = Variants queryset = Variants.objects.all() def get(self, request, *args, **kwargs): queryset = self.get_queryset() ModelsByYears = queryset.values('model').distinct().annotate(min_year=Min(Cast('date', DateTimeField(format="%Y")))).annotate(max_year=Max('date')).order_by('model') return Response(data= {'ModelsByYears':ModelsByYears}) Error message TypeError: __init__() got an unexpected keyword argument 'format' -
Calling a django function from html button
I am new to django. What i am trying to do is to run a django function from my "main.py" file when a html button is pressed. what I've done is created a button in html: <input type="button" value="Formatting excel" onclick="excel_formatting"> And then in my "main.py " I have: def excel_formatting(): print("hello world") return() The website loads fine, but when i press the button nothing is printed in the terminal. i must be doing something wrong. -
Django refuses to parse javascript variable when creating qr code
I have been trying different ways to try to make django read the javascript variable but nothing has been working. Either it prints the variable as a string or gives me an error. I am trying to create a qr-code, I need to enter the qr-code information which is stored in a js variable. <script type="text/javascript"> const id = document.getElementById('id-input-product'); function loadPreviewProduct() { value = '"' + id.value + '"'; document.getElementById('qr-code').innerHTML = `{% qr_from_text ${value} size="t" image_format="png" error_correction="L" %}`; } </script> <div id="qr-code"> </div> -
Bootstrap toast - Data delay not respectés - Toast dont hide
After hit the submit button of a form (Ajax POST) I want to refresh the toast with the message generated in Django view. I succeed to show the message but the data-delay is not respected, the toast does not disappear after 5 sec. <div id="messages" aria-live="polite" aria-atomic="true" style="position: relative"> <div style="position: absolute; top: 12px; right: 12px;" > {% for message in messages %} <div class="toast d-flex toast-success" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000"> <div class="toast-header toast-success shadow-none" > <i class="fas fa-check"></i> </div> <div class="toast-body"> {{message}} </div> </div> {% endfor %} </div> </div> And in success part of Ajax I add $('#messages).load(location.href + " #messages>*", "")