Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set initial object in ModelChoiceField of Django form in the FormView
I have a Django Model, ModelForm and a FormView. When the user enters the view it will get the current slug and use that slug to do a query of company objects. Then I want in my form to select the specific company in the form and select it automatically. Model: class Company(models.Model): """ Model for a Company. """ name = models.CharField(verbose_name=_('Company Name'), max_length=255) slug = models.SlugField(unique=True) ModelForm: class ApplicationForm(ModelForm): """ ModelForm for an Application """ class Meta: model = Application fields = '__all__' exclude = ['slug'] The form field is of type ModelChoiceField. This is my FormView: class ApplicationView(FormView): """ FormView that are displaying the ApplicationForm """ template_name = 'application.html' form_class = ApplicationForm success_url = '/' def get_form(self, *args, **kwargs): form = super().get_form(*args, **kwargs) slug = self.kwargs['slug'] company = Company.objects.get(slug=slug) form.fields['company'].initial = company return form But this code above does not work to select the object of the current company. It only shows me "--------". Why and how can it be solved? -
/.platform/hooks/': No such file or directory when deploying Django App to AWS Elastic Beanstalk
I am trying to deploy a Django app to AWS ElasticBeanStalk. I followed all the guides in the marked correct answer but I still get the below error: [INFO] -----------------------Command Output----------------------- [INFO] find: '/.platform/hooks/': No such file or directory [INFO] ------------------------------------------------------------ As I used windows OS, I created my .sh file from https://cocalc.com/ online console. I also zipped the files and used the EBS console to deploy to avoid my files being converted during git add/commit. My config file in .ebextension content is: container_commands: 01_sh_executable: command: "chmod +x .platform/hooks/predeploy/01_execute.sh" My 01_execute.sh file content is: #!/bin/bash source /var/app/venv/*/bin/activate cd /var/app/staging python manage.py makemigrations python manage.py migrate python manage.py createsu python manage.py collectstatic --noinp The platform chosen is Python 3.7 running on 64bit Amazon Linux 2. I also noticed that when I run eb ssh and type ls, it returns blank. Linux is not one of my strength. Any help will be highly appreciated. -
Can anyone help to explain difference between django middleware and wsgi middleware
Can anyone help to explain difference between django middleware and wsgi middleware? Many thanks! -
Modified django.contrib.auth.middleware.AuthenticationMiddleware
Modify Get_User so that it does not generate an error when there is a request without a token then I need that it does not generate me the error of token if not that it takes me to the sight which already parameterized him those permissions. def get_user(request): """ Return the user model instance associated with the given request session. If no user is retrieved, return an instance of `AnonymousUser`. """ from .models import AnonymousUser user = None try: user_id = _get_user_session_key(request) backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) # Verify the session if hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: if not ( session_hash and hasattr(user, '_legacy_get_session_auth_hash') and constant_time_compare(session_hash, user._legacy_get_session_auth_hash()) ): request.session.flush() user = None return user or AnonymousUser() -
(Wagtail) Field defines a relation with model 'wagtailimages.Images', which is either not installed, or is abstract
I'm having an issue with Wagtail/Django. I have the file app/models/abstract_card_snippet.py which contains: from django.db import models from wagtail.admin.edit_handlers import FieldPanel from wagtail.documents.edit_handlers import DocumentChooserPanel # Abstract Card Snippet class AbstractCardSnippet(models.Model): title = models.CharField(max_length=255) text = models.CharField(max_length=255, null=True, blank=True) url = models.URLField(max_length=255, null=True, blank=True,) image = models.ForeignKey( 'wagtailimages.Images', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('title'), FieldPanel('text'), FieldPanel('url'), ImageChooserPanel('image'), ] def __str__(self): return '{}'.format(self.title) class Meta: abstract = True Then in app/models/generic_card_snippet.py is: from wagtail.snippets.models import register_snippet from .abstract_card_snippet import AbstractCardSnippet @register_snippet class GenericCard(AbstractCardSnippet): pass But when I run the project or try to make migrations this error comes up: web_1 | Exception in thread django-main-thread: web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner web_1 | self.run() web_1 | File "/usr/local/lib/python3.6/threading.py", line 864, in run web_1 | self._target(*self._args, **self._kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper web_1 | fn(*args, **kwargs) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run web_1 | self.check(display_num_errors=True) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 436, in check web_1 | raise SystemCheckError(msg) web_1 | django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: web_1 | web_1 | ERRORS: web_1 | app_snippets.GenericCard.image: (fields.E300) Field defines a relation with model 'wagtailimages.Images', which is either … -
Website Peer to Peer Chat API Recommendations
TL;DR I need to create a platform where people can message each other on a website, what API's are there that can do this easily? From my research so far, I have come across TalkJS, but this seems to be very expensive ($249 per month) are there any other tools that will allow me to easily implement peer to peer chat on my website that are cheaper or preferably free? My website is currently written using Django (Python) TalkJs: https://talkjs.com/ -
I cannot implement DJANGO REST API with REACT
I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed. Please see the code below. REACT Home.js (this is the code for products) const loadAllProducts = () => { getProducts() .then((data) => { if(data.error) { setError(data.error); //box filled with data error console.log(error); // message "error" } else { setProducts(data); // box filled with data product } }); loadAllProducts(); }; coreapicalls.js (here I want to fetch the data) import { API } from "../../backend.js"; export const getProducts = () => { return fetch(`${API}product`, { method: "GET" }) .then(response => response.json()) .catch((err) => console.log(err)); }; .env (I have both of my servers running, the url and symbol "/" are correct.) REACT_APP_BACKEND = http://localhost:8000/api/ My compiler returns no specific error. ./src/core/Home.js Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars ./src/core/Card.js Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/) 'api', 'api.category', 'api.product', Best, Rok. -
Page not found error when trying to load template from Link in mail
Hi All i've implemented sendgrid mail for my newsletter app in django, in which mail is send to user for confirming the subscription, but when i'm trying to click on link mail, it's throwing me error 404. I know that it's not able to find the url but what i'm not getting is how to create url for this. Adding code for ref: HTML: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 align="center">You have subscribed for Newsletter</h1> <p>Thank you for signing up for my email newsletter! Please complete the process by \ <a href="{{ redirect_url }} ?conf='{{ conf }}'"> clicking here to \ confirm your registration</a></p> </body> </html> views.py: def home(request): # Rendering Home page and Handling of Newsletter if request.method == 'POST': subscriber_mail = request.POST['email'] conf_num = random_digits() # checking if subscriber already exist check_subscriber = Subscribers.objects.filter(subscriber_mail=subscriber_mail) if not check_subscriber: sub = Subscribers(subscriber_mail=request.POST['email'], conf_num=random_digits()) sub.save() redirect_url = request.build_absolute_uri('/confirm/') message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.subscriber_mail, subject='Newsletter Confirmation', html_content= get_template('frontend/newsletter_subscribed.html').render({ 'redirect_url': redirect_url, 'conf': sub.conf_num})) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return render(request, 'frontend/index.html', {'email': sub.subscriber_mail, 'action': 'added', 'form': SubscriberForm()}) else: return render(request, 'frontend/index.html', {'form': SubscriberForm(), 'messages':'You are already subscribed for newsletter.'}) else: return render(request, 'frontend/index.html', … -
Deploying django blog with heroku
I just finished writing a blog app with django which works perfectly locally but on deploying, I'm getting this error ProgrammingError at / relation "posts_post" does not exist LINE 1: ...evious_post_id", "posts_post"."next_post_id" FROM "posts_pos... Please what can I do to resolve this? -
Error while importing data with foreign keys in django import-export
I have implemented importing data using django import-export library. When i try to import data with names of object that do not exists it throws error matching query does not exist. It ends with generating template with error stack trace like this: Line number: 1 - CustomUser matching query does not exist. sample@sample.com, data1, firstname, secondname Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 520, in import_row self.import_obj(instance, row, dry_run) File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 385, in import_obj self.import_field(field, obj, data) File "/usr/local/lib/python3.7/site-packages/import_export/resources.py", line 368, in import_field field.save(obj, data, is_m2m) File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 110, in save cleaned = self.clean(data) File "/usr/local/lib/python3.7/site-packages/import_export/fields.py", line 66, in clean value = self.widget.clean(value, row=data) File "/usr/local/lib/python3.7/site-packages/import_export/widgets.py", line 364, in clean return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val}) File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 408, in get self.model._meta.object_name accounts.models.CustomUser.DoesNotExist: CustomUser matching query does not exist. Custom resouce import class: class UserResourceImport(resources.ModelResource): """ Resource class for import utilities """ # set foreign key relations for model, this way we can provide name instead of id custom_user = fields.Field(column_name='year_group', attribute='year_group', widget=ForeignKeyWidget(CustomUser, 'name')) class Meta: model = user_model fields = ('email','custom_user','first_name','last_name') skip_unchanged = False report_skipped = True export_order = ('email', 'custom_user', 'first_name', 'last_name') import_id_fields = ['email'] Every other error of importing will result in generation … -
Javascript variables use in Django Models
I have created a sign up with google authentication system in which I'm getting info of user by a javascript variable . I want to create a django model in which the fields should use the info from javascript function. Here is code of javascript function : function onSignIn(googleUser) { console.log("success"); var profile = googleUser.getBasicProfile(); console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead. console.log('Name: ' + profile.getName()); console.log('Image URL: ' + profile.getImageUrl()); console.log('Email: ' + profile.getEmail()); // This is null if the 'email' scope is not present. location.replace("http://localhost:8000/faculty"); } -
How to fetch cert data (certificate file location) from request object in Django?
How can i fetch data of verify and cert paramater from request object. I have made a request to a url where my django backend deployed url = "https://www.example.com/" cert = "PathToPemFile" verify = "PathToCertFile" I made a request req = request.post(url, post_data, headers=header_dict, cert=cert, verify=verify) Now At Backend of www.example.com Class CertificateView(APIVIEW): def post(self, request, *args, **kwargs): get_cert_location = request.cert AttributeError: request object does not have an attribute cert How can i get the data of cert and verify in my post function from request object. -
How to properly add multi choice field to existing form in Django?
just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False -
compatability of postgres and ms sql in django orm
guys. Our team have an issue, we are developing our django app on linux server with postgres, but in production we will need to use windows and MS SQL (don't say that bad idea, I know already. but we don't have other choice). Should we expect big problems when we transfer that app to windows and MsSQL stack ? Please write about your experience in such tasks if you did smth like that. -
Converting SQL to Django ORM query ("IF" statement inside of a "Window" inside of a "Lead" function)
I am trying to get the date of the next customer that started using a service and append that date to the previous customer. I was trying to wrap my head around how F() and Q() along with SQL-like functions work in Django, but couldn't wrap my head around how to convert the following SQL statement into valid Django code: SELECT *, LEAD( IF(actual_start IS NOT NULL, actual_start, planned_start) , 1) OVER( PARTITION BY customer ORDER BY actual_start, planned_start ) AS next_starting_time FROM builds_build; I tried mashing together some things that I saw: window = { "partition_by": [F('customer')], 'order_by': [F('actual_start'),F('planned_start')] } records = Record.objects.annotate( next_customer = Window( expression = Lead(F('actual_start') if F('actual_start') else F('planned_start'), **window) ) ) but, looking at the query, the conditional part of the LEAD expression was not taken into account (this is what the Django generated SQL looks like): SELECT *, LEAD(actual_start, 1) OVER( PARTITION BY customer ORDER BY actual_start, planned_start ) AS next_starting_time FROM builds_build; however, it is completely removing the intended "IF" statement. Any tips and thoughts would be highly appreciated -
Django auto_now_add adding default server time value
When i am creating a new Log object i want a created_at value with 'auto_now_add' but when i am creating it always saves with a default time. For example a log created at 2020-09-16 18:03 but when i check it it shows 2020-09-16 18:03. My models.py: class Log(models.Model): status = models.CharField(max_length=10) time_stamp = models.DateTimeField(auto_now_add=True) device = models.ForeignKey(Device, on_delete=models.CASCADE) My settings.py: TIME_ZONE = 'Europe/Istanbul' DATETIME_FORMAT = 'Y-m-d H:m' USE_I18N = True USE_L10N = False USE_TZ = False -
Altering filepath after deployment to Heroku
My app is for students who provide their ID CNIC to get their certificates. A function download in views.py needs to access an image (which is a blank certificate) modify it by adding name and graduation date associated with cnic save it as pdf make it available for download All works in development on localhost but when deployed to Heroku, the filepath to the image does not exist, which makes sense because the app is not local anymore - it accessible to anyone. The question is, how do we find the new path to access Certificate_0001.jpg which was initially stored in certificates\static\certificates Views.py def download (request, date, name): x = date.split(" ") date = f"29 {x[3]} {x[4]}" try: image = Image.open("certificates\static\certificates\Certificate_0001.jpg") except: return HttpResponse ("image did not load") font_type = ImageFont.truetype('arial.ttf', 70) font_type_2 = ImageFont.truetype('arial.ttf', 35) draw = ImageDraw.Draw(image) draw.text(xy=(600, 740), text=name, fill=(0,102,0), font=font_type) draw.text (xy=(330, 1230), text=date, fill=(0,102,0), font=font_type_2) try: image.save(f'certificates\static\certificates\{name}.pdf', "PDF", resolution=100.0) except: return HttpResponse("pdf did not save") try: with open(f'certificates\static\certificates\{name}.pdf', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline;filename=NFDP-{name}.pdf' return response except: return HttpResponse("pdf did not load") Settings.py import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware' … -
Why am I getting the "object has no attribute" exception in Django Rest Framework?
I hope someone can help me with this problem. I am getting the following exception: Got AttributeError when attempting to get a value for field identity_document on serializer NaturalProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the NaturalProfileModel instance. Original exception text was: 'NaturalProfileModel' object has no attribute 'identity_document'. This is my code: models.py class IDTypeModel(models.Model): id_type_desc = models.CharField( null = False, blank = False, max_length = 50 ) class IDModel(models.Model): user_profile = models.ForeignKey( "NaturalProfileModel", on_delete = models.CASCADE, verbose_name = "Perfil de usuario" ) id_type = models.ForeignKey( "IDTypeModel", on_delete = models.CASCADE ) id_number = models.CharField( max_length = 15, null = False, blank = False ) class NaturalProfileModel(models.Model): user = models.OneToOneField( get_user_model(), on_delete = models.CASCADE ) first_name = models.CharField( max_length = 50, null = False, blank = False ) last_name = models.CharField( max_length = 50, null = False, blank = False ) serializers.py class IDSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='natural_profile_id-detail' ) class Meta(): model = IDModel fields = [ 'url', 'id_type', 'id_number', ] class NaturalProfileSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='natural_profile-detail' ) identity_document = IDSerializer(required = True, many = True) class Meta(): model = NaturalProfileModel fields = [ 'url', 'user', 'first_name', 'last_name', 'identity_document', ] def create(self, … -
Custom input field in django admin form
I want to display an extra input field in the model change view in django admin. I am overriding the get_from method in ModelAdmin to get the Form class # Customize field labels on lesson detail page here def get_form(self, request, obj=None, change=False, **kwargs): form = super().get_form(request, obj, **kwargs) from django import forms class Form2(form): extra_field_1 = forms.BooleanField() extra_field_2 = forms.DateTimeField() def save(*args, **kwargs): # custom logic to handle the extra input field value Form2.Meta.fields += ['extra_field_1', 'extra_field_2'] return Form2 but these new fields are now getting rendered in the change view page. Am I missing something here ? I tried adding extra field with an example ModelForm and it works not sure why its not working here -
Django - how to make my code infinitely working on backend
I'm trying to crawl the powerball data (each 3 and 8 minute, the data comes out. It is just like a normal lottery game) and show to my website. New numbers come out at each 3 and 8 minute. The code at the bottom checks the time every second. For example, at 2 pm 23 minute the timer will return True and it starts with login . After login, it starts to scrap the new data from the site. After 5minutes when the time becomes 28minute, it will start again with scraping, because it have been already logged in. what i want is, for the first time starting the program, it will scrap all the data before (only today's data) and add the data to the database. And each 3 and 8 minute, it will get the new data from the website and add it to the database. And when I get to the website, I'm watching the database data which is updated each 5minutes not by crawling each time I get to the site. Can anybody give me an idea or examples for this ? (I want to run the code at the backend with no disturbution and update … -
"yaml.scanner.ScannerError: mapping values are not allowed here in ".\docker-compose.yml", line 9, column 11"
I was executing Django app using docker I facing this above error I hope anyone could help docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 - .:/app ports: - "8000:8000" -
Update Object not Duplicate in views.py django
this is my code def createstock(request): stock = Stock() stock.title = 'AAPL' stock.div_ammount = '1' stock.save() return render(request, 'stocks/index.html') Whenever i call this this via URL. It creates the row in the database table. But i want to check that if stock.title = 'AAPL' this title is already in database then dont create object, only update its values. These values will be dynamic in future. But now its hardcore values. -
Diffrent Hosts wanna send cookie
When a user logged-in, a JWT is stored in the cookie. The cookie's domain is example.com. From now on, any request to example.com will be sent with cookies. However, cookies are not sent when I send a request to example.com:8000. So I tried the following. class ObtainJWTView(JSONWebTokenAPIView): serializer_class = JSONWebTokenSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): token = serializer.object.get('token') response = Response(token) if settings.JWT_AUTH_COOKIE: expiration = (datetime.utcnow() + settings.JWT_EXPIRATION_DELTA) response.set_cookie(settings.JWT_AUTH_COOKIE, token, domain=['example.com', 'example.com:8000'], expires=expiration, httponly=True, secure=True) return response return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now I can't even save a token in the cookie anymore. How can I solve this problem? -
How to save python compatible audio file from JavaScript blob
I am trying to save an audio blob to the backend. Here is an audio blob const blob = new Blob(chunks, { 'type' : 'audio/wav; codecs=0' }); Here is the upload function function uploadAudio( blob ) { var reader = new FileReader(); reader.onload = function(event){ var fd = {}; fd["data"] = event.target.result; $.ajax({ // contentType:"application/x-www-form-urlencoded; charset=UTF-8", type: 'POST', url: 'testing/', data: fd, dataType: 'text' }).done(function(data) { console.log(data); document.getElementById("response").innerHTML=data; // alert(data); }); }; Here is the function to save the file. def upload_audio(request): print('upload_audio') if request.is_ajax(): req=request.POST.get('data') d=req.split(",")[1] print("Yes, AJAX!") #print(request.body) f = open('./file.wav', 'wb') f.write(base64.b64decode(d)) #f.write(request.body) f.close() return HttpResponse('audio received') When I try to read it in python for converting to text. I got following error ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format I tried to convert the file import ffmpeg stream = ffmpeg.input('file.wav') stream = ffmpeg.output(stream, 'filen.wav') ffmpeg.run(stream) I got following error Traceback (most recent call last): File "script.py", line 8, in <module> ffmpeg.run(stream) File "C:\Anaconda3\envs\VA\lib\site-packages\ffmpeg\_run.py", line 320, in run overwrite_output=overwrite_output, File "C:\Anaconda3\envs\VA\lib\site-packages\ffmpeg\_run.py", line 285, in run_async args, stdin=stdin_stream, stdout=stdout_stream, stderr=stderr_stream File "C:\Anaconda3\envs\VA\lib\subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "C:\Anaconda3\envs\VA\lib\subprocess.py", line 1017, … -
django issue in html as images are loading as zoom images
I am facing a weird problem, till yesterday the page was loading properly but after 2 days. the page is loading with images being zoomed.. (i.e. actual image size ) unable to figure out. main.html <!DOCTYPE html> {% load static %} <html> <head> <title>Ecom</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1" /> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> <script type="text/javascript"> var user = '{{request.user}}' function getToken(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getToken('csrftoken'); function getCookie(name) { var cookieArr = document.cookie.split(";"); for (var i = 0; i < cookieArr.length; i++) { var cookiePair = cookieArr[i].split("="); console.log('cookiePair:',cookiePair); if(name==cookiePair[0].trim()) { return decodeURIComponent(cookiePair[1]); } } return null; } var cart = JSON.parse(getCookie('cart')) if(cart == undefined) { cart = {} console.log('Cart was created'); document.cookie = 'cart=' + JSON.stringify(cart) +";domain=;path=/" } console.log('Cart:',cart); </script> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a …