Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, postgress docker-compose psycopg2.OperationalError
Set-up: postgres, django and redis services configured via docker-compose. I've read through similar questions on SO but can't see why my compose config results in django not being able to see the db service. The db service is internally configured to port 5432 in the compose network, but mapped to 5433 on the host machine (5432 on the host is used by another docker db container). I'm not sure what I'm missing here, hoping someone can see something in the config or logs that I can't... error logs from web service: stage_web_0.10 | django.db.utils.OperationalError: could not connect to server: Connection refused stage_web_0.10 | Is the server running on host "db" (172.25.0.2) and accepting stage_web_0.10 | TCP/IP connections on port 5432? Django settings from inside the container (correctly looking for db at 5432): settings.DATABASES {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': 'db', 'PORT': '5432', 'NAME': 'stage', 'USER': 'admin', 'TEST': {'NAME': 'test_stage'}}} docker-compose services db: container_name: stage_${DJANGO_ENV}_db_${TAG} env_file: - .env build: context: ./db/ args: # Make these available at build time to create the new db. - POSTGRES_HOST - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_PORT volumes: - /data/postgresql/stage_${DJANGO_ENV}_${TAG}/:/var/lib/postgresql/data/ environment: - TAG - DJANGO_ENV - POSTGRES_HOST - POSTGRES_DB - POSTGRES_USER - POSTGRES_PASSWORD - POSTGRES_PORT ports: … -
What the meaning of the EC2 instance profile and IAM role?
I am using django-s3direct to upload file to S3. My environment is django project on fargate -> s3 Currently, I set ID and KEY in settings.py, it works. settings.py # If these are set to None, the EC2 instance profile and IAM role are used. AWS_ACCESS_KEY_ID = 'your-aws-access-key-id' AWS_SECRET_ACCESS_KEY = 'your-aws-secret-access-key' However, I don't want to use ID and KEY, So I set this None and try to set the EC2 instance profile and IAM role I attached AmazonS3FullAccess to the task role of fargate. However 403 error occurs when uploading file. Then,, what should I do more? -
Django NoReverseMatch: Reverse for 'add_continue' with arguments '('',)'
Anyone know what could be causing this error I'm getting? Most of the other code, which works the exact same way, works perfectly. However, this button doesn't work whenever I click it for some reason. The error only happens once the button to add a movie to a watchlist is clicked. I've checked out some of the other suggestions on here and none of them seem directly correlated to this issue. Any suggestions? Here is the error: NoReverseMatch at /watchlist/ Reverse for 'add_continue' with arguments '('',)' not found. 1 pattern(s) tried: ['resumeMovie/add/(?P<film_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$'] Watchlist.html: {% extends "base.html" %} {% load static %} {% block metadescription %} This is the watchlist page. Proceed to review your items. {% endblock %} {% block title %} Watchlist - MovieBuff {% endblock %} {% block content %} {% if not watchlist_items %} <div> <div class="text-center"> <br /> <h1 class="text-center my_title">Your watchlist is empty</h1> <br /> <p class="text-center"> Please click <a href="{% url 'movies:allFilmGenre' %}">here</a> to continue browsing our collection. </p> </div> </div> {% else %} <div> <div class="text-center"> <br /> <h1 class="text-center my_title">Your Watchlist</h1> <br /> </div> </div> <div class="row mx-auto"> <div class="col-12 col-sm-12 col-md-12 col-lg-6 text-center"> <table class="table my_custom_table"> <thead class="my_custom_thead"> <tr> <th colspan="5">Your … -
Django - Function with template returns `TypeError: not enough arguments for format string`
I am trying to use PostgreSQL's FORMAT function in Django to format phone number strings. I can accomplish this with the following SQL query: SELECT phone_number, FORMAT('(%s) %s-%s', SUBSTRING(phone_number,3,3), SUBSTRING(phone_number,6,3), SUBSTRING(phone_number,9,4)) FROM core_user WHERE phone_number iS NOT NULL which returns a result like: Trying to implement this into Django to be used for an ORM query, I did the following: class FormatPhoneNumber(Func): function = "FORMAT" template = "%(function)s('(%s) %s-%s', SUBSTRING(%(expressions)s,3,3), SUBSTRING(%(expressions)s,6,3), SUBSTRING(%(expressions)s,9,4))" ORM query: User.objects.annotate(phone_number2=FormatPhoneNumber(f"phone_number")) Returns the following error: File /venv/lib/python3.10/site-packages/django/db/models/expressions.py:802, in Func.as_sql(self, compiler, connection, function, template, arg_joiner, **extra_context) 800 arg_joiner = arg_joiner or data.get("arg_joiner", self.arg_joiner) 801 data["expressions"] = data["field"] = arg_joiner.join(sql_parts) --> 802 return template % data, params TypeError: not enough arguments for format string I believe it is due to this line '(%s) %s-%s' that is supplied to the FORMAT function. Does anyone have any ideas on how I can make this work? -
Django test form upload including javascript
I make test script for django project For example normal url testing. def test_view_url(self): response = self.client.login(username="user@example.com", password="abcd1234") response = self.client.get("/resources/") self.assertContains(response, "page OK") It works, However in my case I am using django-s3direct in template. It uploads when file is selected from form not when submit. It uses javascript, so I should use another test script for javascript? or I can do this test in django as well?? -
Filtering queryset defined with @property
For a headless wagtail app I'm trying to query all of the blog pages, find the latest page that is marked as being a hero, and then exclude that hero page from the list of all pages. Reason being, I want to display the hero page as a hero image on the blog index page, and then render a list of all the other pages under that. (I could also just send all the live() pages and have react find the latest hero page on the front end, filtering it there, but trying to figure out a back end solution as well). I created to class properties and was hoping to use one to filter the other, i.e. get_child_pages would be able to exclude() the value returned by get_heroes. api_fields = [ APIField('get_child_pages', serializer=BlogIndexPageSerializer()), APIField('get_heroes', serializer=BlogIndexPageSerializer()), ] @property def get_heroes(self): heroes = BlogPage.objects.filter(hero=True).order_by('-first_published_at')[:1] return heroes @property def get_child_pages(self): # return "SOMETHING" # return self.get_children().specific().public().live() return BlogPage.objects.live().exclude(get_heroes) get_child_pages works without exclude but not with it (get_heroes is not defined). I'm learning wagtail and django and I'm not understanding how to work with properties like this. Thanks! -
What API request should I send to receive graph parameters?
I have a blog on django. I have two models article and comment. Each comment can be added to another one. If I send an API request localhost:8000/comments/1 I receive the comment with id="1" and all the nested comments to the third level. json after api request localhost:8000/comments/ : HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 9, "text": "First comment", "owner": "alex", "article": 3, "parent": null, "reply_set": [ { "id": 10, "text": "Comment to comment", "owner": "alex", "article": 3, "parent": 9, "reply_set": [ { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10 } ] } ] }, { "id": 10, "text": "Comment to comment", "owner": "alex", "article": 3, "parent": 9, "reply_set": [ { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10, "reply_set": [ { "id": 12, "text": "Forth level nested comment", "owner": "alex", "article": 3, "parent": 11 } ] } ] }, { "id": 11, "text": "Third level nested comment", "owner": "alex", "article": 3, "parent": 10, "reply_set": [ { "id": 12, "text": "Forth level nested comment", "owner": "alex", "article": 3, "parent": 11, "reply_set": [] } ] }, { "id": 12, "text": "Forth … -
Use Form.has_changed() validation with Django UpdateView
I am trying to post a message when one or more of the values have changed in an UpdateView. Is this possible to do with Form.has_changed() with this generic view? For example: class MyUpdateView(UpdateView): model = MyModel form = MyModelForm fields = "__all__" template_name = "mymodel_form.html" if form.has_changed(): logger.info("Some values have changed") -
Having TypeError: 'CharField' object is not callable after migrating with django
This is my models.py from my app, the django version is 4.0.4, my python version is 3.10.4. I made all of my models and after making makemigrations in order to generate the database it gives an error code. from enum import unique from django.db import models from django.utils import timezone from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class I_Articulos(models.Model): pais = models.CharField('Pais', max_length=30, null=False, blank=False) grupo_economico = models.CharField('Grupo_Economico', max_length=30, null=False, blank=False) empresa = models.CharField('Empresa', max_length=30, null=False, blank=False) sucursal = models.CharField('Sucursal', max_length=30, null=False, blank=False) almacenado = models.CharField('Almacenado', max_length=30, null=False, blank=False) id_rubro = models.FloatField('id_rubro', null=False, blank=False, default=0, validators=[MinValueValidator(0), MaxValueValidator(99999)], unique=True) descuento_maximo = models.CharField = models.CharField('Descuento_Maximo', max_length=20, null=False, blank=False) descuento_directo = models.CharField('Descuento_Directo', max_length=20, null=False, blank=False) unidad_minima_venta = models.DecimalField('Unidad_Minima_Venta', max_digits=15, decimal_places=4, null=False, blank=False) cantidad_unidades_unidad_venta = models.DecimalField('Cant_U_UV', max_length=30, null=False, blank=False) unidad_venta = models.CharField('Unidad_Venta', max_length=30, null=False, blank=False) descripcion_articulo = models.CharField('Descripcion_Articulo', max_length=100, null=False, blank=False) codigo_articulo = models.CharField('Codigo_articulo', max_length=30, null=False, blank=False) codigo_busqueda = models.CharField('Codigo_busqueda', max_length=30, null=False, blank=False) id_divisiona = models.CharField('id_divisiona', max_length=20, null=False, blank=False) id_segmento = models.CharField('id_segmento', max_length=20, null=False, blank=False) id_subrublo = models.CharField('id_subrublo', max_length=20, null=False, blank=False) id_linea = models.CharField('Pais', max_length=20, null=False, blank=False) tipo_item = models.PositiveIntegerField('tipo_item', null=False, blank=False, default=0, validators=[MinValueValidator(0), MaxValueValidator(99999)]) combo_calcula_stock = models.CharField('combo_calcula_stock', max_length=30, null=False, blank=False) vc_fechahora_ultima_modificacion = models.DateTimeField('vc_fechahora_ultima_modificacion', null=False, blank=False) status = models.PositiveIntegerField('Status', null=False, blank=False, … -
No module named '*.urls'
So I'm creating a new Django app, which I've done a couple of times. However, right now it looks like it's not possible to add the include from django.urls for some reason? I keep getting the "No module named companies.urls" whilst it's 100% there... Here is the setup: urls.py - includes "companies.urls", redirecting to companies/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('companies.urls'), name='Companies'), ] companies/urls.py - the urls.py where it refers to from django.urls import path from . import views from .views import * app_name = 'Companies' urlpatterns = [ path('', views.getRoutes, name='Router'), path('companies/', views.getCompanies, name='getCompanies'), ] settings.py - showing that the app "companies" is added to installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', 'companies', ] Please help me out, I'm really at a loss here. I basically started copying from an older Django project where it does work. But I'm running Django 4.0.4 and the documentation sides with my implementation. -
Django template tag if condition for URL
I have variable to be validated in html template: {{ item.node.href }} {% if item.node.href is http or https %} Do some thing {% else %} Do something else {% endif %} Can you help me to write up if condition for validating item.node.href if it contains http:// or https:// in the URL ? -
Django - API authentification for third-party apps
I have a Django application where user belongs to an Account and there is multiple "Shop" on the account. We want to provide the possibility to generate API keys for the Account with different scope (IE - with a given token, you will have access to a defined part of the shop on the account and set attributes). This token will be used by a third-party application or clients to visualise/edit dat. What is the implementation you would recommend with Django-DRF? It seems that the framework relies heavily on users but in that case the scope/visibility needs to be configurable per token or key at Account level. -
Django vs MERN , Which one to learn?
I went through a basic Django bootcamp last winter but had to stop coding since last August. I am interested in coding again and want to take another course. Should I refresh my Django skills or learn the MERN Stack? I am more concerned with which would give me better job prospects over how long it will take to learn it. I am not sure if this type of post would be better for Reddit or Medium so I'll take feedback on that as well. Thank you for your help! -
Adding multiple random objects to ManyToManyField, based on user input
I am new to Django and attempt to create a geography game/quiz app. In a first step, the player chooses some game settings (number of rounds, difficulty, region/area). Based on the user's input, I want to assign countries to the user. In particular, I created these two classes in model.py. class Country(models.Model): name = models.CharField(max_length=90) code = models.CharField(max_length=15) subcontinent = models.CharField(max_length=25) subcontinent_code = models.CharField(max_length=15) continent = models.CharField(max_length=25) continent_code = models.CharField(max_length=15) def __str__(self): return self.name class Player(models.Model): name = models.CharField(max_length=90) number_rounds = models.IntegerField(default=10) difficulty = models.CharField(max_length=100, default='easy') area = models.CharField(max_length=100, default='world') countries = models.ManyToManyField(Country) def __str__(self): return self.name I created the corresponding forms.py for user input: class SetGameSettings(forms.ModelForm): class Meta: model = Player fields = ['name', 'number_rounds', 'difficulty', 'area'] labels = { 'name': 'Enter your username', 'number_rounds': 'Number of rounds', 'difficulty': 'Difficulty', 'area': 'Area', } widgets = { 'number_rounds': forms.NumberInput(attrs={'min': 1, 'max': 20}), 'difficulty': forms.Select(choices=[('easy', 'Easy'), ('medium', 'Medium'), ('hard', 'Hard')]), 'area': forms.Select(choices=[('World', 'World'), ('Africa', 'Africa'), ('Asia', 'Asia'), ('Europe', 'Europe'), ('Americas', 'Americas'), ('Oceania', 'Oceania')]), } And this is what views.py looks like: def home(request): if request.method == 'POST': form = SetGameSettings(request.POST) if form.is_valid(): form.save() #direct to next url form = SetGameSettings() return render(request, 'geo/home.html', {'form': form}) Until here, everything works fine. My … -
Data saved in session in a view is not saved in pytest session. Why?
I am making a website with Django and would like to test the data stored in session with pytest. I have a very simple view : def dev_my_view(request): if request.method == "POST": post_data = json.loads(request.body.decode("utf-8")) product_id = post_data["productid"] request.session["basket"] = {"id": product_id} # print(request.session.items()) returns # dict_items([('foo', 'bar'), ('basket', {'id, '99'})]) # as expected response = JsonResponse({"id": f"product number {product_id}"}) return response Here is the test I have written : class TestViewsWithSession(TestCase): def test_my_view(self): session = self.client.session session["foo"] = "bar" session.save() url = reverse("home_page:my_view") response = self.client.post( url, json.dumps({"productid": "99"}), content_type="application/json", ) # print(session.items()) returns # dict_items([('foo', 'bar')]) # Test passes self.assertEqual(response.status_code, 200) # Test passes # response.content = b'{"id": "product number 99"} self.assertJSONEqual(response.content, {"id": "product number 99"}) # Test fails. KeyError: 'basket' self.assertEqual( session["basket"], {"id": "99"}, ) self.assertNotEqual( session["basket"], {"id": "Invalid value"}, ) When I add data to the session in the test (session["foo"] = "bar"), the session contains this data in the view. But, it looks it does not work the other way ... When some data is added to the session in the view (request.session["basket"] = {"id": product_id}), I cannot see this data in the test. Why ? -
404 for static images and media in Django in Production Mode
I am beginner in Django I am trying to run my application on Debug=False mode to simulate the production environment, I have added all the static url, and roots. My program is generating the static images in real-time from the video passed to the application during runtime. This is working as expected in the development mode but I am getting 404 for images and videos in the production mode other stuff like bootstrap and JS are getting loaded fine. Earlier bootstrap and js was also not loading then I installed Whitenose and things start working, but now images and videos and giving 404. Link to the application code: https://github.com/abhijitjadhav1998/Deepfake_detection_using_deep_learning/tree/master/Django%20Application Further to this application, I have added the STATIC_ROOT in the settings.py and added os.system('python manage.py collectstatic --noinput') in the views.py folder to populate the static path with images and videos before sending the response to the html page. But still I am getting the 404, I also checked the file with same name is avaliable in the location. I am getting the below error: Error from the console: Able to load the js, bootstrap but able to load the images and video Code from settings.py that I have added DEBUG … -
Django Celery task doesn't fire in development
I'm trying to make use of periodic tasks but can't make it work. I have this test task # handler/tasks.py from celery import Celery app = Celery() @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): # Calls test('hello') every 2 seconds. sender.add_periodic_task(2, test.s('hello'), name='add every 2') @app.task def test(arg): print(arg) Celery is configured # project dir # salaryx_django/celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'salaryx_django.settings') app = Celery('salaryx_django') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) # salaryx_django/settings.py # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/London' The workers are intiated [2022-04-25 14:57:55,424: INFO/MainProcess] Connected to redis://localhost:6379// [2022-04-25 14:57:55,426: INFO/MainProcess] mingle: searching for neighbors [2022-04-25 14:57:56,433: INFO/MainProcess] mingle: all alone [2022-04-25 14:57:56,452: WARNING/MainProcess] /Users/jonas/Desktop/salaryx_django/venv/lib/python3.8/site-packages/celery/fixups/django.py:203: UserWarning: Using settings.DEBUG leads to a memory leak, never use this setting in production environments! warnings.warn('''Using settings.DEBUG leads to a memory [2022-04-25 14:57:56,453: INFO/MainProcess] celery@Air-von-Jonas ready. and Redis is waiting for connections but nothing happens at all.. Sanity Check … -
Daphne doesn't see heroku environment variables
I'm trying to deploy my Django & Channels app to Heroku, everything works fine in the deployment except that Daphne doesn't use any specified environment variables. I have tried to print the value of env variables from settings.py and they are exist and correct, so I think there should be a way to let asgi.py read them from settings.py but I haven't found anything in my search. my settings.py SECRET_KEY = os.environ.get( 'SECRET_KEY', 'django-insecure-pff2j7g9=9^d42-j_7)-u6kw@(%dx^bg+-q!(!cd3hhp$sn1_5') DEBUG = os.environ.get('DEBUG', True) ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '*').split(',') WSGI_APPLICATION = 'mtp.wsgi.application' ASGI_APPLICATION = 'mtp.asgi.application' EVENTSTREAM_STORAGE_CLASS = 'django_eventstream.storage.DjangoModelStorage' DATABASES = {} DATABASES['default'] = dj_database_url.config( default="postgres://postgres:121312@localhost:5432/mtp") my asgi.py import notification.routing import os from django.core.asgi import get_asgi_application from django.urls import re_path as url from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mtp.settings') application = ProtocolTypeRouter({ 'http': URLRouter([ url(r'^sse/', AuthMiddlewareStack( URLRouter(notification.routing.sse_urlpatterns) )), url(r'', get_asgi_application()), ]), }) Procfile web: daphne mtp.asgi:application --port $PORT --bind 0.0.0.0 -v2 Heroku variables Thank you. -
Can you explain why this Django syntax worked?
I'm not sure why seller=request.user worked on my end. I didn't assign any "user" variable and yet I still was able to get the user's username. def create_listing(request): if request.method == "POST": listing = Auction_listing( title=request.POST.get('title'), description=request.POST.get('description'), min_bid=request.POST.get('min_bid'), image_url=request.POST.get('image_url'), category=request.POST.get('category'), seller=request.user ) listing.save() return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/create_listing.html") -
NoReverseMatch at /control/newsletter-list/
Working on a college project, close to finishing off a newsletter app but am running into an issue. I am receiving the error "NoReverseMatch at /control/newsletter-list/" as I am trying to create a detail view for the newsletter. I realize I am following an older tutorial so I am having to fix a lot of old code, cant figure this out however. Any help would be appreicated. -
How to save many to many relations
i want to save the many to many relations, but i get this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use users.set() instead. models.py class Department(models.Model): id = models.AutoField(primary_key=True) department = models.CharField(max_length=60) info_grafana = models.TextField() users = models.ManyToManyField(User) views.py class ViewUserAccount(View): """ Description: Страница выбранного пользователя """ def get(self, request, id_account: int, *args, **kwargs) -> render: return render(request, 'settings/UserAccount.html', { 'title': f'Аккаунт пользователя {request.user}', 'account': User.objects.get(id=id_account), 'direction': Department.objects.all() }) def post(self, request, id_account, *args, **kwargs): id_direction = request.POST.get('direction_id') id_project = request.POST.get('project_id') if id_direction: direction = Department.objects.get(id=id_direction) direction.users = User.objects.get(id=id_account) direction.save() if id_project: pass return redirect(request.META.get('HTTP_REFERER')) how should i solve this problem? -
Can't pip install pathlib on M1 Mac
When I run pip install pathlib==1.0.1 I get the following error: error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [20 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/4l/rwj9f3x12qs0nbw_dq3prw2c0000gn/T/pip-install-g5u_0nde/pathlib_adb255351e05488f95986f7a8775e1f0/setup.py", line 6, in <module> setup( File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_distutils/core.py", line 109, in setup _setup_distribution = dist = klass(attrs) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/dist.py", line 460, in __init__ for ep in metadata.entry_points(group='distutils.setup_keywords'): File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 999, in entry_points return SelectableGroups.load(eps).select(**params) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 449, in load ordered = sorted(eps, key=by_group) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 997, in <genexpr> dist.entry_points for dist in unique(distributions()) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 609, in entry_points return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self) File "/Users/danieljohnson/Documents/code/folder/venv/lib/python3.9/site-packages/setuptools/_vendor/importlib_metadata/__init__.py", line 917, in read_text return self._path.joinpath(filename).read_text(encoding='utf-8') AttributeError: 'PosixPath' object has no attribute 'read_text' [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. Any idea how to solve the error? Version 1.0.1 is the version I need and I have seen m1 laptops with pathlib version 1.0.1 on them -
Django get JSON object sent from Javascript to Django Views
I need to pass a Json Object value after making an API call to my views.py in order to render in django template. After making an ajax call I'm not able to get the value in django` let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = application.applicationId $.ajax({ type: "GET", dataType: "json", url: `${url}/${kycStatus}`, headers: { 'Content-Type': 'application/json', 'X-API-Key': '', }, data: { senddata: JSON.stringify(), }, success: function(data) { document.getElementById("kyc-status").innerHTML = data.overallResult.status console.log(data.overallResult.status) } })` in my views.py def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def kycsubmit(request): """ A view to return the index page""" if is_ajax(request=request): if request.method == 'GET': data = request.GET.get('senddata') print(data) return render(request, 'kycsubmit/onboard.html') -
Django i18n External Redirect security issue
(I'm new with Django) I ran an automated scan (OWASP ZAP) to test my application security and it's returning a high risk flag for External Redirect: Automated Scan Alert Looks like it's something to do with the path "/i18n/setlang/" and the parameter "next", like "?next=(redirect)" I set the i18n path like that urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ... ] And this is my HTML <div class="flex justify-items-end"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <form action="{% url 'set_language' %}" method="post" id="form_{{ language.code }}" style="display:inline!important;"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ language.code }}" /> </form> <button class="lang-button" type="submit" form="form_{{ language.code }}" value="Submit"> {% if language.code == "en" %} <img src="{% static 'assets/webfonts/gb.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 mr-3 hover:opacity-75" /> {% endif %} {% if language.code == "es" %} <img src="{% static 'assets/webfonts/es.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 hover:opacity-75" /> {% endif %} {% if language.code == "pt" %} <img src="{% static 'assets/webfonts/br.svg' %}" width="30" alt="gb" class="rounded-lg h-5 w-5 mr-3 hover:opacity-75" /> {% endif %} </button> {% endfor %} </div> I don't know if it's … -
How can I apply logic is the user present in the Frontend Order Model?
I just want If a user Ordered something then the user will be able to rate on the order else can't and will show an error message "You didn't purchase any website". I applied logic 5/6 times in different ways but I couldn't fix the issues. Oeder Model: class Frontend_Order(models.Model): USer = models.ForeignKey(User,default=None,on_delete=models.CASCADE,related_name='user_frontend_order') Service_Type = models.CharField(max_length=250, null=True) Price = models.CharField(max_length=250, null=True) Number_of_Section = models.CharField(max_length=250, null=True) Per_section_Price = models.CharField(max_length=250, null=True) Website_Functionality = models.CharField(max_length=50, null=True) Email = models.EmailField(max_length=50, null=True) files = models.FileField(upload_to="0_frontend_files/", null=True, blank=True) created_date = models.DateTimeField(auto_now_add=True, null=True) order_message = models.ForeignKey(Message_Manu,on_delete=models.CASCADE, null=True, related_name="message") def __str__(self): return str(self.pk)+ str(".") + str(self.USer) Rating Model: class Frontend_Rating(models.Model): USer = models.OneToOneField(User,default=None,on_delete=models.CASCADE, related_name="frontend_rating") Rating = models.IntegerField(null=True) Feedback = models.TextField(max_length=250, null=True) created_date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return str(self.pk)+ str(".") + str(self.USer) + str("(") + str(self.Rating) + str("stars") +str(")") Order View: def frontend_order_rating(request): if request.user.is_authenticated: if request.method == "POST": frontend_rating = int(request.POST.get('frontend_ratting')) frontend_feedback = request.POST.get('frontend_feedback') try: Frontend_Rating.objects.create( USer = request.user, Rating = int(frontend_rating), Feedback = frontend_feedback ) messages.success(request,f"{request.user.first_name}, Thank You for your feedback!") return redirect("/", userz = request.user) except: messages.error(request,f"{request.user.first_name}, Sorry! You've already given a feedback!") return redirect("/", userz = request.user) else: messages.error(request,"Please login or create an account.") return redirect("/")