Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have problem whe loading this page in django project
enter image description here- it shows like this when i run the program I tried to change the model i created; in the model image_url with charset changed to image with imageset....( i did migrate though) but when I run the code took this then it shows like this -
How to display average ratings in the form of stars in django
I want to display the average rating on a product in the form of stars where i want to have 5 stars and then fill the stars with gold color on how much the average rating on the product is. This is my code and my relation b/w models class Product(models.Model): name = models.CharField(max_length=300) price = models.DecimalField(max_digits=7, decimal_places=2) image_url = models.CharField(max_length=400) digital = models.BooleanField(blank=False) sizes = models.ManyToManyField(Size, through='ProductSize') quantity = models.IntegerField(default=1) def __str__(self): return self.name @property def get_average_rating(self): average = self.comment_set.aggregate(Avg('rating'))['rating__avg'] if average is not None: return round(average, 1) else: return 0 class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) text = models.TextField() image = models.ImageField(upload_to='images/comment_images', null=True, blank=True) created_on = models.DateField(auto_now_add=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) I tried to run a loop like this but it did not work as the average rating is in float I do not know much javascript so if you can help me in js that will be appreciated too thank you!! {% for _ in product.get_average_rating %} ★ {% endfor %} -
Django Choices model field with choices of classes
The following code was working in python 3.10 but not in 3.11 due to a change in the enum module. Now the app won't launch with the following error message : File "/home/runner/work/e/e/certification/models.py", line 3, in <module> from .certifications.models import Certification, QuizzCertification # noqa: F401 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/runner/work/e/e/certification/certifications/models.py", line 17, in <module> class CertificationType(models.TextChoices): File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/site-packages/django/db/models/enums.py", line 49, in __new__ cls = super().__new__(metacls, classname, bases, classdict, **kwds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 560, in __new__ raise exc File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 259, in __set_name__ enum_member = enum_class._new_member_(enum_class, *args) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.2/x64/lib/python3.11/enum.py", line 1278, in __new__ raise TypeError('%r is not a string' % (values[0], )) TypeError: <class 'certification.certifications.models.QuizzCertification'> is not a string How would you implement a model field with choices, where the first element is a Model class? class QuizzCertification(models.Model): ... class OtherCertification(models.Model): ... class CertificationType(models.TextChoices): QUIZZ = QuizzCertification, "Quizz" OTHER = OtherCertification, "Other" class Certification(models.Model): name = models.CharField(max_length=100, unique=True) description = models.TextField(_("Description"), blank=True, null=True) type_of = models.CharField( _("Type of certification"), max_length=100, choices=CertificationType, default=CertificationType.QUIZZ, ) -
i have this error on my django app i tried every solution possible but it remains the same
so im trying to build a realtime chat application for my college project and i used django because i heard that its preety flexible to use as webframewoke app but since i started i kept facing errors, i had a solution for most of them but i got stuck in this error so i need help #forms.py from django.contrib.auth.forms import UserChangeForm from django.contrib.auth.models import User from django.db import models from django import forms class SignupForm(UserChangeForm): class Meta: model = User fields = ['username', 'password1', 'password2'] #urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path('members/', views.members, name='members'), path('', views.frontpage, name='frontpage'), path('signup/', views.signup, name='signup'), path('login/', auth_views.LoginView.as_view(template_name='members\login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), ] #views.py from django.contrib.auth import login from django.shortcuts import render, redirect from .forms import SignUpForm def frontpage(request): return render(request, 'members\frontpage.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save() login(request) return redirect('frontpage') else: form = SignUpForm() return render(request, 'members/signup.html', {'form': form}) #models.py from django.db import models from django.contrib.auth.models import User class User(models.Model): username = models.CharField(max_length=255, blank= True, editable=True) password1 = models.CharField(max_length=30, null=True, blank=True, editable= True) password2 = models.CharField(max_length=30, null=True, blank=True, editable= True) #the error message Exception in … -
Best Solution for connecting to 2 diffreent databases with 2 diffrent access in Django by using ORM or query Script
I want to connect my django project to 2 diffrent databases, one of them is MS-SQL with read-only access and the other is a PostgreSQL with full access what I want to do is read from the MS-SQL by using celery beat and write the aggrigated data on the Postgres what is the best solution to update my Postgres DB with the most performance? What is the most sample way which is already said in django documentation is this: https://docs.djangoproject.com/en/5.0/topics/db/multi-db/ I want to know that is if i use router.py file is better of just create an API which I read the some functions as a python script which are contatains the SQL query and insert or update them into the PostgreSQl What is the best solution? -
Custom save() method not working any more in Django 5.0.4
I have this custom save() method in mt admin.py: def save_model(self, request, obj, form, change): if obj._state.adding: obj.added_by = request.user return super().save_model(request, obj, form, change) After a recent update this is not working any more; indeed, when I hit 'save' on the backend I get no errors and the data is not saved on the database. It has worked until a recent update (I think up until 5.0.2). -
What is the Django logic flow to show pdf inside HTML template after click the given link
I'm using Django to create a website to public my post, all of my post is pdf. As usual, I defined my view and view logic, it returns a context dictionary views.py class PageView(TemplateView): def get_context_data(self): context = super().get_context_data(**kwargs) highlightObject = Post.objects.filter(is_highlight = 1).order_by('-created_on') context['highlight'] = highlightObject return context Then, on my html file {% extends "base.html" %} {% for row in highlight %} <h3 class="mb-auto">{{ row. Title }}</h3> <div class="btn-group"> <a href="{{ row.pdfFile.url }}" class="icon-link">Reading more</a> </div> {% endfor %} Until now, when cliking on the "Reading more", it changes to pdf Viewer, but I want to show pdf viewer inside html template, for example, it should change to other html file which extend the template from base.html and show pdf viewer using path row.pdfFile.url So, how to write a new html file for reading pdf from directory row.pdfFile.url Or, if there is any other way to solve this problem. Thanks -
Custom User Model having ForeignKey to Customer with dj-stripe
I would like to have a Custom User Model in my django application, featuring a column to hold reference to Customer objects coming from stripe, being synced via dj-stripe. So my approach was to extend as follows: from django.contrib.auth.models import AbstractUser, UserManager from django.db import models class StripeUserModel(AbstractUser): objects = UserManager() customer = models.ForeignKey("djstripe.Customer", null=True, blank=True, on_delete=models.SET_NULL) Setting the standard django User model to: AUTH_USER_MODEL = "billing_stripe_app.StripeUserModel" When I start with a clean new database by deleting the SQLite file and running python manage.py makemigrations, I observe following error: django.db.migrations.exceptions.CircularDependencyError: billing_stripe_app.0001_initial, djstripe.0001_initial, djstripe.0008_2_5, djstripe.0009_2_6, djstripe.0010_alter_customer_balance, djstripe.0011_2_7 Without the customer field in StripeUserModel, everything works. I wonder how to resolve this. I have run into circular dependency in Python before. It completely makes sense. In my application (billing_stripe_app), I reference dj-stripe customer field. And apparently this one relies on the AUTH_USER_MODEL user model itself again, creating that circular dep, as can be seen from the djstripe migration file 0001_initial.py (excerpt below). ... DJSTRIPE_SUBSCRIBER_MODEL: str = getattr( settings, "DJSTRIPE_SUBSCRIBER_MODEL", settings.AUTH_USER_MODEL ) # type: ignore # Needed here for external apps that have added the DJSTRIPE_SUBSCRIBER_MODEL # *not* in the '__first__' migration of the app, which results in: # ValueError: Related model 'DJSTRIPE_SUBSCRIBER_MODEL' … -
no item provider dropdown while adding social application to django admin
Django Admin PanelI'm currently learning web development with django and while trying to add soial authentication to my project with django-allauth i was met with an error saying invalid configuration after loading the social account tag and creating a link with the provider login url tag, I though it was because i hadn't added the social applications to the django admin yet so i tried that, i went to sites and added 127.0.0.1:8000 as my link with google as the name but when i tried to add the social application, there was no item in the dropdown menu where i'm normally supposed to select a provider even though i added the allauth.socialaccount.providers for google, faceboook and microsoft my settingss.py--> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #Third-Party 'allauth', 'allauth.account', "allauth.socialaccount", "allauth.socialaccount.providers.google", 'allauth.socialaccount.providers.microsoft', 'allauth.socialaccount.providers.facebook', ] SOCIALACCOUNT_PROVIDERS = { 'google': { 'EMAIL_AUTHENTICATION': True, 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, 'OAUTH_PKCE_ENABLED': True, } } LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT = 'home' #allauth config SITE_ID = 1 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_EMAIL_VERIFICATION = "none" EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' urls.py --> urlpatterns = [ #admin path('admin/', … -
Django Mediapipe application: how to manage delays in realtime video processing?
I'm developing a Django application which opens the client camera via JS using navigator.MediaDevices.getUserMedia(), send a blob to the server through websocket and then the server should process the images through mediapose library. I'm using the following three functions respectively to: convert blob to cv image def blob2image(bytes_data): np_data = np.frombuffer(bytes_data, dtype=np.uint8) img = cv2.imdecode(np_data, cv2.IMREAD_COLOR) if img is None: raise ValueError("Could not decode image from bytes") return img extract markers from the img def extractMarkers(image, pose, mp_drawing, custom_connections): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) results = pose.process(image) mp_drawing.draw_landmarks( image, results.pose_landmarks, connections = custom_connections, ) return image, results convert back the annotated image to b64_img def image2b64(img): _, encoded_image = cv2.imencode('.jpg', img) b64_img = base64.b64encode(encoded_image).decode('utf-8') return b64_img The code runs, but keeps accumulating delay during the streaming. Is there any way to drop the buffer or to improve the performance of the code? I tried locally the code for extracting markers extractMarkers(), without using the Django server application getting images coming from a local camera and it works smootly. I also tried to use the Django application to get the images from the client and sending them to the server through websocket and then only sending back to the client the images … -
Web application using gunicorn in nginx server not working
I had 3 apps in a server running on Ubuntu 22.04. The first one was a Django app, the second a Flask appp under a subdomain and the third one a FastAPI under another subdomain. When I tried to add a fourth one (Flask) I don't know how I messed up but now none of them work. All the apps run perfectly in my computer. When I try to access the page through the browser in my computer it returns ERR_CONNECTION_REFUSED and when accessing throught my phone it returns a 502 Bad Gateway nginx/1.18.0 (Ubuntu) error. The first one doesn't log anything in the nginx's error.log but the second one does. My current server config is as follows: server { server_name host.es www.host.es; location ~ /\.ht { deny all; } location ~/\.git { deny all; } location = /favicon.ico { access_log off; log_not_found off; } location /media { alias /var/www/host.es/myapp/media; } location /static { alias /var/www/host.es/myapp/static; } location / { include proxy_params; proxy_pass http://unix:/run/myapp.sock; } # The next configuration applies to the 3 subdomain apps location /subdomain1 { include porxy_params; proxy_set_header SCRIPT_NAME /subdomain1; proxy_pass https://unix:/run/mysecondapp.sock; } } server { if ($host = www.host.es) { return 301 https://$host$request_uri; } if ($host … -
i have used to google provider in social auth in django but provider is not showing in django template
social app this provider name is not showing at provider field i am a new django developer. Now i used to Authentication using Social auth. When i used this code everythin ok but not working right now. i try to several time but not working. i have used this : INSTALLED_APPS = [ 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ]` MIDDLEWARE = [ 'allauth.account.middleware.AccountMiddleware', ] SITE_ID = 1 LOGIN_REDIRECT_URL='/' SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', }, } } -
Issue Adding "django.contrib.gis" to INSTALLED_APPS in Django
I'm currently developing an application using Django and aiming to integrate geospatial functionalities by adding "django.contrib.gis" to my project's INSTALLED_APPS. However, upon adding this module to INSTALLED_APPS in the settings.py file, I encounter the following error: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal307", "gdal306", "gdal305", "gdal304", "gdal303", "gdal302", "gdal301", "gdal300", "gdal204"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings Despite having the GDAL library installed in the directory C:\Program Files\PostgreSQL\16\gdal-data, specifying the GDAL_LIBRARY_PATH in the settings.py file doesn't seem to resolve the issue. Additionally, I have installed PostGIS via the Application Stack Builder in PostgreSQL. I'm seeking guidance on how to resolve this issue and successfully integrate "django.contrib.gis" into my Django project. Any insights or suggestions would be greatly appreciated. Thank you! -
RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS
when running python3 manage.py crontab run i get the above error error detials Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/management/commands/crontab.py", line 29, in handle Crontab().run_job(options['jobhash']) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/crontab.py", line 126, in run_job job = self.__get_job_by_hash(job_hash) File "/home/tg-ashique/.local/lib/python3.8/site-packages/django_crontab/crontab.py", line 171, in __get_job_by_hash raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! aise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! can anyone please help me to fix this error. i am using ubuntu as os django as a framework. raise RuntimeError( RuntimeError: No job with hash None found. It seems the crontab is out of sync with your settings.CRONJOBS. Run "python manage.py crontab add" again to resolve this issue! can anyone please help me … -
How to send form data from frontend ReactJS to backend Django?
Here I want to send products values to the backend Django as Django have multi Serializers But i think i have sent proper formatted value data also i am getting error Please help me. class ProductSerializer(serializers.ModelSerializer): product_size = ProductSizeSerializer(many = True) product_color_stock = ProductSizeSerializer(many = True) product_image = ProductSizeSerializer(many = True) class Meta: model = Product fields = ["user","category","Slug","Name","size_Description","color_Description","Description","Main_Image","Banner","Rating","Date","archive","product_color_stock","product_size","product_image","secret_key"] extra_kwargs = { 'user': {'read_only': True}, 'Slug': {'read_only': True}, 'Rating': {'read_only': True}, 'Date': {'read_only': True}, 'product_color_stock': {'read_only': True}, 'product_image': {'read_only': True}, 'product_size': {'read_only': True}, 'secret_key':{'read_only': True}, } This is the Submit function that is sent from next js to django const handleSubmit = async (event) => { event.preventDefault(); const products = new FormData(); const times = 1; const secret_details = "details" + times ; const secret_size = "size" + times ; const secret_color_stock = "color_stock" + times ; const secret_img = "image" + times ; products.append("secret_key", secret_details); products.append("user", parseInt(2)); Object.keys(p_details).forEach((key) => products.append(key, p_details[key])); var parentObj = {}; for (var key in p_imgs.Image) { if (p_imgs.Image.hasOwnProperty(key)) { var file = p_imgs.Image[key]; var nameWithKey = p_imgs.Name + "[" + key + "]"; var obj = { "Name": nameWithKey, "user": 2, "image": file, "secret_key": secret_img }; parentObj[nameWithKey] = obj; } } products.append('product_image', JSON.stringify(parentObj)); parentObj … -
Internal Server Error when Querying Orders: ValueError Must be User instance
I encountered an Internal Server Error while querying orders in my Django application. The error message indicates a ValueError: "Must be User instance." This occurs when filtering orders by customer_id. I'm developing a Django application where users can place orders. I have models for Order, Customer, and User. Each order is associated with a customer, and customers are linked to users through a foreign key relationship. I have a viewset to handle order queries, and I'm trying to filter orders based on the customer_id. However, when attempting to filter, I encounter a ValueError stating that it must be a User instance. 1.Reviewed the models and viewset code to ensure proper relationships and filtering. 2.Checked the queryset and filtering logic in the viewset's get_queryset method. 3.Examined the Customer and User models to verify the foreign key relationship. -
Can't connect Django server to Cassandra DB (AstraDB)
I've hosted my Cassandra DB on AstraDB and am trying to connect my Django server to it. This is the first time I'm working with Django too so I'm a bit confused on how it works. In my settings.py file, this is my code from pathlib import Path from cassandra import ConsistencyLevel from cassandra.cluster import Cluster from cassandra.auth import PlainTextAuthProvider import os from dotenv import load_dotenv import dse load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECURE_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blogs', 'graphene_django', ] INSTALLED_APPS = ['django_cassandra_engine'] + INSTALLED_APPS SESSION_ENGINE = 'django_cassandra_engine.sessions.backends.db' 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', ] ROOT_URLCONF = 'core.urls' 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 = 'core.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases # DATABASES = { # 'default': { # 'ENGINE': … -
Why can docker not find my file when I run docker compose up
I have a Django application for the backend and a Vue application for the frontend. The app works 100% on my local machine. I am trying to dockerize the application so I can deploy it on a VPS just for someone to look at. The front end starts up when I run docker compose up but the back end gives me the same error every time: python3: can't open file '/app/manage.py': [Errno 2] No such file or directory My directory structure is as follows: back (directory) ... (django apps directories) -- manage.py -- Dockerfile -- requirements.txt front (directory) ... (vue directories) -- Dockerfile -- package.json -- vite.config.js -- index.html Here is my Dockerfile for the backend: FROM python:3.10 WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . back EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Here is my Dockerfile for the front end: FROM node:20-alpine3.17 WORKDIR /app COPY package.json /app/ RUN npm install COPY . front/ EXPOSE 8080 CMD ["npm", "run", "dev:docker"] and here is my docker-compose.yml file: version: "1.1" services: db: image: postgres:15-alpine volumes: - ./db:/var/lib/postgresql/data environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_DB=postgres back: build: ./back ports: - "8000:8000" volumes: - ./:/back env_file: ./back/.env command: … -
Django create several container columns in a template and fill it with several values from QuerySet
I'm pretty a newbie in Web-Development, so I've met some difficulties while trying to connect html-templates with Django code. My plan for a certain page of my projected site is roughly to have a header on above, then lower there are 3 column-shaped containers (left to right, representing, i.e., different groups) filled with names of members of those groups (with vertical alignment, each member in a separate little container with photo, name and description). I thought that, as I use Django, it would be stupid to hard-code all the members into containers, and there probably are some methods to fill those columns from the code. I used cycles. Here is the template ("core" is a name of the app, templates are located in project/core/templates/core directory): {% extends 'core/base.html' %} {% block content %} <h1>{{title}}</h1> <div>Characters</div> <div> {% for fac in factions %} {% if fac == outers %} <div> <h2>{{fac}}</h2> {% for char in fac %} <div> <h3>{{char.name}}</h3> <h3>{{char.description}}</h3> </div> {% endfor %} </div> {% endif %} {% if fac == resistance %} ... {% endfor %} </div> {% endblock %} File core/models.py: class Character(models.Model): FACTION_CHOICES = ( ('outers', 'Outer World'), ('resistance', 'Resistance'), ('neutrals', 'Neutral characters'), ) name = models.CharField(max_length=100) … -
How to get rid of django.db.utils.OperationalError: no such table?
I'm developing this app in Django where I can't generate the migrations under any circumstances. I have tried other posts on SO, I have spent hours on ChatGPT, but there's no progress. After defining the single model, views and urls, my project is always returning django.db.utils.OperationalError: no such table: vini_rest_plotdata in the code that I will provide below. Can anyone see what is happening here? I have tried to create a whole new project only to find the same error, so I don't believe it is an error in the settings, but something I have in the code that I am repeating but just can't see. views.py: from django.shortcuts import render from django.http import JsonResponse from .models import plotData from .dash_app import app import json # Create your views here. def import_json(request): if request.method == 'POST': data = json.loads(request.body) title = data.get('title') description = data.get('description') url = data.get('url') json_data = data.get('json_data') plot_data = plotData.objects.create( title = title, description = description, url = url, json_data = json_data, ) return JsonResponse({'status': 'success', 'id': plot_data.id}) else: return JsonResponse({'status': 'error', 'message': 'Only POST requests are allowed'}) models.py: class plotData(models.Model): title = models.CharField(max_length = 100, primary_key=True, unique=True) description = models.TextField() url = models.URLField() json_data = … -
'The request signature we calculated does not match the signature you provided' in DigitalOcean Spaces
My django app saves user-uploaded files to my s3 bucket in DigitalOcean Spaces(using django-storages[s3], which is based on amazon-s3) and the path to the file is saved in my database. However when I click the url in located in the database it leads me to a page with this error: The request signature we calculated does not match the signature you provided. Check your key and signing method. The actual url, for example, looks something like this: https://my-spaces.nyc3.digitaloceanspaces.com/media/uploads/Recording_2.mp3?AWSAccessKeyId=DO009ABCDEFGH&Signature=Y9tn%2FTZa6sVlGGZSU77tA%3D&Expires=1604202599. Ideally the url saved should be https://my-spaces.nyc3.digitaloceanspaces.com/media/uploads/Recording_2.mp3 This actually also impacts other parts of my project because the url will be accessed later using requests but because of this error I get status [402]. My settings.py is this: AWS_ACCESS_KEY_ID = 'DO009ABCDEFGH' AWS_SECRET_ACCESS_KEY = 'Nsecret_key' AWS_STORAGE_BUCKET_NAME = 'bucket_name' AWS_DEFAULT_ACL = 'public-read' AWS_S3_ENDPOINT_URL = 'https://transcribe-spaces.nyc3.digitaloceanspaces.com/' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400' } AWS_MEDIA_LOCATION = 'media/' PUBLIC_MEDIA_LOCATION = 'media/' MEDIA_URL = '%s%s' % (AWS_S3_ENDPOINT_URL, AWS_MEDIA_LOCATION) DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage' The url that is saved contains the Access Key, the Signature that was used to write the file to the bucket and a timeout. I want all of that to not be there when the url to the file is saved in the database. I've tried to edit … -
Kong 502 Bad Gateway
I have two VMs. One is running an Apache server with a Django API and the other is running Kong. The two VMs are on the same network and can ping each other, and I can access the Django site on my browser from my Kong VM. I have configured the Kong route to point specifically to the local IP address on the network (192.168.x.x) instead of localhost. On the Kong VM I can do curl requests directly to the API just fine, and I can access the site on my browser, and the test route to httpbin works fine as well. But I still continue to run into this error when I try to access the API through my service. I'm running Kong as is, no docker stuff I tried getting the logs and got no information other than the Bad Gateway stuff, I've triple checked and verified that the routes are pointing to the correct local IP address and route and not localhost, still nothing I also have a web application firewall setup (Modsecurity) but disabling the firewall doesn't fix the problem and no relevant error logs show up that might suggest the firewall is blocking my requests … -
How to optimize a bulk query to redis in django - hiredis
I am porting a rest/graphql api from a Java project to Django in Python. We are using redis in both. We have one endpoint that is rather large (returns several MB). In this endpoint we construct a key and if that key exists in redis we return that data and skip past the other logic in the endpoint. I have deployed the api to a development environment. The Java version of this endpoint returns data between 4-5 seconds faster than the python version. I recognize some of this is that Java is a compiled language vs Python which is interpreted. I'm aware that there are a host of other differences, but I'm trying to see if there is any low hanging fruit that I can pick to speed up my Python api. I ran across an optimized library named hiredis. The website says the library speeds up multi-bulk replies, which is my use case. I repeatedly hit an endpoint that returns a large amount of data. Hiredis is supposedly a parser written in C. I have redis-py and django-redis installed. I read that I need to pip install hiredis. One source says hiredis will automatically be detected and just work … -
How can I show and hide Like/Unlike buttons using Javascript in my Web app?
I'm doing online course CS50W by Harvard and building a web app similar to twitter. When user sees a post I need to show the user Like or Unlike button depending on user liked it or not. There's also a counter showing how many users liked the post so far. I am able to update the counter if the user liked or unliked the post, but I'm having problem with the code showing or hiding the buttons. Here's my code: models.py class Post(models.Model): """ Model representing a post. """ user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) no_of_likes = models.IntegerField(default=0) def __str__(self): return f"Post {self.id} by {self.user.username} on {self.timestamp}" class Like(models.Model): """ Model representing a like. """ user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.user} likes {self.post}" urls.py path("", views.index, name="index"), path("like/<int:post_id>", views.like, name="like"), path("unlike/<int:post_id>", views.unlike, name="unlike"), views.py def index(request): """ Home page. """ posts = Post.objects.all().order_by('-timestamp') paginator = Paginator(posts, 5) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) likes = Like.objects.all() # Make a list of liked posts. liked_posts = [] try: for like in likes: if like.user.id == request.user.id: liked_posts.append(like.post.id) except: liked_posts = [] return render(request, "network/index.html", { "posts": posts, "page_obj": … -
Errors in Importing assets folder with static url in React parcel project
I am trying to serverside render a react page using Django. The server-side rendering is working fine for normal react components. The project is using parcel to auto-build javaScript files so that Django could render them. This is the command I am using to compile react to Js. "scripts": { "watch": "parcel watch src/index.tsx --public-url /assets/" } I am new to the parcel, So sorry for the poor framing of the problem and/or any wrong terminology. The problem comes whenever I try to import an assets component in my assets folder into my react components. The import statement in my react code is working fine but I am getting an error in the import statements of the assets folder telling the file path for import is wrong. Here is the below screenshot of the issue. enter image description here @parcel/core: Failed to resolve 'assets/theme/base/typography' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:23:24 22 | import breakpoints from "assets/theme/base/breakpoints"; > 23 | import typography from "assets/theme/base/typography"; > | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 24 | import boxShadows from "assets/theme/base/boxShadows"; 25 | import borders from "assets/theme/base/borders"; Done in 689.72s. C:\profitional\BRAVO\Server\assets>yarn parcel watch src/index.tsx yarn run v1.22.19 $ C:\profitional\BRAVO\Server\assets\node_modules\.bin\parcel watch src/index.tsx × Build failed. @parcel/core: Failed to resolve 'assets/theme/base/breakpoints' from './src/assets/theme/index.js' C:\profitional\BRAVO\Server\assets\src\assets\theme\index.js:22:25 …