Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
operator class "gin_trgm_ops" does not exist for access method "gin"
psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker. I build a project on docker with django-cookiecutter template, all settings are default. I put a gin index to one of my string fields, migrations running successfully, pg_trgm extention is being created successfully, but if I try to test my project with pytest I got this error. Here is my pytest.ini [pytest] DJANGO_SETTINGS_MODULE = config.settings.test Here is my test settings file's database configuration: test.py DATABASES['test'] = { # noqa 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test', 'PASSWORD': 'test', 'USER': 'test', 'HOST': 'localhost', 'PORT': 5454, } This is part of the migration which creates the extention pg_trgm and puts an index to the field given migrations.AddIndex( model_name='<model_name>', index=django.contrib.postgres.indexes.GinIndex(fields=['field_name'], name='field_name_gin_idx', opclasses=['gin_trgm_ops']), ), And this is the whole traceback which I am getting: self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0> sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if … -
How do I connect a website to the postgres database?
I am developing a website using django rest framework and react. And I transferred from the test VM to the timeweb cloud virtual cloud and ran into the problem that when connecting to the site, the site starts without information from the postgres database. And also when starting the react web server.the js command "npm run start" outputs an error in browsers on remote client computers: JSON.parse: unexpected character at line 1 column 1 of the JSON data I think this is due to the fact that there is no connection to the database server in postgresql. But, I've already tried adding addresses to ALLOWED HOSTS. I changed both the database and Django. P.S. The username, passwords and addresses are not real. $ cat node_modules/react-scripts/config/webpackDevServer.config.js ... // want to allow setting the allowedHosts manually for more complex setups allowedHosts: disableFirewall ? 'all' : [allowedHost], headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': '*', }, allowedHosts: [ // Ваш список разрешенных хостов здесь 'localhost', '127.0.0.1', 'IPADDR1' ], ... $ cat settings.py ... ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'IPADDR1', 'HOST1'] ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'BASE', 'USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': 'IPADDR1', 'PORT': '5432', } } $ cat /etc/postgresql/14/main/pg_hba.conf ... … -
when clicked, JS is taking mw to wrong url in backend (django)
when i click on link it is taking me to '/product/api/product/2' URL but I have defined /api/product/str:pk/ for backend I'm using django. import React from 'react' import { Card } from 'react-bootstrap' import Rating from './Rating' import { Link } from 'react-router-dom' // we are using this to load in the same page without reloading whole page function Product({ product }) { return ( <Card className="my-3 p-3 rounded"> <Link to={`/product/${product._id}`}> {/* here we are using link in place of a & to in place of href */} <Card.Img src={product.image} /> </Link> <Card.Body> <Link to={`/product/${product._id}`}> <Card.Title as="div"> <strong>{product.name}</strong> </Card.Title> </Link> <Card.Text as="div"> <div className="my-3"> <Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} /> </div> </Card.Text> <Card.Text as="h3"> ${product.price} </Card.Text> </Card.Body> </Card> ) } export default Product; when I place my cursor on product link it is showing the correct URL, but when i click on that link it is taking to wrong pattern on backend server. -
Add an http GET/POST entry point to a Django with channels websocket
I'm new in Django and I'm building a site for booking. I build the front-end in vue 3 and the back-end in django using channels. I've implemented the websockets but now I'm trying to add a GET or POST entry point for the confirmation via link (like "url/api/confirm/confirm_code" or "url/api/confirm/confirm_code=code") in a mail I sent from the back-end. The problem is that my back-end never receive the request. I tried like this: app_name.urls from django.contrib import admin from django.urls import path, include urlpatterns: list[path] = [ path('admin/', admin.site.urls), path('api/', include('app.routing')), ] app.routing from django.urls import path from app.consumers.view import ViewConsumer from app.consumers.booking import BookingConsumer from app.consumers.account import AccountConsumer from app.consumers.profile import ProfileConsumer from app.http.confirm_reservation import confirm_reservation websocket_urlpatterns = [ path(r"ws/view/", ViewConsumer.as_asgi()), path(r"ws/booking/", BookingConsumer.as_asgi()), path(r"ws/account/", AccountConsumer.as_asgi()), path(r"ws/profile/", ProfileConsumer.as_asgi()), ] urlpatterns = [ path(r"confirm/<str:confirm_code>/", confirm_reservation, name="confirm_reservation"), ] app.http.confirm_reservation from django.http import JsonResponse from app.services.booking import BookingService def confirm_reservation(request, confirm_code: str): print(request) print(confirm_code) return JsonResponse(BookingService().confirm_reservation(request)) Least but not last, if you have any suggestions for a better code than I wrote, please tell me in a comment. Thanks. I'm using my own site and postman (http://192.168.1.5:8080/api/confirm/1234/) to try sending the confirmation code but the front-end get "Cannot GET /api/confirm/1234/" and the back-end doesn't … -
Cannot make Django run the frontend from Vite's build ("was blocked because of a disallowed MIME type (“text/html”)")
My frontend is a React app that I compiled using npm run build. Once the build folder is copied to the django project, I go in my Django virtualenv and run python3 manage.py collectstatic and python3 manage.py runserver When I run the server, I can read two errors in the console: Loading module from “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js” was blocked because of a disallowed MIME type (“text/html”). The resource from “http://127.0.0.1:8000/assets/index-6ReKyqhx.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). and one warning: Loading failed for the module with source “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js”. (Django) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') package.json ... "scripts": { "dev": "vite", "build": "rm -rf ../backend/build && tsc && vite build && cp -r build ../backend/build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" }, ... I am confuse because there is no static folder in the build folder. Django gives me this warning: WARNINGS: ?: (staticfiles.W004) The directory '/home/user/project/backend/build/static' in the STATICFILES_DIRS setting does not exist. The build folder looks like this: build/ ----assets/ --------index-<randomString>.css --------index-<anotherString>.js ----index.html ----vite.svg -
Open-Source Discord Bot Verification System
I am contributing to an open source project that works as a verification system for discord servers. It deletes all data immediately after the user is verified and is prevented spam on many servers and websites.. Here is the Github link: https://github.com/human-internet. Do you have any feedback or points of improvement for me, in particular on how to receive an independent security review? Do you have any feedback or points of improvement for me, in particular on how to receive an independent security review? -
unable to create user account
my create user work currectlly until i use a signal to create customer (user profile) after user created and i get error unable to create user account # signal from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from store.models import Customer @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_customer_for_new_user(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) # app from django.apps import AppConfig class StoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'store' def ready(self): import store.signals.handlers -
django allauth settings.SOCIALACCOUNT_ENABLED overwritten?
django-allauth provides a seettings parameter SOCIALACCOUNT_ENABLED that is used in urls.py to add conditionally socialaccount urls: allauth/urls.py: if app_settings.SOCIALACCOUNT_ENABLED: urlpatterns += [path("social/", include("allauth.socialaccount.urls"))] in html templates there is the same parameter used e.g. in allauth/templates/account/login.html: {% if SOCIALACCOUNT_ENABLED %} {% include "socialaccount/snippets/login.html" with page_layout="entrance" %} {% endif %} BUT: in templates it does not reflect settings.SOCIALACCOUNT_ENABLED but is taken from the apps.is_installed status: allauth/app_settings.py: class AppSettings(object): .... @property def SOCIALACCOUNT_ENABLED(self): return apps.is_installed("allauth.socialaccount") .... That means in summary: settings.SOCIALACCOUNT_ENABLED -> effect on included allauth url patterns settings.INSTALLED_APPS[..., 'allauth.socialaccount'..] -> effect on html templates {% if SOCIALACCOUNT_ENABLED %} Can anyone explain why this makes sense?? It did cost me quite some time to understand why templates do not react on "normal" settings parameter. -
How to open specific Accordion item in Django using Bootstrap?
I have a Django app with a page that contains a Bootstrap Accordion. I have a form in the third accordion item. On submit within that form I want the page to refresh to the same accordion item - I have some feedback messaging there that want to display to the user. Currently on Submit the page refreshes to the default item - in my case that's the first accordion item. I have tried appending /#collapseThree to the url, but the page refreshes to the default view. Thanks, Andrew -
Unable to get SaaS data for tenant using django-tenants, showing all data not tenant specific data
I am building a web application using django-tenants and have followed the documentation thoroughly, but still having issues showing data for a tenant specific to its subdomain and schema. Instead, I am getting all the data from the public schema, not the tenant specific schema regardless of the URL I am accessing. tenant.models has my tenant and subdomain models. And then apps are my django apps I want across tenants. I believe my issue is how I have my shared and tenant apps, but from many different combinations nothing changes on the front end. tenant.models.py: class MspCompany(MyBaseModel, TenantMixin): company_name = models.CharField(max_length=60) industry_type = models.CharField(max_length=68, choices=INDUSTRY_TYPE) email = models.EmailField(max_length=150, unique=True) owner_name = models.CharField(max_length=60, blank=True, null=True) description = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='images/company',blank=True,null=True) users = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users', on_delete=models.CASCADE ) class Domain(DomainMixin): pass shared apps and tenant apps: SHARED_APPS = [ 'django_tenants', 'tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'django.contrib.sites', "mathfilters", "crispy_forms", # Crispy Forms "social_django", "django_extensions", 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'multiselectfield', 'phone_field', 'djstripe', 'chat', 'ckeditor', 'ckeditor_uploader', 'taggit' ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', "dashboards", "apps", 'accounts', "layouts", "components", "pages", ] You will see from the images below, the data is the same regardless of the subdomain … -
query in objects with django orm with a containing sentence
i have some city like this: In [99]: City.objects.filter(title='Hamilton') Out[99]: <QuerySet [<City: hamilton>] i have some sentences like this: sentence = '3101A 1280 Main Street West Hamilton ON L8S 4K1' how can i find cities that contains its title with this sentence? Note: i have used this method but it is not True. because this query is useful for list not string in django: In [100]: City.objects.filter(slug__in=sentence) Out[100]: <QuerySet []> -
Django-Cross Model Query 3 Models
I am working on a practice project to create 3 separate pages that is Brand Page, Car Model Page and Car Model Variant detail page. I am working on a project with three models car brands, car model, car model variants When an user opens the Car model page they should see the list of variants in that car model class BrandName(models.Model): FullName = models.CharField(max_length= 100) Slogan = models.CharField(max_length = 255) slug = models.SlugField(unique=True) def __str__(self): return f"{self.FullName}" class CarModel(models.Model): Brand = models.ForeignKey(BrandName, on_delete = models.CASCADE,null=True, related_name = "brands") ModelName = models.CharField(max_length = 200) slug = models.SlugField(unique=True) def __str__(self): return f"{self.ModelName}" class CarModelVariant(models.Model): ModelVariantName = models.CharField(max_length = 100) Brandname = models.ForeignKey(BrandName, on_delete = models.CASCADE, null = True, related_name="brands1") Model1 = models.ForeignKey(CarModel, on_delete = models.CASCADE, null = True, related_name = "model1") Doors = models.IntegerField SeatingCapacity = models.IntegerField def __str__(self): return f"{self.ModelVariantName}" **In views.py of the app ** from django.shortcuts import render from django.http import HttpResponse from . models import CarModelVariant, CarModel, BrandName from django.views.generic import ListView, DetailView class CarModelVariantView(ListView): template_name = "carlist.html" model = CarModelVariant def get_queryset(self): list_model = super().get_queryset() data = list_model.filter(Model1= CarModel_instance) return data In urls.py of the app `from django.urls import path from . import views urlpatterns = … -
Python Django. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Всем привет. Столкнулся с проблемой, которую не могу решить. В моделях прописаны get_absolute_url, но почему-то получаю ошибку: "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." Вот код (models.py): class Vendor(models.Model): name = models.CharField(max_length=255, default='') vendor_type = models.ForeignKey('VendorType', on_delete=models.PROTECT, null=False) def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('motherboard_vendors') class VendorType(models.Model): class Type(models.IntegerChoices): MOTHERBOARD = 1, 'Материнская плата' CPU = 2, 'Процессор' STORAGE = 3, 'Накопитель памяти' VIDEOCARD = 4, 'Видеокарта' RAM = 5, 'Оперативная память' MONITOR = 6, 'Монитор' SOFTWARE = 7, 'Программное обеспечение' PROJECTOR = 8, 'Проектор' PRINTER = 9, 'Принтер' name = models.CharField(choices=Type.choices, max_length=255, default='') def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('motherboards') forms.py: class AddMotherboardVendorForm(forms.ModelForm): class Meta: model = Vendor fields = ['name'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-input'}), } def clean_name(self): name = self.cleaned_data['name'] if len(name) > 50: raise ValidationError("Длина превышает 50 символов") return name def save(self): vendor = super().save(commit=False) vendor.vendor_type_id = VendorType.Type.MOTHERBOARD vendor.save() return vendor.get_absolute_url() views.py: class AddMotherboardVendor(LoginRequiredMixin, CreateView): form_class = AddMotherboardVendorForm template_name = "home/motherboard/addmotherboardvendor.html" title_page = 'Добавление производителя материнской платы' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = self.title_page return context urls.py: path('motherboard_vendors/add_motherboard_vendor/', views.AddMotherboardVendor.as_view(), name='add_motherboard_vendor') Раньше была другая сущность Vendor: class MotherboardVendor(models.Model): motherboard_vendor_name = models.CharField(max_length=255, default='') … -
Erreur De Configuration Du Middleware Django
he error message "TypeError: DeviceInfoMiddleware() takes no arguments" suggests that an instance of the DeviceInfoMiddleware class is being created without providing any arguments. This error commonly arises due to misconfigurations in Django's settings.py file, particularly in the middleware section. To resolve this, ensure that the DeviceInfoMiddleware class is properly defined and added to the middleware list in settings.py without requiring any arguments during instantiation. Verify that there are no typos or misconfigurations in how the middleware is referenced or initialized within your Django application. Comment pourrais-je gérer ce problème ? 'allauth.account.middleware.AccountMiddleware', -
Cloudinary image issues in react/django project
I'm creating a ecommerce website and I'm having some issues with my cloudinary uploads. When I use the admin panel to upload there are on issues, but when I try to upload from my website it works somewhat, but my image fetching appends the correct link onto another cloudinary link For example: When I upload an image via the website and not the admin panel, the alt attribute renders into my website, but when i look into the console its trying to fetch this url: https://res.cloudinary.com/dt4sw7qtl/image/upload/v1/media/https://res.cloudinary.com/dt4sw7qtl/image/upload/v1711814695/wmtt2ry1yycxdukggs3f.jpg Which is the correct image url appended to "https://res.cloudinary.com/dt4sw7qtl/image/upload/v1/media/" Links split: https://res.cloudinary.com/dt4sw7qtl/image/upload/v1/media/ https://res.cloudinary.com/dt4sw7qtl/image/upload/v1711814695/wmtt2ry1yycxdukggs3f.jpg If i upload a working image from the admin panel and move on with testing the order, the image is shown working all the way until the order payment screen, where it also tries to fetch an image appended to the previous link in the same way. Let me know if I need to include some more code to make sense out of this. At the bottom I have a screen similar to the order page, the order summary, which is working as it should, if somone would want to compare to find the issue. Here is the upload image screen … -
Download image to client Django
My problem is that the download does not start when I send the form the first time I created it in a view and it worked but for order and efficiency I decided to pass part of the view to the model but it does not work class Archivo(models.Model): Archivo = models.ImageField(upload_to="Seccion1") def descarga1(archivo_nombre): # Obtén la ruta completa del archivo archivo_ruta = os.path.join(settings.BASE_DIR, "media", "Seccion1", archivo_nombre) # Crea un objeto FileResponse con la ruta del archivo response = FileResponse(open(archivo_ruta, "rb")) # Indica que el archivo debe tratarse como un adjunto para descargar response['Content-Disposition'] = 'attachment; filename="Hola.png"' return response class Jpgtopng(View): def get(self,request): return render(request,"Pngtojpg.html",{"form":Formext}) def post(self,request): Formulario = Formext(request.POST,request.FILES)#?Recibimos datos del formulario if Formulario.is_valid(): imagen = Formulario.cleaned_data["Archivo"] imagen_nombre = imagen.name if Formulario.Extension(imagen_nombre): Formulario.save() Archivo.descarga1(imagen_nombre) # Pasa el nombre del archivormulario.Extension(Imagenrn):#?Pero antes de guardarlo verifica que su extension sea valida else: return HttpResponse("Extension incorrecta") else: #? En caso de no ser valido reenviamos el formulario return render(request,"Pngtojpg.html",{"Formu":Formulario}) return HttpResponse("Hubo un error") <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!--El multipar/form-data sirve para que el formulario pueda enviar archivos--> <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{form}} <button type="submit"></button> </form> </body> </html> I just need … -
How can I get a comma separated list with related posts from a many-to-many field?
I am trying to learn Django and have encountered a problem I can't figure out for the life of me. In this project I have an app called projects. In this app I have one model called Projectinfo and one called Buildingtypes. Every project can have one or more building types. What I am trying to do is to write a view that lists out all the projects with a commaseparated list of related building types. Here's a simplified version of my two models: class Buildingtypes(models.Model): buildingtype = models.CharField(max_length=100) def __str__(self): return self.buildingtype class ProjectInfo(models.Model): project_number = models.CharField(max_length=12, blank=True) project_name = models.CharField(max_length=120) buildingtypes = models.ManyToManyField(Buildingtypes, default=[1]) def __str__(self): return self.project_name I made a view that looks like this: from django.http import HttpResponse from django.template import loader from .models import ProjectInfo def index(request): myProjects = ProjectInfo.objects.all() template = loader.get_template('projects/index.html') context = { 'projects': myProjects, } return HttpResponse(template.render(context, request)) And the template: {% if projects %} {% for x in projects %} {{ x.project_number }} | {{ x.project_name }} | {{ x.buildingtype }} {% endfor %} {% endif %} Which resulted in this: projectnumber | project name | building type ---------------------------------------------------------- 101010 | project 1 | projects.Buildingtypes.None 202020 | project 2 | … -
Styles didn't apply to Django Project when uploaded to Render
I tried to upload my django project to Render which contains plenty of HTML files as well CSS styles. The latter is used in a CSS file called 'styles.css' within the static folder. When I run the project, the images are shown, but it's like the styles have not been applied to everything, not even the Django Admin panel. On the console, it mentioned something about how the stylesheet wasn't loaded because of MIME type. The same happens with my main.js file, which is also within the static folder. I have heard about using gunicorn, which I have it installed, but i'm not sure if it's actually responsible for causing this since the images load fine (although their sizes are very much different). I want to know if there's a solution to this. For reference, this is how I added the urls of my media and static in the settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' This is my current urls.py for my main project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), path('chatbot/', … -
I am trying to implement authentication in django using django_cas_ng, and also provide a option for all-auth for google login
My requirement is to have a core app to manage authentication, which should include google authentication (all-auth in django) and django_cas_ng (CAS authentication). Now I want to be able to use this authentication app for multiple projects (CAS system). I should register only for one app , and should be able to login to another app using the same username and password. (CAS auth system). path('', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'), path('accounts/logout', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'), I the url cas_ng_login redirects me to CAS_SERVER_URL = 'http://localhost:8000/accounts/', where I have the google authentication implemented. enter image description here -
i am geting value error while get cust id value from passing query in link which is in checkout file . I am using razorpay payment-gateway
I am using django framework and i will get the value error while i use razorpay payment gateway enter image description here **This iS models ** class Payment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) amount = models.FloatField() razorpay_order_id = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_status = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_id = models.CharField(max_length=100,blank = True , null = True) paid = models.BooleanField(default = False) class OrderPlaced(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) #cid = models.ForeignKey(Payment,on_delete=models.CASCADE) customer = models.ForeignKey(Customer,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateField(auto_now_add = True) status = models.CharField(max_length = 50,choices = STATUS_CHOICES,default = 'Pending') payment = models.ForeignKey(Payment, on_delete=models.CASCADE,default ="") @property def total_cost(self): return self.quantity*self.product.discounted_price This is html code {% extends 'app/base.html' %} {% load static %} {% block title %} Buy Now {% endblock %} {% block main-content %} <div class="container"> {% if messages %} {% for msg in messages %} <div class="alert alert-denger" role="alert"> {{msg}} </div> {% endfor %} {% endif %} <div class="row mt-5"> <div class="col-sm-6"> <h4> Order Summery </h4> <hr> {% for item in cart_items %} <div class="card mb-2"> <div class="card-body"> <h5> Product: {{item.product.title}}</h5> <p>Quantity: {{item.quantity}} </p> <p class="fw-bold">Price: {{item.product.discounted_price}}</p> </div> </div> {% endfor %} <p class="fw-bold"> Total Cost + Rs. 40 = {{totalamount}}</p> … -
Issue Passing Size Parameter from JavaScript to Django Backend
I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view: def get_product(request, slug): try: product = Product.objects.get(slug=slug) if request.GET.get('size'): size = request.GET.get('size') print(size) return render(request, "core/product_detail.html") except Exception as e: print(e) And here's the JavaScript function: function get_correct_price(size) { console.log(size); window.location.href = window.location.pathname + `?size=${size}`; } In my HTML template, I'm calling the JavaScript function with the size parameter: <button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button> However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console. Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you! -
Items are being added in the cart in multiples of 3 in Django
I am creating a ecommerce website on Django but the problem is that when I add a item in the cart the quantity is set to 3 instead of 1. and when I increase the quantity by clicking one more time. It's quantity becomes 6 instead of 2 and so on. Below is the code from cart.html to add and remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{item.quantity}}</p> <div class="cartquantity-buttons"> <i data-product={{item.product.id}} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{item.product.id}} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> </div> and below is the code from cart.js var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, '\naction: ', action) console.log('USER: ',user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) } else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('Not Logged in') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity': 1} } else { cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Remove Item') delete cart[productId] } } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } function updateUserOrder(productId, action){ console.log('User … -
Django Not Sending Tasks to Celery in Production
I am a deployer and delpoys django applications using gunicorn & nginx. Recently, I setup a celery project and here are my services: Gunicorn Project Service [Unit] Description=gunicorn daemon for my project After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/user/myproject/project.sock project.wsgi:application [Install] WantedBy=multi-user.target Celery Service [Unit] Description=Celery Worker Service for my project After=network.target [Service] Type=simple User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/celery -A project worker -l info Restart=always [Install] WantedBy=multi-user.target Celery Logs are stuck at: celery@server ready. But When I run python3 manage.py runserver in production celery logs updates & my task works but not when I use direct service... I tried changing celery to solo worker --pool=solo -l info [celery service] but that didn't work. My Server RAM & CPU is not being fuly utilized so that's not an issue. Thank You! -
Django miss static files after packaging with pyinstaller
I packaged my django project with pyinstaller, my project tree is like below: I did all bellow steps: Copy all static file into static/ with python manage.py collectstatic Add all static file in .spec file like this: datas=[ ('remotescope/templates/remotescope/', 'remotescope/templates/remotescope'), ('static/', 'static'), ('remotescope/logging.conf', '.'),], Update setting.py like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') But when I try to run my executable file with command of ./RemoteScope runserver 0.0.0.0:8000 --noreload, it info that all static files not found like bellow: 2024-03-30 09:35:51,125 - 139621882558208 - django.request - WARNING - Not Found: /static/admin/css/base.css [30/Mar/2024 09:35:51] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 2288 ... 2024-03-30 09:35:51,134 - 139621795096320 - django.request - WARNING - Not Found: /static/admin/css/login.css [30/Mar/2024 09:35:51] "GET /static/admin/css/login.css HTTP/1.1" 404 2270 BTW: Everything is good in debug mode wiht cmd of "python manage.py runserver 0.0.0.0:8000"(Need modify the setting.py) Anybody has some advice? Thank u very much~ -
SSL/DNS Connection Issue: Too Many Redirections
I have a problem connecting to my VPS server using domain name. I installed SSL certificate on my Debian 10 Docker server and https works only with IP address, when I try to connect with domain name it says 503 Backend Not Found. I tried to do it without nginx and now I configured it with nginx and I am at the moment when it says "Too many redirects". I tried a lot of solutions but I haven't found anything similar to this. Here is my nginx.conf script: events { worker_connections 1024; } http { upstream web { server web:8000; } server { listen 80; listen [::]:80; server_name domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name domain.com; ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; location / { proxy_pass http://web; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_buffering off; proxy_redirect off; } } } and here is my docker-compose.yml: version: '3' services: web: build: . ports: - "8000:8000" volumes: - .:/app command: python3 manage.py runserver 0.0.0.0:8000 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - /etc/nginx/nginx.conf:/etc/nginx/nginx.conf - /etc/letsencrypt:/etc/letsencrypt depends_on: - web restart: on-failure How to properly run an SSL server on a domain