Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my cookie-navbar combo isn't working, even though I don't get errors
I have this in my view for when someone registers for an acccount: response = redirect ("/register/success") response.set_cookie('register', 'True') return response This creates a cookie so I know they are registered. Then, I have this in my navbar: <ul> <li class="all"><a href="/">All videos</a></li> <li class="stam"><a href="/stam">Stam videos</a></li> <li class="music"><a href="/music">Music videos</a></li> <li class="news"><a href="/news">News videos</a></li> <li class="contact"><a href="/contact">Contact</a></li> {% if user.is_authenticated %} <li class="logout"><a href="/logout">Logout</a></li> {% elif request.COOKIE.register == 'True' and user.is_authenticated == 'False' %} <li class="login"><a href="/login">Login</a></li> {% else %} <li class="register"><a href="/register">Register</a></li> {% endif %} </ul> Basically, if the user is logged in shows 'logout' in the navbar (this works), if they are logged out it shows 'register', and if they are logged out and have the 'register' cookie it says 'login'. However, this last one doesn't work, and I don't know why, because I don't get any errors in relation to making a cookie when I make an account, but eveen after I make an account and logout it doesn't show 'login'. Here is my full register view: from django import forms from django.shortcuts import render, redirect from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.core.mail import send_mail from django.contrib.auth import authenticate, login CARRIER_CHOICES =( ('@txt.freedommobile.ca', … -
It gives an error when I try to update multiple images in django
I get an error editing product models when I want to edit photos related to each product. please help. I'm sorry my English is not good :) this error msg: AttributeError at /account/villa/update/13 'PhotoVillaForm' object has no attribute 'cleaned_data' Update View: def VillaEdit(request, pk): villa = get_object_or_404(Villa, id=pk) ImageFormset = modelformset_factory(PhotoVilla, fields=('photo',), extra=4) if request.method == "POST": form = VillaEditForm(request.POST or None, instance=villa) formset = ImageFormset(request.POST or None, request.FILES or None) if form.is_valid() or formset.is_valid(): form.save() data = PhotoVilla.objects.filter(id_villa=pk) for index, f in enumerate(formset): if f.cleaned_data: if f.cleaned_data['id'] is None: photo = PhotoVilla(villa=villa, photo=f.cleaned_data.get('photo')) photo.save() elif f.cleaned_data['photo'] is False: photo = PhotoVilla.objects.get(id=request.POST.get('form-' + str(index) + '-id')) photo.delete() else: photo = PhotoVilla(id_villa=villa, photo=f.cleaned_data.get('photo')) d = PhotoVilla.objects.get(id=data[index].id) d.photo = photo.photo d.save() return HttpResponseRedirect(villa.get_absolute_url()) else: form = VillaEditForm(instance=villa) formset = ImageFormset(queryset=PhotoVilla.objects.filter(id_villa=pk)) content = { 'form': form, 'villa': villa, 'formset': formset, } return render(request, 'registration/villa-update.html', content) forms.py file: class VillaEditForm(forms.ModelForm): category = forms.ModelChoiceField(queryset=Category.objects.filter(typeWodden='v')) class Meta: model = Villa fields = ["category", "code", "title", "duration", "thumbnail", "status", "service", "bed", "area"] template file html : <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="card-body"> <div class="form-group"> {{ form.title|as_crispy_field }} </div> {{ formset.management_form }} {% for f in formset %} <div style="background-color: #f2f4f4; margin: 5px; padding: 5px; width: … -
No posts on my Blog page on Heroku, problem with database(?)
At the start i must say that i'm complete beginner. I use django. I pushed my blog page on heroku, but its completly empty, there are no posts. It should look somehow like on the picture. Right now there is only Banner with quote, title "Lastest Post" and button to add new posts. I made a mistake before, because i changed an appname on heroku settings page, and migrated database to an old appname in cmd. I changed appname in cmd right after this, and tried to reset database. Then migrated database again but nothing changed. Tried also to restart dynos etc. I don't know what else kind of information should i tell you guys. There are also no posts when i login to admin page -
memcache on django not working when deploy project
my project memcache works properly in development state but not work when deploy project. What is the reason for this? What location should I put? What code should I change to solve this problem? also did pip install python-memcached What am I doing wrong? Any help will be appreciated. ---------- # settings for memcache: when development : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '127.0.0.1:11211', ] } } when deploy project: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '185.208.182.254:11211', ] } } ------------- my view: @cache_page(60 * 15) def my_view(request): ... -
Django - How to decode a base64url and render it in Django template
In my view function, I am sending a form to an endpoint then I receive a response in JSON. The response is then displayed on the template after the form has been submitted. The problem is that a key in the response is a photo that is encoded in base64url. e.g: {"photo": "a very long base64url"} What I want to achieve is to decode that base64url and render the image on the webpage. Here's my view function: def post_nin(request): if request.method == 'POST': form = NINPostForm(request.POST) if form.is_valid(): nin = form.cleaned_data['nin'] url = request.build_absolute_uri(reverse_lazy('nin_verification', kwargs={'nin': nin}, )) r = requests.get(url=url) resp = r.text resp_json = json.loads(resp) resp_list = resp_json['data'] # [{'tracking_id':12345, 'photo':'base64url'}] return render(request, 'ninsuccess.html', {'response': resp_list}) else: form = NINPostForm() context = {'form': form, } return render(request, 'ninform.html', context) Here is my template: <table class=""> <thead> <tr> <th>Tracking ID</th> <th>Picture</th> </tr> </thead> <tbody> {% for val in response %} <tr> <td>{{ val.tracking_id }}</td> <td>{{ val.photo }}</td> # a long base64url is displayed which is not what I want </tr> {% endfor %} -
Caching - Django rest framework
Use Case For example, an applicaton is data intensive, it has to show lot of data on frontend like feed, trending things, profiles etc. And all these data depend upon location Suppose, I have GetMyFeed API, the way I am Doing caching is :- I am caching the queryset I am taking cache key as API payload, because depending on it queryset will be formed. Cache key is API payload. Cache value is queryset ISSUE , I AM FACING IS:- Changes on Database will be in Large amount per second, so to invalidate the cache, I have to clear the whole cache. But I don't think it is the right way of doing cache invalidation. How can I update a single instance in list of objects which is cache value? And the main problem is single instance can be present in multiple queryset. So How will I update each copy of instance, which is present in different queryset, in cache? -
Modelform not saving data even tho it is being executed
The other posts that have this same question didnt actually help me so i decided to ask, problem is a little weird. Bcs the form.save command is being executed, at least i think but when i take a look at my db by the admin page, it doesnt work, and i dont know y, interesting enough the data is displayed in the print and the sucess message is displayed, if any extra information is needed i will gladly give it. Here it is the base model class DadoDB(models.Model): marca=models.CharField(max_length = 30, default ="ACURA") modelo=models.CharField(max_length = 30, default="XWZ") ano=models.IntegerField(default= 2021) status=models.CharField(max_length= 10,default= "BOM") cor=models.CharField(max_length= 10, default= "VERMELHO") combustivel=models.CharField(max_length= 10,default= "FLEX") quilometragem=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) lucro=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) preco=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) margem_de_lucro=models.DecimalField(max_digits= 10,decimal_places=2,max_length= 12,default=100) data_postada = models.DateTimeField(default=timezone.now) autor= models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'{self.user.username} Empresa' Here it is the base form from django import forms from .models import DadoDB class InsiraDadosForm(forms.ModelForm): class Meta: model = DadoDB ['marca','modelo','ano','status','cor','combustivel'.... Here is the view @login_required def InserirDado(request): if request.method == 'POST': form = InsiraDadosForm(request.POST,instance= request.user) if form.is_valid(): form.save() print(request.POST) messages.success(request, f'Seus dados foram inseridos com sucesso!') return redirect('dado-InserirDado') else: form = InsiraDadosForm() return render(request, 'dado/inserirdado.html', {'form': form}) -
Django db foreign keys return 2 diffirent types
In MySQL I have 3 tables: Client, Room and ClientRoom,which points on two previous tables. -- ----------------------------------------------------- -- Table `client` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `client` ( `id` INT NOT NULL, `name` VARCHAR(255) NULL, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; -- ----------------------------------------------------- -- Table `room` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `room` ( `id` INT NOT NULL, `price` DECIMAL(18,2) NOT NULL, `apart_num` INT NOT NULL, `free` BOOL default TRUE, PRIMARY KEY (`id`) ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; -- ----------------------------------------------------- -- Table `client-room` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `client_room` ( `id` INT PRIMARY KEY AUTO_INCREMENT, `client_id` INT NOT NULL, `room_id` INT NOT NULL, `date_in` DATETIME NOT NULL, `date_out` DATETIME NOT NULL, INDEX `fk_client_room_idx` (`client_id` ASC), CONSTRAINT `fk_client_room_id` FOREIGN KEY (`client_id`) REFERENCES `client` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, INDEX `fk_room_idx` (`room_id` ASC), CONSTRAINT `fk_room_id` FOREIGN KEY (`room_id`) REFERENCES `room` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; Using python manage.py inspectdb i got class Client(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, blank=True, null=True) class … -
django migrations does not update database
I have django app already online and running. I created new model and if I do the makemigrations, it is working fine, but if I want to migrate it, then I receive Running migrations:No migrations to apply. Even though that I made a change. The change is also in the migration file. I am using postgresql with it. I tried to delete the migration file and create it once more, but it did not help. Any idea what might be wrong? -
How to host django script on a rdp (and add domain name)
How to Host my djanogo script on my RDP with my custom domain from hostinger. -
Does django 3.2 support mongodb?
I found no folder at django package's database folder like other database folder such as like mysql,sqlite etc. -
Django app won't save new data(URL) on server herokuapp
**I'm new into this so THANKS FOR ANY HELP!** The app doesn't display any errors or smth similar on the website that is wrong. When I start the app locally it works without any trouble. The app needs just to submit new links and update the prices on the product. This is the link from the app that is up from locally to server. Do I need to change the server? https://wantdeedpricee.herokuapp.com/ **this is the views.py code:** form = AddLinkForm(request.POST or None) if request.method == 'POST': try: if form.is_valid(): form.save() except AttributeError: error = "Uopa...ne mogu dohvatit ime ili cijenu" except: error = "Uopa...nesto je poslo po krivu" form = AddLinkForm() qs = Link.objects.all() items_no = qs.count() if items_no > 0: discount_list = [] for item in qs: if item.old_price > item.current_price: discount_list.append(item) no_discounted = len(discount_list) context = { 'qs' : qs, 'items_no' : items_no, 'no_discounted' : no_discounted, 'form' : form, 'error' : error, } return render(request, 'links/main.html', context) **and this is the models.py** maybe I'm doing smth wrong with the save option? def __str__(self): return str(self.name) class Meta: ordering = ('price_difference', '-created') def save(self, *args, **kwargs): name, price = get_link_data(self.url) old_price = self.current_price if self.current_price: if price != old_price: … -
Access to localhost was denied You don't have authorization to view this page. HTTP ERROR 403 in Django
This is the error I am getting when I click on submit button from django.conf.urls import url,include from django.urls import path,re_path from . import views app_name = 'challengeide' urlpatterns = [ path('challengeide/<int:sr_no>', views.show, name='show'), url('challengeide/', views.qtn,name='test'), path('#', views.submit_button,name='submit_button'), url('challenge/', views.challengeide, name='challengeide'), ] This is my URL code <form method="POST" action="{% url 'challengeide:submit_button' %}" name="mybtn123">{% csrf_token %} <button style="float: right;" class="btn btn-success" data-toggle="tooltip" data-placement="top" style="margin-left: auto;">Submit</button> </form> This is my HTML code where there is submit button to submit a given function to the database def submit_button(request): question_desc = Challenge_Detail.objects.get(id = 1) for i in range(1,3): if (i==1): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] data = { 'client_secret': 'secret key' , 'async': 0, 'source': source, 'lang': lang, 'time_limit': 5, 'memory_limit': 262144, } x = str(i1) i1 = x.replace("qwe","\n") data['input'] = i1 ''' if 'input' in request.POST: data['input'] = request.POST['input']''' r = requests.post(RUN_URL, data=data) temp =(r.json().copy()) print(temp) print(data) global out_returned if(temp["run_status"]["status"]!="CE"): out_returned = temp['run_status']["output"] time=time+float(temp['run_status']['time_used']) space=space+int(temp['run_status']['memory_used']) e = temp['compile_status'] print(e) compare(out_returned,e1) print(e1) print(out_returned) else: error = (temp["compile_status"]) print(error) ex = {"Problem" :error} print(type(ex)) print(ex) return JsonResponse(r.json(), safe=False) else: return HttpResponseForbidden() if (i==2): if request.is_ajax(): source = request.POST['source'] lang = request.POST['lang'] x = str(i2) i2 = x.replace("qwe","\n") data['input'] = i2 ''' … -
Access time control system for exams in Django-based online examination platform
I am a beginner in Django. Trying to create an online exam platform and prefer to use Bootstrap based frontend. Now I am very confused about the right way to implement the time inspection system for any test. Here, the time inspection system means, suppose that an experiment called "Bose Memorial 2nd Science Fest" will be held on 02-05-2021 at 8:30 am and the duration of the examination is 2 hours. Now my problem is, how can I ensure that the examinee can only enter the exam on 02-05-2021 from 8:30 am to 10:30 am? How can I implement a dynamic countdown timer on the question paper page so that the examinee can see the time limit? I know my problem is not directly code/error based. And it has a variety of solution strategies. So, you do not need to provide the full code. Please just give me some references or suggest some way so I can learn it by looking at the reference myself. -
problem with receiving emails with Django
i have a simple contact Page in my Django App that receive emails when user submit the form but when i check my Gmail it shows that i received email from my email, like i sent email from my email to myself Here is my views.py: def Contact(request): form=ContactForm(request.POST or None) if form.is_valid(): email=form.cleaned_data["email"] subject=form.cleaned_data["subject"] message=form.cleaned_data["message"] send_mail( subject, message, settings.EMAIL_HOST_USER, [email], fail_silently=False, ) messages.success(request,"your message has been sent successfully") context={"form":form} return render(request,"contact.html",context) and here is my settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = '**********' EMAIL_HOST_PASSWORD = '*********' EMAIL_USE_TLS = True EMAIL_USE_SSL= False EMAIL_PORT = '587' but when i check my Gmail it shows that i received email from my email, like i sent email from my email to myself -
How to make button to change CSS permanent between hrefs?
On my main base_generic.html I have put a button to change between two css. {% load static %} <link rel="stylesheet" type="text/css" href='{% static '/css/style.css' %}?{% now "U" %}'> <script> function toggleTheme() { var theme = document.getElementsByTagName('link')[0]; if (theme.getAttribute('href') == '{% static '/css/style.css' %}?{% now "U" %}') { theme.setAttribute('href', '{% static '/css/style_access.css' %}?{% now "U" %}'); } else { theme.setAttribute('href', '{% static '/css/style.css' %}?{% now "U" %}'); } } </script> <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>Title to change</title>{% endblock %} </head> <body> Accessibility switch:<br /> <button onclick="toggleTheme()">Switch</button> <br/> {% block sidebar %}<!-- insert default navigation text for every page -->{% endblock %} {% block content %}<!-- default content text (typically empty) -->{% endblock %} </body> </html> And it works fine, but when you chance css and click href to another url, it goes back to default css. How can I make it work, so if one person click the change button, then css is persistent? F.e. if I click 'switch css' button on login page it switches is to second css, but once I am logged in (and href'fed to different url), it goes back every page to original one. I would like it to work in a … -
problem in django:unable to create process
I installed django successfully and created a new project with the command: .\django-admin startproject myproject It worked fine but when I try to run the server via the command: py manage.py runserver it throws an error telling me "unable to create process using 'C:\Users\Apanoup Edward\AppData\Local\Microsoft\WindowsApps\python.exe manage.py runserver' " I have python 3.9 installed and django 3.2 as well what is the issue .. can any one please help? -
Django can't to open shape_predictor_68_face_landmarks.dat. RuntimeError: Unable to open shape_predictor_68_face_landmarks.dat
My Django application can't open a shape_predictor_68_face_landmarks.dat in views. But in simpy .py file this code works. Please help to solve this problem. I have tried to use a threads and asycno, but it is doesn't work. class Main(View): def post(self, request): images = Images.objects.all() image = request.FILES.get('image') name = request.POST.get('name') if not image and not name: # images = Images.objects.all() return render(request, 'find_photo/main.html', context={'images': images, 'result': True, }) group = Groups.objects.create(photo=image, title=name,) find_photos("../" + group.photo.url) # x = threading.Thread(target=find_photos, args=("../" + group.photo.url,)) # x.setDaemon(True) # x.start() # # print(x.is_alive()) # mypath = '/find_photos/' # onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] # # for file in onlyfiles: # print(file) # group.find_images.add(file) # group.save() return render(request, 'find_photo/main.html', context={'images': images, }) find_photos function: def find_photos(image): sp = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") face_rec = dlib.face_recognition_model_v1('dlib_face_recognition_resnet_model_v1.dat') detector = dlib.get_frontal_face_detector() min_distance = 2 f1 = get_face_descriptors(image, sp, face_rec, detector)[0] files = getfilelist(dirpath) flag = 0 for f in files: flag = flag + 1 print('Анализ ' + f + ' - ' + str(flag) + ' фото из ' + str(vsego)) if os.path.exists(f): try: findfaces = get_face_descriptors(f) print('На фото: ' + str(len(findfaces)) + ' лиц') for f2 in findfaces: if (f2 != []): euc_distance … -
Multiply two fields in django
I have two different models class Part(models.Model): partno = models.CharField(max_length=50) price = models.PositiveIntegerField(default= 0) tax = models.PositiveIntegerField(default= 0) created_date = models.DateField(auto_now_add=True) class PurchaseOrder(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) po_quantity = models.PositiveIntegerField(default= 0) amount = models.PositiveIntegerField(default= 0) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) I'd like to multiply price from Part with po_quantity and result show in the amount. e.g amount = price * po_quantity Can someone assist me to solve this? -
receive pdf from an api instead of pdf in unicode format Python/Django
I have a problem when consuming an API that returns a pdf to me, said pdf is returning it to me I think in unicode format, the point is that I can't make it simply return the normal pdf, that is, put it in some view or method so that a normal pdf is simply downloaded to the client, I don't know if I explain it well def volante_individual_empadronamiento(request): if request.method == 'POST': document_identity = request.POST.get('identification') url = f"https://pre-interpublicaapi.interpublica.es/api/padron/volanteindemppdf?filtros[0].Nombre=NumDocumento&filtros[0].Valor={document_identity}&filtros[1].Nombre=TipoPlantillaPadron&filtros[1].Valor=10" token_value = access_token() print(token_value) payload={} headers = { 'Authorization': f'Bearer {token_value}' } response = requests.request("GET", url, headers=headers, data=payload) volante_individual = response.text print(volante_individual) return render(request, 'volante_individual_empadronamiento.html') -
Django raise ValidationException on id field when testing abstract model
I have an abstract django model like this: from django.db import models class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True When testing this class using following code: from django.test import TestCase from django.db import models from core.models import BaseModel class BaseModelTest(TestCase): def test_1(self): class SimpleClass(BaseModel): name = models.CharField(max_length=10) simple = SimpleClass(name="test") simple.save() simple.full_clean() ... I get following error: django.core.exceptions.ValidationError: {'id': ['“6072d8ce3c23022d0694ae8e” value must be an integer.']} I'm using mongodb as my database. There is no such error when I delete abstract = True. -
Django 2FA works locally but fails (silently) on server
The Problem I need to implement two factor authentication for a Django project. I am using Django Two-Factor Authentication which works just fine locally both with Google Authenticator and our own SMS gateway. The issue occurs when I publish the app to the test server. The login works as normal but when I fill inn the token it will simply redirect me back to the initial login step to fill inn my credentials again. It does not give me any error messages in the ui and, as far as I can see, none in the logs either. Don't know if it's relevant but the app is running as a Docker Swarm service on the server. What I have tried Due to the lack of feedback and knowledge of the 2FA library as well as the OTP-library I don't really know where to start. I'm pretty sure the settings are as good as identical between my local machine and the test environment. The package version are the same. I even made sure the time and timezones are identical between my machine and the server. Looking in the database in the tables for the OTP library the failure count is 0 and … -
Pass variable value to form field
How can I pass the value of a variable to the value attribute of a field in my form? I have tried overriding the init method but I can't get it to work. This is my code. models.py: class Profile(models.Model): user = models.OneToOneField(UserManegement, related_name='user', on_delete=models.CASCADE) avatar = models.ImageField(upload_to=custom_upload_to, null=True, blank=True) first_name = models.TextField(user, null=True, blank=True) last_name = models.TextField(user, null=True, blank=True) phone = models.TextField(user, null=True, blank=True) forms.py: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar', 'first_name','last_name', 'phone'] widgets = { 'avatar': forms.ClearableFileInput(attrs={'class': 'form-control-file mt-3'}), 'first_name': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder': 'Nombre'}), 'last_name': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder': 'Apellidos'}), 'phone': forms.TextInput(attrs={'class': 'form-control mt-3', 'placeholder':'Teléfono'}), } In this case, I would like to add the first time the form is loaded, the first_name field with the value of request.user.first_name. Thank you very much! -
passing data to JavaScript via python
I wanted to make my first frontend project by making a website which can take some inputs e.g. ticker symbol, interval, period and observation. after you give the website these inputs it would need data from a python file which scrapes the data from yahoo finance after it got the data I want it to send it to my JavaScript file which I use to generate the graph. I then want the js file to send the graph to my website which can show the client data about the stock My problem is that I don't understand how all these files can communicate. Here is all my code: python: import pandas as pd import yfinance as yf import matplotlib.pyplot as plt def stock_data(stock, period, interval, observation): ticker = yf.Ticker(stock) ticker_history = ticker.history(period, interval) sf = ticker_history[observation] df = pd.DataFrame({'Date':sf.index, 'Values':sf.values}) x = df['Date'].tolist() y = df['Values'].tolist() HTML: <html> <head> <link rel="stylesheet" href="style.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.0.2/helpers.esm.min.js"></script> </head> <body> <div class="options"> <div> <select> <option value="Period">Period</option> <option value="1 day">1 day</option> <option value="5 days">5 days</option> <option value="1 month">1 month</option> <option value="2 month">2 month</option> <option value="3 month">3 month</option> <option value="6 month">6 month</option> <option value="1 year">1 year</option> <option value="2 years">2 years</option> <option value="5 years">5 years</option> <option value="10 … -
Django messages + bootstrap toast. How to make it work?
Trying to get bootstrap popup and django messages to work. The problem is that I do not understand how to do it correctly so that if there is a message in the context, it would be displayed in the upper right part of the site. Documentation: https://getbootstrap.com/docs/4.3/components/toasts/ Django v3.1.6 and Bootstrap v4.5 In the static files of the project there is bootstrap.bundle.js, it is also included in the base template. I'm not good at django in layout, so I will be very grateful for the most detailed answer.