Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I manipulate a Django dictionary in JavaScript?
I have a dictionary called cards, which I have created from my Card model. Each card has a front and back property. I think I am importing the 'cards' dictionary into my JS file from the template correctly. But I am unsure on how to access the vales from the dictionary, and how to display the values without any {,[,' etc. I did previously try having 2 different arrays: one for the fronts of the cards, one of the backs of the cards. However, I have a feeling this could get messy later on. Either way, it would be useful to know how to display python dictionaries in JS. models.py: from django.db import models class Deck(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Card(models.Model): front = models.CharField(max_length=200) back = models.CharField(max_length=200) deck = models.ForeignKey(Deck, on_delete=models.CASCADE, related_name='cards') def __str__(self): return self.front view function: def learn(request, deck_id): deck = get_object_or_404(Deck, pk=deck_id) cards_queryset = deck.cards.all() cards = [{'front': card.front, 'back': card.back} for card in cards_queryset] return render(request, 'srs/learn.html', { 'deck': deck, 'cards': cards, }) template file: {% extends "srs/layout.html" %} {% load static %} {% block body %} <div class="body-container"> <p class="front"></p> <p class="back"></p> <button id="show-answer">Show Answer</button> <button id="next-card">Next</button> </div> <div id="cards-var" data-cards="{{ … -
How to configure celery with SQS as backend?
I'm trying to setup a SQS broker with a celery app, configured in a django project. Here's my setup: celery.py: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") app = Celery("my-app") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() My celery related django settings: CELERY_BROKER_TRANSPORT_OPTIONS = { "region": "eu-west-1", "queue_name_prefix": f"celery-", } CELERY_BROKER_URL = "sqs://" CELERY_TASK_DEFAULT_QUEUE = "default" This configuration works fine using a rabbitmq broker, which makes me think the overall configuration is correct, but when I use SQS as broker, the messages are sent to SQS (the "Message available" counter increases), but once picked up by my worker, they go to "Messages in flight" and stay there forever it seems (at least for hours). Also, I can see the worker logs doing things, but never actually executes the task for some reason. Here are some celery worker logs: host;x-amz-date 786cb490d758593ebf5a6e0c0b34cf025b3309bb0d777891344fd32bd01cb61b [2023-11-19 19:52:05,766: DEBUG/MainProcess] StringToSign: AWS4-HMAC-SHA256 20231119T195205Z 20231119/eu-west-1/sqs/aws4_request 32a2b642b24ffcd3f42216826611c27799efb1cf756b26e7119d5553009f527c [2023-11-19 19:52:05,766: DEBUG/MainProcess] Signature: 93bcf47703548603fa0787fbbd2ae8aa4b54460db91695f4f6c818b9141b620e [2023-11-19 19:52:10,959: DEBUG/MainProcess] Response headers: {} [2023-11-19 19:52:10,960: DEBUG/MainProcess] Response body: b'<?xml version="1.0"?><ReceiveMessageResponse xmlns="http://queue.amazonaws.com/doc/2012-11-05/"><ReceiveMessageResult><Message><MessageId>c4e1b404-.....-c046dc4aeb60</MessageId><ReceiptHandle>AQEBy+4G0x9BF8su10zFWJQuyEXJOFSxF........cRPUdk/vjWzirMiBw97ZSG44M=</ReceiptHandle><MD5OfBody>483202aa2938b...da1b024b63</MD5OfBody><Body>eyJib2R5IjogIlcxdGRMQ0I3...CJyZXBseV90byI6ICJmOWZjY2FmDIyMTBkYTAyMiJ9fQ==</Body><Attribute><Name>ApproximateReceiveCount</Name><Value>1</Value></Attribute></Message></ReceiveMessageResult><ResponseMetadata><RequestId>28a76707-9a01...d3f3a42ad7</RequestId></ResponseMetadata></ReceiveMessageResponse>' [2023-11-19 19:52:10,960: DEBUG/MainProcess] Event choose-signer.sqs.ReceiveMessage: calling handler <function set_operation_specific_signer at 0xffff9b901750> [2023-11-19 19:52:10,960: DEBUG/MainProcess] Calculating signature using v4 auth. [2023-11-19 19:52:10,960: DEBUG/MainProcess] CanonicalRequest: POST /ACCOUNT_ID/celery-default host:sqs.eu-west-1.amazonaws.com x-amz-date:20231119T195210Z host;x-amz-date 786cb490d758593ebf5a6e...d777891344fd32bd01cb61b [2023-11-19 19:52:10,961: DEBUG/MainProcess] StringToSign: AWS4-HMAC-SHA256 20231119T195210Z 20231119/eu-west-1/sqs/aws4_request … -
Multi-line TeX expressions with Django MathJax
I am using MathType to convert formulas to TeX notation and pass them as template variables in Django. Most formulas convert to a single line and work fine. But there are some that convert to several lines and I am struggling to figure out if it is possible to render them in the template. Working example: Formula: Django view: def mmm(request): #The formula string is the result of conversion to Tex via MathType copy-paste option mean_formula = "$$\overline x = {{\sum {{x_i}} } \over n}$$" return render( request, "statistics101/mmm.html", { "mean_formula": mean_formula, }, ) Template: <div class="formula"> <div class="formula-maths"> {{mean_formula}} </div> <div class="formula-desc"> <p> Where,<br> <b>x</b> = each value in the data set<br> <b>i</b> = the counter of the values in the data set, from 1 to n<br> <b>n</b> = the total number of values in the data set<br> </p> </div> </div> Web: Failing example: Formula: Tex conversion of the above comes out multi-line like this: $$\left( {\matrix{ n \cr x \cr } } \right){p^x}{(1 - p)^{n - x}}$$ I have tried to assign the variable in the view like this: formula = "$$\left( {\matrix{\n n \cr \n x \cr \n\n } } \right){p^x}{(1 - p)^{n - x}}$$" But on … -
Django Summernote not showing up in Linode Server
I've added Django summernote to my post model and it's working perfectly in localhost. However, the summernote field is not showing up in the server. I am using DJango+Gunicorn+Nginx in Linode. settings.py X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_THEME = 'bs4' # Show summernote with Bootstrap4 urls.py path('summernote/', include('django_summernote.urls')), admin.py class BlogAdmin(SummernoteModelAdmin): # instead of ModelAdmin summernote_fields = ('content','blog_post',) admin.site.register(Blog, BlogAdmin) I am quite not sure what am I doing wrong? Localhost summernote admin summernote This is how my nginx file looks like. server { listen 80; server_name pinkgiraffemarketing.com www.pinkgiraffemarketing.com; # such as: 121.21.21.65 dev.mywebsite.com location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/ubuntu/pinkgiraffemarketing/staticfiles/; } location /static/admin/ { alias /home/ubuntu/pinkgiraffemarketing/venv/lib/python3.10/site-packages/django/contrib/admin/static/admin/; } location /media/ { alias /home/ubuntu/pinkgiraffemarketing/staticfiles/images/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Any guidance will be appreciated. Thank you in advance. I tried all the possible solution on the internet and none worked so far. -
Django request logs: Can't get them to appear in Cloudwatch
I'm struggling to get simple GET requests to show up in Cloudwatch. It seems that all that's appearing are some WARNING and INFO log items, not GET requests. The GET requests ARE appearing in my console when I run things locally. Here are my logging settings: cloudwatch_level = 'INFO' LOGGING_CONFIG = None logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console': { # exact format is not important, this is the minimum information 'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s', }, "aws": { "format": "%(asctime)s [%(levelname)-8s] %(message)s [%(pathname)s:%(lineno)d]", "datefmt": "%Y-%m-%d %H:%M:%S", }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'aws', }, "watchtower": { "level": cloudwatch_level, "class": "watchtower.CloudWatchLogHandler", # From step 2 'boto3_client': boto3_logs_client, "log_group": log_group, # Different stream for each environment "stream_name": f"logs", "formatter": "aws", }, }, 'loggers': { # root logger '': { 'level': cloudwatch_level, 'handlers': ['console', 'watchtower'], }, 'django': { 'handlers': ['console', 'watchtower'], 'level': cloudwatch_level, 'propagate': True, }, 'django.server': { 'handlers': ['watchtower'], 'level': cloudwatch_level, 'propagate': True, }, "watchtower": { "level": cloudwatch_level, "handlers": ["watchtower"], "propagate": True, } } }) I'm a little confused on the logger setup for Django - should GET requests be logged by the django logger or the django.server logger? I know django.request is only for 400/500 errors, … -
Django:AttributeError: 'WSGIRequest' object has no attribute 'request'
While I want to get the clicked values from website and search the result from the database, I set up a function and create the class, when I run the server, I can read the button but while I cilck the button the mistake occured.I will show my code here. Traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/search/hsa-GFAP_0019/ Django Version: 4.2.1 Python Version: 3.9.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search'] Installed 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'] Traceback (most recent call last): File "G:\my software\mydoc\python\pythonlist\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "G:\my software\mydoc\python\pythonlist\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\my software\mydoc\python\pythonlist\0.django_total\circRNA\search\views.py", line 70, in click_search_result return render(self.request, 'search_result.html', {'value_clicked': value_clicked, Exception Type: AttributeError at /search/hsa-GFAP_0019/ Exception Value: 'WSGIRequest' object has no attribute 'request' urls.py urlpatterns = [ path('', views.HomePageView.as_view(), name='homepage'), path('download/', views.DownloadPage.as_view(), name='download'), path('contact/', views.Contact.as_view(), name='contact'), path('search/', views.Search.as_view(), name='search'), path(r'search/?', views.Search.search_by_symbol, name='search result'), path('search/<str:value_clicked>/', views.Search.click_search_result, name='click search result') ] The urls used for click function is the last. views.py class Search(View): def get(self): return render(self.request, 'search_table.html') def search_by_symbol(self, click=None): if click is not None: symbol = click else: symbol = self.GET.get('symbol', '') if symbol: interaction1 = TestCircModels.objects.filter(symbol1__icontains=symbol) full_name_line = … -
fetch api keep saving only the first input value in django with dynamic formset, how can i make to save all the input value at once
but without using fetch api, the django save all of my input values but it keep refreshing. I need to use fetch api. please guide me through this, i am beginner! html <div> <form method="post" id="save_multiple_fields"> <h4>Choose the topic and write additional informations</h4> {% csrf_token %} <label for="id_title"></label> <select name="title" id="id_title" class="form-control"> <option value selected>------</option> <!-- {% for i in create_topic_models %} <option value="{{i.id}}">{{i}}</option> {% endfor %} --> </select> {{ select_title_form }} <br> <div class="form_list"> {{ formset.management_form }} {% for formset_form in formset %} <div class="real_form"> {{ formset_form.as_p }} </div> {% endfor %} </div> <div class="empty_form">{{ formset.empty_form.as_p }}</div> <button type="button" class="btn btn-primary" id="add_fields">add title box with textarea</button> <input type="submit" class="btn btn-primary" value="save" id="save_fields"> </form> <div id="fields_list"> </div> </div> javascript to add input fields const form_count = document.getElementsByClassName('real_form'); const id_items_TOTAL_FORMS = document.getElementById('id_items-TOTAL_FORMS') var add_fields = document.getElementById('add_fields'); add_fields.addEventListener('click',add_fields_function); function add_fields_function(event){ if(event){ event.preventDefault(); } // console.log(form_count.length) const empty_form = document.querySelector('.empty_form').cloneNode(true); const form_list = document.querySelector('.form_list'); empty_form.setAttribute('class','real_form'); empty_form.setAttribute('id',`form-${form_count.length}`) id_items_TOTAL_FORMS.setAttribute('value',form_count.length + 1); const regex = new RegExp('__prefix__','g'); empty_form.innerHTML = empty_form.innerHTML.replace(regex,form_count.length); form_list.append(empty_form); } javascript with fetch api and ignore the comments // saving multiple inputs fields document.getElementById('save_multiple_fields').addEventListener('submit',save_multiple_inputs); function save_multiple_inputs(e){ if(e){ e.preventDefault(); } const formData = new FormData(this); console.log(`---------${formData}`) fetch('{% url "jobs:createjob" %}',{ method:'POST', body: formData, }) .then(response … -
Order Django queryset by value closest to 0
I have a queryset that is returning a list of entries that are tied for the lead in a contest... leaders = ContestEntry.objects.filter(name=game, wins=wins) After I get this data I need to put them in order by a second field ('difference') as a tie breaker. The problem I can't figure out is I need the order to be by the number closest to 0. There will be a lot of negative and positive numbers. Thanks for your help -
How do I make it in a Django project so that after choosing an option in one form, the options in the other form are narrowed?
I'm trying to make my first project in Django which is a unit converter. I want to have a form where you can choose the type of units (like length, area, mass etc.). After choosing the type, then in the "to unit" and "from unit" fields there should ony be displayed units of the according type. Here are the contents of my files: models.py: from django.db import models class UnitType(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Unit(models.Model): unitType = models.ForeignKey(UnitType, on_delete = models.CASCADE) name = models.CharField(max_length=50) conversion_factor = models.DecimalField(max_digits=10, decimal_places=4) def __str__(self): return self.name def convert_to(self, value, to_unit): if isinstance(value, (int, float)) and isinstance(to_unit, Unit): conversion_factor = self.conversion_factor / to_unit.conversion_factor converted_value = round(value * conversion_factor, 4) return converted_value else: raise ValueError("Invalid input for conversion.") forms.py: from django import forms from .models import UnitType, Unit class UnitTypeForm(forms.Form): unit_type = forms.ModelChoiceField(queryset=UnitType.objects.all()) class UnitConversionForm(forms.Form): quantity = forms.DecimalField() from_unit = forms.ModelChoiceField(queryset=Unit.objects.all()) to_unit = forms.ModelChoiceField(queryset=Unit.objects.all()) def __init__ (self, unit_type, *args, **kwargs): super(UnitConversionForm, self).__init__(*args, **kwargs) self.fields["from_unit"].queryset = Unit.objects.filter(unitType_id=unit_type) self.fields["to_unit"].queryset = Unit.objects.filter(unitType_id=unit_type) views.py: from django.shortcuts import render from .forms import UnitTypeForm, UnitConversionForm from .models import UnitType, Unit def unit_converter(request, unit_type = None): if request.method == 'POST': typeForm = UnitTypeForm(request.POST) if typeForm.is_valid(): unit_type = typeForm.cleaned_data['unit_type'] form … -
How can I send Email in Django Function based view using Brevo API
I have developed a Django web application and integrated sending customize email using Brevo formally known as SendinBlue. My settings.py file for sending emails is configured fine, because I am able to receive Password reset email but I am unable to sending email in Function based view. I want to send email to user upon application approval but I am getting 'User' object has no attribute 'swagger_types' error. See below my view code where integrate the API for sending Email: from __future__ import print_function import sib_api_v3_sdk from sib_api_v3_sdk.rest import ApiException @login_required(login_url='user-login') def approve_applicant(request, pk): # Get Applicant id app_id = Profile.objects.get(id=pk) # Get Applicant's names app_user = app_id.applicant applicant_detail = app_id.surname app_othername = app_id.othernames app_phone = app_id.phone app_email = app_id.applicant.email # app_edu = app_id.applicant.education.qualification # Try Check Application Submission try: app_id = Submitted.objects.get(applicant=app_user) # When Applicant is Not Found except Submitted.DoesNotExist: # Send Message messages.error(request, f"{applicant_detail} {app_othername} has No Submited Application") # Redirect Back return redirect('search-applicant') else: approved = Fee.objects.count() if request.method == "POST": # applicant = Submitted.objects.get(applicant_id=pk) # Filter and Update scholarship Approval Submitted.objects.filter(applicant_id=pk).update(approved='APROVED') record_fee=Fee.objects.create(applicant=app_user, email=app_email, phone=app_phone) record_fee.save() # Instantiate the client with the API KEY configuration = sib_api_v3_sdk.Configuration() configuration.api_key['api-key']=config('API_KEY') api_instance = sib_api_v3_sdk.TransactionalEmailsApi(sib_api_v3_sdk.ApiClient(configuration)) # Define the campaign settings\ subject … -
Dango REST JWT authentication totally misunderstanding
Hello im trying to make MSA login/register in my project. I tried to implement it with JWT I understand the concept, i understand what happens in the start and in the end. But have no clue what's in the middle How to login my user with this token? Look My login template. I have AJAX to call the function on the core app, that then will call TOKEN SERVICE {% extends 'main.html' %} {% load static %} {% block content %} <link rel="stylesheet" type="text/css" href="{% static 'styles/popup.css' %}"> {% if status == 'success' %} <div class="popup-container"> <div class="popup"> <p class="popup-message">Something went wrong while processing request. Please try again.<br> Or, <a href="#">Report Problem</a></p> <button class="popup-close-button" type="button"><i class="fas fa-times"></i></button> </div> </div> <div class="formcontainer"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-6"> <h2 class="mb-4">User Login</h2> <form method="post" class="LoginForm"> {% csrf_token %} <div class="form-group"> <label>Email</label> <input type="text" name="email" id="email" class="form-control" placeholder="e.g user@user.com" required > </div> <div class="form-group"> <label>Password</label> <input type="password" name="password" id="password" class="form-control" placeholder="&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;" required > <small style="display: flex; justify-content: right; margin-top: 10px;">Haven't signed up yet?&nbsp;<a href="{% url 'register_page' %}">Sign Up</a></small> <small style="color: red; display: flex; justify-content: center; margin-top: 10px; display: none">Invalid Credentials</small> </div> <button type="submit" class="btn btn-primary" style="margin-bottom: 15px;">Login</button> </form> </div> </div> </div> … -
How to connect front-end container with back-end container?
I have dockerized a django back-end and I have dockerized a react native app with android studio. They are both on seperate repos. So there is a back-end repo and a front-end repo. And I can run them separately. But how to connect them now each together. So that they can communcate with each other? The docker-compose.yml file for the back-end looks like: version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 0:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: zijn DB_PASS: 11 DB_USER: zijn DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: tcp volumes: - type: bind source: C:\repos\dwl_backend\DierenWelzijn target: /app bind: create_host_path: true db: environment: POSTGRES_DB: zijn POSTGRES_PASSWORD: 11 POSTGRES_USER: zijn image: postgres:13-alpine networks: default: null volumes: - type: volume source: dev-db-data target: /var/lib/postgresql/data volume: {} networks: default: name: dwl_backend_default volumes: dev-db-data: name: dwl_backend_dev-db-data and the docker-compose.yml file front-end: version: "2.4" services: dwl_frontend: build: context: . args: - NODE_ENV=development environment: - NODE_ENV=development tty: true env_file: - ./.env … -
Djongo Null Values With MongoDB
i am using django to build a system and i prefer to use nosql db like MongoDB so i use djongo to convert sql code from django to schema and command that pymongo can deal with it , when i define a column like this workto = models.TimeField(null=True,blank=True) and insert new row to the table without pass any value to workto column in the new row the workto will be exist like that { "workto" : "" } but it shouldn't be exist how can i solve this and store only key that have value this is the output of migrate command (env) user@user:~/myproject$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, authintecation, contenttypes, metadata, sessions, store Running migrations: This version of djongo does not support "NULL, NOT NULL column validation check" fully. Visit https://nesdis.github.io/djongo/support/ Applying contenttypes.0001_initial...This version of djongo does not support "schema validation using CONSTRAINT" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying contenttypes.0002_remove_content_type_name...This version of djongo does not support "COLUMN DROP NOT NULL " fully. Visit https://nesdis.github.io/djongo/support/ This version of djongo does not support "DROP CASCADE" fully. Visit https://nesdis.github.io/djongo/support/ OK Applying auth.0001_initial...This version of djongo does not support "schema validation using KEY" fully. Visit https://nesdis.github.io/djongo/support/ This version … -
How to run docker compose run command other then localhost?
I have dockerized a django app. And I also have a react native app. I can connect the front-end with the back-end without docker without any problems. But if I want to connect the front-end with the back-end docker container. I am facing some problems. The backend docker container runs on localhost:0.0.0.0:8000 But the front-end url has domain url: http://192.168.1.135:8000 And of course if I try to connect the front-end with the backend docker container. This doesn't work. Because then I get this error: authentication.service.js:32 POST http://192.168.1.135:8000/api/user/token/ net::ERR_CONNECTION_REFUSED So I try to run the backend docker container on: http://192.168.1.135:8000 But if I change the url from localhost to 192.168.1.135:8000 that I get this error: Error: That IP address can't be assigned to. So this is the docker compose.yml file" version: "3.9" name: dwl_backend services: app: image: crdierenwelzijn2.azurecr.io/web1 build: context: C:\repos\dwl_backend dockerfile: Dockerfile args: DEV: "true" command: - sh - -c - "python manage.py wait_for_db && python ./manage.py migrate && python ./manage.py runserver 192.168.1.135:8000" depends_on: db: condition: service_started required: true environment: DB-PORT: "5432" DB_HOST: db DB_NAME: name DB_PASS: pass DB_USER: user DEBUG: "1" DJANGO_ALLOWED_HOSTS: localhost 127.0.0.1 [::1] SECRET_KEY: django-insecure-kwuz7%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u networks: default: null ports: - mode: ingress target: 8000 published: "8000" protocol: … -
Why do different devices use the same session in Django?
I use the session to count the number of failed logins. But when I use Wi-Fi internet, because the IP of two devices (mobile and PC) is the same, Django uses the same session. If I have two failed logins on PC and two failed logins on mobile, it will add these two together. But the interesting thing is that when I log into the account from one device, the second device does not log into the account and must be logged into the account separately. That is, it uses two different storage methods to log into the account and count the number of unsuccessful logins. if 'RC' in request.session: VRC = request.session['RC'] else: VRC = 1 VRC += 1 request.session['RC'] = VRC -
Django Cart System - Delete from Cart
I am developing an e-commerce application using Django and HTML. Right now, I am working on deleting an item from my cart. views.py in Cart app: from django.shortcuts import render, get_object_or_404, redirect from .cart import Cart from SeniorProjectApp.models import MenuItem from django.http import JsonResponse def cart(request): cart = Cart(request) cart_items = cart.cart.values() name = cart.cart.values total_price = sum(float(item['price']) for item in cart_items) return render(request, "cart/cart.html", {'cart_items': cart_items, 'total_price': total_price, 'name': name}) def cart_add(request): cart = Cart(request) if request.POST.get('action') == 'post': item_id = int(request.POST.get('product_id')) item = get_object_or_404(MenuItem, id=item_id) cart.add(item=item) cart_quantity = cart.__len__() response_data = {'qty': cart_quantity} return JsonResponse(response_data) def cart_delete(request, item_id): cart = Cart(request) item = get_object_or_404(MenuItem, id=item_id) cart.remove(item) return JsonResponse({'message': 'Item removed successfully'}) cart.py in Cart app: class Cart(): def __init__(self, request): self.session = request.session cart = self.session.get('session_key') if 'session_key' not in request.session: cart = self.session['session_key'] = {} self.cart = cart def add(self, item): item_id = str(item.id) if item_id in self.cart: self.cart[item_id]['quantity'] += 1 else: self.cart[item_id] = { 'name': item.name, 'price': str(item.price), 'quantity': 1 } self.session.modified = True def delete(self, item): item_id = str(item.id) if item_id in str(item.id): self.cart[item_id]['quantity'] -= 1 if self.cart[item_id]['quantity'] == 0: del self.cart[item_id] self.save() def __len__(self): return len(self.cart) cart.html in Cart app: {% extends 'SeniorProjectApp/base.html' %} … -
Add DRM to images
I have a website, like a chat system where people discuss with other in private (1 to 1). And they can as well share pictures. It's a Django application. Right now the protection is that when you (user A) send an image to a user B, the image is encrypted with your key and with the key of user B creating 2 images then on frontend JS will decrypt the image to display it. That way if you download the image you will get the encrypted one and not be able to share it. (it's not perfect since you can decrypt it if you find how the key is generated by your front but for basic users it's enough) I saw that on most browsers, using DRM protection will avoid as well to make screenshots (the browser will stop you from doing that) But I can not find any documentation or tutorial on how to apply DRM to an image on a web based app. Does someone has an idea how to do it or where to find resources for that? Thanks a lot -
django-cors-headers doesn't let a GET-request bypass the CORS blockage
I have an app with Django backend (localhost:8000) and Vue.js frontend (localhost:5173). I'm trying to fetch data from the backend to the frontend via GET-request. However, all requests are being blocked by the CORS policy with an error: Access to XMLHttpRequest at 'http://127.0.0.1:8000' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. django-cors-headers module is installed and registered in settings.py: INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', 'http://localhost:5173', ) I've made sure that 'corsheaders.middleware.CorsMiddleware' is the first on the MIDDLEWARE list as many answers to the similar questions suggest. I've also tried setting CORS_ORIGIN_ALLOW_ALL = True, but it made no difference. How do I configure the application settings so that the requests are allowed to go through? Thanks. -
Including self in the context
Is it advisable to include self in the context data that is being passed in the templates in django? def get_context_data(self, *args, **kwargs): return {'self': self} Does it have some security vulnerabilities or anything that may have a bad impact? Thank you. -
Hreflang conflicts and missing self-referencing hreflang issue in Django-based site
Issue 1: No self-referencing hreflang Description: Issue Type: No self-referencing hreflang. Page URLs: Page URL Current Hreflang Values: <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/" rel="canonical"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/catalogue/category/somecategory/for-kids_1532/?sort_by=newest" hreflang="en" rel="alternate"/> Assumptions: The absence of a self-referencing hreflang tag might be due to the link href containing parameters. Issue 2: Conflicting hreflang and rel=canonical Description: Issue Type: Conflicting hreflang and rel=canonical. Page URLs: Page URL Current Hreflang Values: <link href="http://localhost:1300/en/blog/1072/" rel="canonical"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="x-default" rel="alternate"/> <link href="http://localhost:1300/fi/blog/1072/" hreflang="fi-FI" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-SE" rel="alternate"/> <link href="http://localhost:1300/sv/blog/1072/" hreflang="sv-AX" rel="alternate"/> <link href="http://localhost:1300/en/blog/1072/" hreflang="en" rel="alternate"/> Assumptions: Conflicting hreflang and rel=canonical issue might be due to the same URL marked as canonical and alternate. Additional Context: Code Snippets: base.html: {% with canonical_url=request.build_absolute_uri %} <link rel="canonical" href="{% canonical_url request %}" /> {% endwith %} {% for alt in ALTERNATES %} <link rel="alternate" href="{{ alt.href }}{% if request.GET %}?{{ request.GET.urlencode }}{% endif %}" hreflang="{{ alt.hreflang }}" /> {% endfor %} context_processor.html: def i18n_alternates(request): """ Generate hreflang alternate URLs for internationalization. Example: If called with a request path '/en/blog/1072/', the function returns: {'ALTERNATES': [ {'hreflang': 'x-default', 'href': 'http://localhost:1300/en/blog/1072/'}, {'hreflang': 'fi-FI', 'href': 'http://localhost:1300/fi/blog/1072/'}, {'hreflang': 'sv-SE', 'href': 'http://localhost:1300/sv/blog/1072/'}, {'hreflang': 'sv-AX', … -
I want to change popover content after a click to show cart items. Debug the code
I want to change popover content after a click to show cart items. Debug the code. The popover is still saying title: "Your Cart" and content: "Hello". I don't know how to fix it. I am currently working on a django project and facing an issue with dynamically changing the content of a popover after a click event. The popover is meant to display the items in the user's shopping cart. {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Forsale</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <link rel="stylesheet" href={% static 'shop/style.css' %}> <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script> </head> body:- <body> <div class="container"> <div class="row"> <div class="col-md-12"> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Features</a> </li> <li class="nav-item"> <button id="cart-link" type="button" class="btn btn-secondary" data-bs-toggle="popover" data-bs-trigger="focus" data-bs-title="Dismissible popover" data-bs-content="It's very engaging. Right?"> Cart </button> </li> <li class="nav-item"> <a class="nav-link disabled" aria-disabled="true">Disabled</a> </li> </ul> </div> </div> </nav> </div> </div> <div class="row"> <div class="col-md-12"> <form class="card card-sm"> <div class="card-body row no-gytters align-items-center"> <div … -
Whay I can't get that image?
Good night. I want to display a picture from /media/images/ to store/ page but I get an error that the file is not found. Few times check out all files but nothing work. Where is may hide problem or where I can find solution? Console Output > python .\manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 19, 2023 - 04:16:07 Django version 4.2.7, using settings 'marketplace.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [19/Nov/2023 04:16:10] "GET /store/ HTTP/1.1" 200 1282 Not Found: /media/images/Download-Icon.png [19/Nov/2023 04:16:11] "GET /media/images/Download-Icon.png HTTP/1.1" 404 2278 [19/Nov/2023 04:16:11] "GET /store/ HTTP/1.1" 200 1282 Not Found: /media/images/Download-Icon.png settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'store' ] Store/Models.py class Product(models.Model): title = models.CharField(max_length=64) description = models.TextField() images = models.ImageField(upload_to='images/') price = models.DecimalField(max_digits=7, decimal_places=2) # Max Value: 99,999.99 sold = models.BooleanField() def __str__(self): return self.title Store/Urls.py from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path('', views.store_catalog, name='store_catalog'), path('about', views.store_info, name='store_info') ] # In production, you would typically let your web server (like Nginx or … -
Debugging Django with VSCode. Error is Exception has occurred: ModuleNotFoundError
.venv is activated in the terminal that's running the debug. I'm running the debug from the volume.py file. In volume.py I'm using import core.backend.sql.subclasses.class1 as class1. That triggers the error when I'm debugging. Exact error is "ModuleNotFoundError: No module named 'core'". launch.json { "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver" ], "django": true, "justMyCode": true, } ] } Structure of files website/ ├── .venv ├── manage.py ├── website/ ├── core/ ├── backend/ | ├── sql/ | ├── subclasses/ | | ├── __init__.py | | ├── class1.py | | ├── volume.py | ├── __init__.py ├── __init__.py I'm expecting to debug, but I don't understand how imports work in python. I tried using relative imports, but then the error is 'import error attempted relative import with no known parent package'. I read that you could use sys to fix imports when debugging, but I don't want to add "sys" to every file that's importing class1.py. -
Django model with uuid5 primary key
I have a problem to define Django model where the Primary Key is UUID5 that base on model fields. Here is what I have got already. class Place(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid5('PLACE_UUID_NAMESPACE', '{}{}{}'.format(self.city, self.zip, self.country))) city = models.CharField(max_length=24, blank=True, null=True) zip = models.CharField(max_length=6, blank=True, null=True) country = CountryField(default='US') The problem is with referring to model field as I did self.city, self.zip, self.country. Django does not accept the way I did. How can I define the uuid5 using model fields? I appreciate your help. -
Django - Lost connection to MySQL server during query
I have a very long await im my django rest framework project (up to 30 minutes) for a response from a websocket stream. I am waiting for a user reply in the websocket (chat). I then want to save a instance of a model class to the database. However I get an error "django.db.utils.OperationalError: (2013, 'Lost connection to MySQL server during query')" if the user in not responding with in minutes. I cant change the logic since I need to monitor the websocket connection where the user is replying. I tried to increase the connection duration by setting CONN_MAX_AGE: 1800 in my settings.py but it seems that this doesnt do the trick. Thanks