Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework UnicodeDecodeError
Model available: photo = models.ImageField(verbose_name='Фото', upload_to='images/human/%Y/%m/%d/', default='default/user.png', blank=True) photo_200 = ImageSpecField( source='photo', processors=[ResizeToFill(200, 200)], format='JPEG', options={'quality': 80}, ) photo_272 = ImageSpecField( source='photo', processors=[ResizeToFill(272, 250)], format='JPEG', options={'quality': 80}, ) serializer: class HumanListSerializer(serializers.ModelSerializer): class Meta: model = Human fields = ( 'name', 'surname', 'middle_name', 'description', 'photo_272', 'slug' ) I get an error on photo_272 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte with picture photo everything is in order, since it is not used django rest framework -
Django MEDIA_URL and MEDIA_ROOT create a new folder /static/
I'm trying to upload an image via the Django admin, but the django admins creates a new folder static/images instead of save to existing folder static/images ''' STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') ''' -
How to return values in django-import-export ManyToManyFields
I have had headache over why my import does not include the manytomany fields with it, instead it shows none upon import .Here is my resources.py class ImportStudentsResource(resources.ModelResource): klass = fields.Field(widget= ManyToManyWidget(Klass)) stream = fields.Field(widget=ManyToManyWidget(Stream)) gender__name = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name')) school__name = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name')) class Meta: model = Students fields = ('school__name','adm','name','kcpe','klass','stream','gender__name','notes') import_id_fields = ('adm',) import_order = ('school__name','adm','name','kcpe','klass','stream','gender__name','notes') The view class UploadStudentsView(View): context = {} def get(self,request): form = NewStudentsForm() self.context['form'] = form return render(request,'upload_student.html',self.context) def post(self, request): form = NewStudentsForm(request.POST , request.FILES) data_set = Dataset() if form.is_valid(): file = request.FILES['file'] extension = file.name.split(".")[-1].lower() resource = ImportStudentsResource() if extension == 'csv': data = data_set.load(file.read().decode('utf-8'), format=extension) else: data = data_set.load(file.read(), format=extension) result = resource.import_data(data_set, dry_run=True, collect_failed_rows=False, raise_errors=True) print(result) if result.has_validation_errors() or result.has_errors(): print("error", result.invalid_rows) self.context['result'] = result return redirect('upload_students') else: result = resource.import_data(data_set, dry_run=False, raise_errors=False) self.context['result'] = None else: self.context['form'] = NewStudentsForm() return render(request, 'upload_student.html', self.context) The models. class Klass(models.Model): name = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(4),], help_text='E.g 1,2,3, 4') school = models.ForeignKey(School,on_delete=models.CASCADE) class Stream(models.Model): name = models.CharField(max_length=50,help_text='Name of the stream') klass = models.ForeignKey(Klass,on_delete=models.CASCADE,help_text='Choose a class the stream belongs to') school = models.ForeignKey(School,on_delete=models.CASCADE) And a sample of the files I'm trying to upload. It gives None in klass and … -
What is self.instance in django?
What self.instance means in the code below? Class ProfileForm(forms.ModelForm): first_name = forms.CharField(required=True) last_name = forms.CharField(required=True) interest_0 = forms.CharField(required=True) interest_1 = forms.CharField(required=True) interest_2 = forms.CharField(required=True) def save(self): Profile = self.instance Profile.first_name = self.cleaned_data[“first_name”] Profile.last_name = self.cleaned_data[“last_name”] profile.interest_set.all().delete() For i in range(3): interest = self.cleaned_data[“interest_{}”.format(i] ProfileInterest.objects.create( profile=profile, interest=interest) Here is a complete code. I already read this post, but still, I can't understand their explanation. Can you explain in the easiest way possible? -
Heroku's Django is not loading any css file
I'm practicing on django project and when I run the code in localhost everything goes well, although on heroku app deployment none of the css files are loaded even the google font. boards_app/config/settings.py INSTALLED_APPS = [ 'django.contrib.staticfiles', ] DEBUG = True STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] boards_app/static/css/app.css .navbar-brand { font-family: 'Train One', cursive; } boards_app/templates/base.html {% load static %}<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{% block title %}Django Boards{% endblock %}</title> <link href="https://fonts.googleapis.com/css2?family=Train+One&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/app.css' %}"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="{% url 'home' %}">Django Boards</a> </div> </nav> <div class="container"> <ol class="breadcrumb my-4"> {% block breadcrumb %} {% endblock %} </ol> {% block content %} {% endblock %} </div> </body> </html> localhost style loading preview live style not loaded Code on github Live preview on Heroku -
Heroku how to see logs of clock process
I recently implemented a clock process in my heroku app (Python) to scrape data into a database for me every X hours. In the script, I have a line that is supposed to send me an email when the scraping begins and again when it ends. Today was the first day that it was supposed to run at 8AM UTC, and it seems to have ran perfectly fine as the data on my site has been updated. However, I didn't receive any emails from the scraper, so I was trying to find the logs for that specific dyno to see if it hinted at why the email wasn't sent. However I am unable to see anything that even shows the process ran this morning. With the below command all I see is that the dyno process is up as of my last Heroku deploy. But there is nothing that seems to suggest it ran successfully today... even though I know it did. heroku logs --tail --dyno clock yields the following output, which corresponds to the last time I deployed my app to heroku. 2021-04-10T19:25:54.411972+00:00 heroku[clock.1]: State changed from up to starting 2021-04-10T19:25:55.283661+00:00 heroku[clock.1]: Stopping all processes with SIGTERM 2021-04-10T19:25:55.402083+00:00 heroku[clock.1]: … -
I can't find the GitHub API for extract the code of a repository
I am working with GitHub API. But I don't find any API that will help me to see and extract the different version of code. Please help me. -
How to use LIKE %a% when passing a parameter in raw sql django
I have a parameter search_query and I want to get all the objects that consist search_query using only raw sql(I know that Django has built-in functions for that) Here is my code: def search(request): cursor = connection.cursor() cursor.execute("SELECT (Lastname + ' ' + Firstname + ' ' + Patronymic) as n from Person") data = dictfetchall(cursor) search_query = request.GET.get('search','') cursor.execute("SELECT (Lastname + ' ' + Firstname + ' ' + Patronymic) as n from Person WHERE Lastname LIKE %s",[search_query]) data = dictfetchall(cursor) return render(request,'other.html',{'data':data,'search_q':search_query}) Tried to do like this WHERE Lastname LIKE %%s%, but it didn't work. Couldn't find anything in the internet(( -
values methods in django
Instead of using method all(), I want to use method values() to do an optimal search within the database, and I only want to get two fields from my model. One of my fields is related to price, which is obtained by subtracting the original price from the discount. How can I access this field inside method values. The error the project gives me: Cannot resolve keyword 'total_price' into field my model : class Product(models.Model): title = models.CharField(max_length=100) unit_price = models.IntegerField() discount = models.IntegerField() total_price = models.IntegerField() @property def total_price(self): if not self.discount: return self.unit_price elif self.discount: total = (self.discount * self.unit_price) / 100 return int(self.unit_price - total) return self.total_price my view : products = Product.objects.values('name','total_price') -
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 …