Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding google fonts in django-quill-editor
I'm working with django-quill-editor and I want to add a custom google font. However I could not add it. I just want to know that is it possible to add custom google fonts in django-quill-editor. I tried like this but it didn't work. QUILL_CONFIGS = { 'default':{ 'theme': 'snow', 'modules': { 'syntax': True, 'toolbar': [ [ {'font': ['Montserrat']}, {'header': []}, {'align': []}, 'bold', 'italic', 'underline', 'strike', 'blockquote', {'color': []}, {'background': []}, ], ['code-block', 'link'], ['clean'], ] } } } -
Finding Duplications with Pandas Pivot Table Works The First Time, Fails Second Time Forward
We have an xlsx file that we process into a dataframe to gather duplications values and count of duplications def duplicationCount(table_file_path, targetColumns): dfTable = pd.read_excel(io=table_file_path, sheet_name='Sheet1', skiprows=0) dfTable.columns = dfTable.columns.str.strip("'") res = dfTable.pivot_table(index=targetColumns, aggfunc='size') res.reset_index() res.rename(columns={'Unnamed: 0': 'no of dups'}, inplace=True) res.index.name = 'index' res = res[res['no of dups'] >= 2] targetColumns.extend(['no of dups']) res = res.filter(targetColumns).values.tolist() return res This works well the first time with output containing for example: account year no of dups 10301 2022 2 42334 2022 2 but running the same code with the same file the second time we get: Traceback (most recent call last): File "E:\Programs\XX\backend\app\views.py", line 265, in app_process_text_file results['DuplicationReportResults'] = duplicationCount(tables_file_paths[0], dupsFindingTargets) File "E:\Programs\XX\backend\app\functions.py", line 92, in duplicationCount res = dfTable.pivot_table(index=targetColumns, aggfunc='size') File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 8044, in pivot_table return pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 95, in pivot_table table = __internal_pivot_table( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\reshape\pivot.py", line 164, in __internal_pivot_table grouped = data.groupby(keys, observed=observed, sort=sort) File "E:\Programs\XX\venv\lib\site-packages\pandas\core\frame.py", line 7718, in groupby return DataFrameGroupBy( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\groupby.py", line 882, in __init__ grouper, exclusions, obj = get_grouper( File "E:\Programs\XX\venv\lib\site-packages\pandas\core\groupby\grouper.py", line 882, in get_grouper raise KeyError(gpr) KeyError: 'no of dups' -
What's the best way to implement JWT authentication with multiple clients?
We currently use Djoser (with simplejwt), which has served us well. The only OAuth clients we had so far have been frontend apps. However, we now have to add access to some external services. There is no appetite to have separate gatekeeper proxy. This will need longer token life, etc and the simple_jwt is no longer the best solution. DRF website has a long list of third party libraries, which is great to have the choice, but makes the choice harder. Which of these packages, or another one that's not listed there, is a fairly easy replacement for Djoser? Ideally, it would be something which doesn't require us to write new views, etc for everything. -
My ckeditor-uploaded image doesn't show up in the post unless I restart the django app from cpanel
`My ckeditor uploaded image doesn't show up unless I restart the django app from cpanel my ckeditor-imported post page works fine in local server, BUT in the production server after i upload an image to server **FIRST **image doesnt in appear post layout (it used to in local server) in local server image would show up here in editor i used to have the image here in the editor it doesn't appear in my post neither... ....unless i restart it from cpanel after i restarted the app from cpanel, it started to work fine i have the following settings.py code: from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'x' DEBUG = False ALLOWED_HOSTS = ['cozumdefteri.com'] INSTALLED_APPS = [ 'gonderiyaz.apps.GonderiyazConfig', 'ckeditor', 'ckeditor_uploader', 'mebsci.apps.MebsciConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') CKEDITOR_UPLOAD_PATH = 'static/uploads/' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] ROOT_URLCONF = 'cozumdefteri.urls' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cozumdefteri.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = … -
Ubuntu to windows django project
So I have developed several projects in Ubuntu. So I get the projects set up in Windows and run them; they are running properly, but I am facing a problem with the static files, that is, the CSS, showing up when I run the web applications. I have inspected the webapps, and it shows that the CSS and static files are being fetched and served (200 code). So what is the issue, and how can I solve it? -
how to reverse queryset without getting error: AttributeError: 'reversed' object has no attribute 'values'
I want to reverse the order of the following queryset, but I get the error AttributeError: 'reversed' object has no attribute 'values'. I believe this is because of the reversed_instances.values(). Without changing reversed_instances.values(), how can I reverse the order of instances? Thank you, and please leave a comment at the bottom. def view(request, pk): instances = Calls.objects.filter(var=var).order_by('-date')[:3] reversed_instances = reversed(instances ) return JsonResponse({"calls":list(reversed_instances.values())}) -
Django and ReactJS Project: Module parse failed: Unexpected token (14:12) You may need an appropriate loader to handle this file type
I know there's a lot of similar questions out there but I've tried to do what was suggested and I just can't seem to solve this error. So I'm working on a project using Django and ReactJS. I am using Webpack and Babel to connect front end and back end. I keep getting this error when I run the frontend: ERROR in ./src/components/App.js 14:12 Module parse failed: Unexpected token (14:12) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders | return ( > <div className="App"> | <Router> | <Navbar /> | <Routes> @ ./src/index.js 1:0-35 I will attach my webpack.congig file and babel.config file. Any help would be appreciated! Webpack.config.js const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, // { // test: /\.(js|jsx)$/, // include: path.resolve(__dirname, 'src'), // exclude: /(node_modules|bower_components|build)/, // use: ['babel-loader'] // } ], }, resolve: { extensions: ['*', '.js', '.jsx'] }, module: { rules: [ { test: /\.css$/, use: [ 'style-loader', 'css-loader' ] } ] }, … -
Loading of GDAL library impossible after an upgrade
I have a Python environment with Django 3 that has to use GDAL (because the DB engine I use is django.contrib.gis.db.backends.postgis). After an upgrade of GDAL (from 3.6.4_6 to 3.7.1_1), I have this exception on any command to run the django project : File "~/.pyenv/versions/3.8.9/lib/python3.8/ctypes/__init__.py", line 373, in __init__ self._handle = _dlopen(self._name, mode) OSError: dlopen(/usr/local/lib/libgdal.dylib, 0x0006): Symbol not found: __ZN3Aws6Client19ClientConfigurationC1Ev Referenced from: <FA8C3295-2793-3C69-A419-16C41753696B> /opt/homebrew/Cellar/apache-arrow/12.0.1_4/lib/libarrow.1200.1.0.dylib Expected in: <BDB1F1E3-0BE9-3D7D-A57E-9D9F8CAD197A> /opt/homebrew/Cellar/aws-sdk-cpp/1.11.145/lib/libaws-cpp-sdk-core.dylib I've managed to isolate the problem in a fresh python environment with only loading the GDAL library : from ctypes import CDLL; CDLL("/usr/local/lib/libgdal.dylib"). Note, I'm on a Mac (CPU M2 Pro), I've installed GDAL and all its dependancies via brew. I've tried reinstalling it from fresh but it didn't change a thing and I've also tried with different python versions. -
My drop-down not showing up in my templates - django
i'm trying to make a nested drop-down with dajngo-mptt for a category section in mt project the code is working and i can see my codes in inspect but its not showing in my template can anybody help??? my template: <div class="dropdown"> <ul class="dropdown-menu"> {% recursetree categories %} <button class="btn btn-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name }} </button> <li {% if not node.is_leaf_node %}class="dropdown-submenu"{% endif %}> <a class="dropdown-item {% if not node.is_leaf_node %}dropdown-toggle{% endif %}" href="{% if node.is_leaf_node %}{{ node.get_absolute_url }}{% endif %}" {% if not node.is_leaf_node %}role="button" data-bs-toggle="dropdown" aria-expanded="false"{% endif %}> {{ node.name }} {% if not node.is_leaf_node %}<span class="dropdown-caret"></span>{% endif %} </a> {% if not node.is_leaf_node %} <ul class="dropdown-menu"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> veiws.py class HomePage(View): def get(self, request, ): postss = Post.objects.all() categories = Category.objects.all() form = CategoryForm() return render(request, 'home/index.html', {'postss': postss, 'categories': categories, 'form': form}) and i have this js in my base.html document.addEventListener('DOMContentLoaded', function() { var dropdownSubmenus = [].slice.call(document.querySelectorAll('.dropdown-submenu')); dropdownSubmenus.forEach(function(submenu) { submenu.addEventListener('mouseenter', function() { this.querySelector('.dropdown-menu').classList.add('show'); }); submenu.addEventListener('mouseleave', function() { this.querySelector('.dropdown-menu').classList.remove('show'); }); }); }); i'm added to my code and added button to show it but it's not showed up what can i do? -
How to get the value from an Orderable from a Wagtail Page, and then call a function that will return a value based on the input of the Orderable?
I have a Django/Wagtail project. I have modified the HomePage in models.py and then in the Wagtail CMS, I populated the newly created fields of my homepage. Here is how my models.py looks like: from django.db import models from wagtail.core.models import Page from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel from wagtail.core.fields import RichTextField from modelcluster.fields import ParentalKey from modelcluster.models import ClusterableModel from wagtail.core.models import Orderable from wagtail.images.edit_handlers import ImageChooserPanel from django.shortcuts import render class HomePage(Page): templates = "templates/home/home_page.html" background_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) hero_title = models.CharField(max_length=255, blank=True, null=True) form_placeholder_text = models.CharField(max_length=255, blank=True, null=True) form_cta_button_text = models.CharField(max_length=255, blank=True, null=True) hero_title_2 = models.CharField(max_length=255, blank=True, null=True) hero_title_3 = models.CharField(max_length=255, blank=True, null=True) description = RichTextField(blank=True, null=True) hero_title_4 = models.CharField(max_length=255, blank=True, null=True) content_panels = Page.content_panels + [ MultiFieldPanel([ ImageChooserPanel('background_image'), FieldPanel('hero_title'), FieldPanel('form_placeholder_text'), FieldPanel('form_cta_button_text'), InlinePanel('slider_items', label="Slider Items"), ], heading="Hero Section 1"), MultiFieldPanel([ FieldPanel('hero_title_2'), InlinePanel('card_locations', label="Card Locations"), ], heading="Hero Section 2"), MultiFieldPanel([ FieldPanel('hero_title_3'), FieldPanel('description'), ], heading="Hero Section 3"), MultiFieldPanel([ FieldPanel('hero_title_4'), InlinePanel('column_one_items', label="Column One Items"), InlinePanel('column_two_items', label="Column Two Items"), InlinePanel('column_three_items', label="Column Three Items"), ], heading="Hero Section 4"), ] class SliderItem(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, related_name='slider_items') slider_text = models.CharField(max_length=255, blank=True, null=True) slider_link = models.URLField(blank=True, null=True) panels = [ FieldPanel('slider_text'), FieldPanel('slider_link'), ] class CardLocation(Orderable): page = ParentalKey(HomePage, on_delete=models.CASCADE, … -
Nginxproxymanager doesn't serve mediafiles in django
I am using nginxproxymanager https://nginxproxymanager.com/ and can't configure it to serve media files uploaded by users in django app. This is my docker compose file: version: "3.9" services: api: &api build: context: . dockerfile: ./docker/production/django/Dockerfile command: /start image: shop_api volumes: - static_volume:/app/staticfiles - media_volume:/app/mediafiles env_file: - ./.envs/.production/.django - ./.envs/.production/.postgres depends_on: - postgres - redis networks: - reverseproxy_nw postgres: image: postgres:15-bullseye volumes: - production_postgres_data:/var/lib/postgresql/data env_file: - ./.envs/.production/.postgres networks: - reverseproxy_nw redis: image: redis:7-alpine networks: - reverseproxy_nw celery_worker: <<: *api image: shop_api_celery_worker command: /start-celeryworker networks: - reverseproxy_nw flower: <<: *api image: shop_api_flower command: /start-flower volumes: - flower_data:/data networks: - reverseproxy_nw networks: reverseproxy_nw: external: true volumes: static_volume: {} media_volume: {} production_postgres_data: {} flower_data: {} this is nginxproxymanager configs enter image description here MEDIA_URL = "/mediafiles/" MEDIA_ROOT = str(ROOT_DIR / "mediafiles") when i try to get image https://{domain}/mediafiles/my-img.png it just returns 404 error, i checked mediafiles folder inside docker container and it has that file, but when i try to request it, it gives 404 :( -
Pass variables as arguments to Django custom tag in view
I have a custom tag in Django project: class ExampleNode(template.Node): def __init__(self, nodelist, header_copy='', paragraph_copy='', ): self.nodelist = nodelist self.header_copy = header_copy self.paragraph_copy = paragraph_copy def render(self, context): template = 'example.html' context = { 'elements': self.nodelist.render(context), "header_copy": self.header_copy, "paragraph_copy": self.paragraph_copy, } return render_to_string(template, context) @register.tag def example_component(parser, token): try: tag_name, header_copy, paragraph_copy = token.split_contents() except ValueError: raise TemplateSyntaxError("%r takes two arguments" % token.contents.split()[0]) nodelist = parser.parse(('endexample_component',)) parser.delete_first_token() return ExampleNode(nodelist, header_copy, paragraph_copy) And the view of the component is: <div> <h1>{{ header_copy }}</h1> <p>{{ paragraph_copy }}</p> </div> <div>{{ elements }}</div> Usage: {% with header_copy='Lorem ipsum dolor sit amet' paragraph_copy='Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.' %} {% example_component header_copy paragraph_copy %} <div>ex1</div> <div>ex2</div> {% endexample_component %} {% endwith %} And the issue is that what I am receiving in view is header_copy and paragraph_copy instead of Lorem ipsum. Only passing actual primitive value works. Maybe there is a better way to receive those args and parse them? -
understanding of urlpatterns in urls.py of Django App
Problem: When we try to add the data to the database. So, the request will always come to this URL starting with the project-level directory, todo_main. So here, we will create a pattern. path('todo/', include('todo.urls')), This path will forward the request to todo. URLs. from django.urls import path from .import views urlpatterns =[ path('addTask/', views.addTask, name='addTask'), ] So whenever we send a request to add a task, then the corresponding views.addTask should run, which will be a task. Questions: I try to understand my best what is the meaning or purpose of addTask. Can we write another word instead of it? -
Django path converter not converting value in path
I have an app that should be able to take a field's value in lower and uppercase. The url below should work http://localhost:8000/app/family=Araceae/ but fail if value is araceae. I followed the official documentation but it's not working. path('app/family=<str:family>/', views.SpeciesDetail_family.as_view(), name='family') I made a converter to convert the value to lower case if it's in uppercase but is returning 404 saying URL does not match the patterns below admin/ app/family=<value:family>/ [name='family'] app/family=<value:family><drf_format_suffix:format> [name='family'] urls.py from django.urls import path, register_converter from rest_framework.urlpatterns import format_suffix_patterns from app import converters, views register_converter(converters.convert_value_to_lowercase, 'value') urlpatterns = [path('app/family=<value:family>/', views.SpeciesDetail_family.as_view(), name='family')] urlpatterns = format_suffix_patterns(urlpatterns) converters.py class convert_value_to_lowercase: regex = '[A-Z]' def to_python(self, value): value = value.lower() return value def to_url(self, value): return value -
Dockerise Django with proxy server NGINX
I have dockerised a django application. And now I try to deploy the app to a live server. So I am using the NGINX reversed proxy server. I have a folder name called proxy within a dockerfile: FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] and a default.conf.tpl file: server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } And a run.sh script: #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' and docker-compose-deploy.yml looks: version: "3.9" services: app: build: context: . dockerfile: Dockerfile.prod restart: always volumes: - static-data:/vol/web environment: - DJANGO_ALLOWED_HOSTS={DJANGO_ALLOWED_HOSTS} env_file: - ./.env.prod proxy: build: context: ./proxy restart: always depends_on: - app ports: - 8000:8000 volumes: - static-data:/vol/static volumes: static-data: part of my settings.py file looks like: import os import dotenv dotenv.read_dotenv() from pathlib import Path from os import environ import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR … -
How do I enable HTTPS redirect in Mayan EDMS
I have a session of Mayan in docker with traefik for hosting on the local network. I want to use my keycloak with oidc. Following this forum post works, but the redirect_uri is http and not https. As is the case with case django project I have tried setting MAYAN_SECURE_PROXY_SSL_HEADER=("HTTP_X_FORWARDED_PROTO", "https") which didn't work and reading the documentation and source code haven't let me to any obvious settings. -
DynamoDB in Django 4.2.4
I have a Django project now i want to shif in DynamoDB insted of sqlite3 for database,looking for documentation so i can configure it on my project, specific documentation? configure DynamoDb in Django project that contain multiple app -
The current path, 1/password/, didn’t match any of these
Im trying to access the reset password through the form link. Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form. Traceback Using the URLconf defined in carreview.urls, Django tried these URL patterns, in this order: admin/ [name='home'] car/<int:pk> [name='post-details'] create_post/ [name='create_post'] car/edit/<int:pk> [name='edit_post'] car/<int:pk>/delete [name='delete_post'] like/<int:pk> [name='likes'] signup/ signup/ The current path, 1/password/, didn’t match any of these. blog/urls.py urlpatterns = [ path('', view.as_view(), name='home'), path('car/<int:pk>', PostDetail.as_view(), name='post-details'), path('create_post/', CreatePost.as_view(), name='create_post'), path('car/edit/<int:pk>', EditPost.as_view(), name='edit_post'), path('car/<int:pk>/delete', DeletePost.as_view(), name='delete_post'), path('like/<int:pk>', Likes, name='likes') ] signup/urls.py urlpatterns = [ path('', view.as_view(), name='home'), path('car/<int:pk>', PostDetail.as_view(), name='post-details'), path('create_post/', CreatePost.as_view(), name='create_post'), path('car/edit/<int:pk>', EditPost.as_view(), name='edit_post'), path('car/<int:pk>/delete', DeletePost.as_view(), name='delete_post'), path('like/<int:pk>', Likes, name='likes') ] Edit profile view (signup/views.py) class ProfileEdit(generic.UpdateView): form_class = EditProfile template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user I believe its something to do with "1/password/" instead of being redirected to "/passwords/" If you need any more files ill add them, thanks :) I'm trying to be redirected to change the password in the edit profile section. -
Modal window doesn't open in django
I'm having a little problem with a modal in django. When I click on the button to open the modal window just nothing happens. I'm a beginner, so don't swear too much at very stupid mistakes. {% extends 'main/layout.html' %} {% block title %} Registration {% endblock %} {% block content %} <div class="features"> <h1> Registration </h1> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Open modal window</button> <div class="modal fade" id="exampleModal" role = "dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"> Form </h5> <button class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p>Something</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> <form method = "post"> {% csrf_token %} {{ form.name }}<br> {{ form.mail }}<br> {{ form.phone }}<br> {{ form.password }}<br> <font color="red">{{error}}</font><br> <br> <button class = "btn btn-success" type = "submit">add news</button> </form> </div> {% endblock %} Pattern {% load static %} <!doctype html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% block title %} {% endblock %}</title> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/5.2.3/js/bootstrap.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static 'main/css/main.css' %}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.4.2/css/all.css"> </head> <body> <aside> <img src="{% static 'main/img/1.jpg' %}" alt="Logo"> <span class="logo">Rolex</span> <h3>Навигация</h3> <ul> <a href="{% url 'home' %}"><li><i … -
I have problem to get items from cart model using nested URL
I'm working on multi vendor online store project using django , I'm trying to get items from cart but I get not found response I use nested URL : app_name = "cart" urlpatterns = [ path( "cart_retrieve/<str:pk>/items/", CartItemsRetrieveView.as_view(), name="retrieve-cart-items", ), ] so I have this view to get the items from the cart : class CartItemsRetrieveView(generics.RetrieveAPIView): queryset = Cart.objects.all() serializer_class = CartSerializer authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] pagination_class = StandardResultsSetPagination def get_queryset(self): # Assuming the cart is identified by a cart_id in the URL cart_id = self.kwargs.get("pk") try: cart = Cart.objects.get(cart_id=cart_id) return cart.items.all() # Return all items related to the cart except Cart.DoesNotExist: return CartItems.objects.none() the problem is when I commented the get_queryset I can retrieve the cart object : { "cart_id": "75ed487e-445a-437c-aef6-4cf62217e6e7", "created_at": "2023-08-20T12:15:56.360320Z", "items": [ { "cart_items_id": "b2fe23bc-442c-41fb-be8d-65f9f03241ae", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "463d4e16-46a2-4da0-9e25-2a99a494b6f6", "title": "el short el fashe5", "discounted_price": 90.0 }, "quantity": 1, "sub_total": 90.0 }, { "cart_items_id": "8bf66b5b-2b9d-4dd3-8528-cfc693035168", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "5fecf90c-874b-452f-8a8d-adde50ee2f33", "title": "cover lel 2amar", "discounted_price": 50.0 }, "quantity": 2, "sub_total": 100.0 }, { "cart_items_id": "140a0762-17ef-4e65-aa1a-997b79fec14b", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": "e6e61a33-82cc-40f7-aef7-f538150bb703", "title": "mouse bs nice", "discounted_price": 33.25 }, "quantity": 3, "sub_total": 99.75 }, { "cart_items_id": "2f569234-bc7d-4d2c-ad49-d4a6bbe9cc4b", "cart": "75ed487e-445a-437c-aef6-4cf62217e6e7", "product": { "product_id": … -
My view display raw data instead of showing the data in Datatables
I have been trying to understand how ajax and Datatables works in Django. But, as the title says, my list of data is being raw displayed in my view. Screenshot: I will put here my code so you can help me understand what's missing, or wrong. My list view: class SampleList(LoginRequiredMixin, ListView): model = Samples def render_to_response(self, context, **response_kwargs): data = list(self.get_queryset().values()) return JsonResponse(data, safe=False) My template: {% extends 'partials/base.html' %} {% load static %} {% block title %}Samples List{% endblock title %} {% block content %} <div class="main-panel"> <div class="content-wrapper"> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} <!-- partial --> <h2>Here are all samples: </h2> <h1>Samples</h1> <table id="samples-table"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Date</th> </tr> </thead> <tbody> //I don't know if here must be empty </tbody> </table> <script> $(document).ready(function() { // Initialize DataTable $('#samples-table').DataTable({ // Replace "yourmodel-list/" with the URL of your view "ajax": { "url": "{% url 'samples:samplelist' %}", "dataSrc": "data" // Property name that holds the array of records in the JSON response }, "columns": [ {"data": "id"}, // Column for ID {"data": "sample_code"}, // … -
Can't use redis password with special characters in django
I have a redis server with authentication password containing =, and ?. Meanwhile I am using the Location scheme as redis://[:password]@localhost:6397. Config: 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://:6?V4=434#ef4@localhost:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } }, I always get an error TypeError: __init__() got an unexpected keyword argument 'V4'. Somehow the Location scheme string doesnt count for cases where password have =, and ? in certain order, such that it thinks it is separators in the scheme. I tried to escape the special characters : 6\?V4\=434#ef4 but it gave me different error: ValueError: Port could not be cast to integer value as '6\\' Can this be solved without moving password in OPTIONS ? -
django requires libmysqlclient.21.dylib but I have libmysqlclient.22.dylib on MAC OSX
I have this error when using django, it seems to require /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib However I have /opt/homebrew/opt/mysql/lib/libmysqlclient.22.dylib in my system. I use brew on Mac OSX Venture How can I fix this? Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/__init__.py", line 17, in <module> from . import _mysql ImportError: dlopen(/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 0x0002): Library not loaded: /opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib Referenced from: <158921C4-1F3C-3D68-AE0F-402C3D6AF77B> /Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so Reason: tried: '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/opt/mysql/lib/libmysqlclient.21.dylib' (no such file), '/usr/local/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache), '/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib' (no such file), '/usr/local/lib/libmysqlclient.21.dylib' (no such file), '/usr/lib/libmysqlclient.21.dylib' (no such file, not in dyld cache) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.17_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.17_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run self._target(*self._args, **self._kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/core/management/__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/whitebear/.local/share/virtualenvs/office-GFy7wr8U/lib/python3.9/site-packages/django/__init__.py", line 24, … -
How to pass Payment Intent Id in Checkout in Stripe?
I am trying stripe in test mode in Django. I am new here. I want to let customer choose the card from their saved cards for checkout. I am storing customer's preferred card (payment method which is pm_xxxxxxx) in selected_card_id. Then I have created Payment Intent. Now I want to pass this payment intent id into checkout. But currently my code is creating two payment intents: (1.) in payment intent which stays INCOMPLETE ue to 3DS authentication (and I can't do anything about it as it is in test mode) (2.) in checkout which is getting COMPLETED but it is using only the last saved card. Here is my code: # For getting id of current logged in user current_user_id = request.user.id user = User.objects.get(id = current_user_id) selected_card_id = request.session.get("selected_card_id") # Create customer id for new user if not user.customer_id: customer = stripe.Customer.create() user.customer_id = customer.id user.save() payment_intent = stripe.PaymentIntent.create( currency='inr', customer = user.customer_id, amount=299900, # Amount in paise payment_method=selected_card_id, confirm = True, ) payment_intent_id = payment_intent["id"] checkout_session = stripe.checkout.Session.create( mode='payment', payment_intent= payment_intent_id, payment_method_types=['card'], line_items=[ { 'quantity': 1, 'price': 'price_1NevYPSIWq54gkyCEytMLqZ1', } ], success_url=domain_url + 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url + 'cancelled/', customer=user.customer_id ) My objective can be achieved either if Payment Intent can … -
ModuleNotFoundError: No module named 'attachments.wsgi'
i am trying to deploy my django app on render but i am finding this error attachments is my projectname my code for wsgi is """ WSGI config for attachments project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'attachments.settings') application = get_wsgi_application() enter image description here i was expecting a sucess message