Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Factory boy field for self-referential field in django abstract model
`class BaseOrganization( OrganizationModelMixin, TimeStampedModel, OrganizationWidgetsMixin ): name = models.CharField(max_length=255, verbose_name="Nomlanishi", null=True) juridical_address = models.CharField( max_length=150, verbose_name="Yuridik manzili", null=True, blank=True ) phone_number = models.CharField( max_length=150, verbose_name="Telefon raqami", null=True, blank=True, validators=[phone_regex], ) parent = models.ForeignKey( "self", on_delete=models.SET_NULL, null=True, blank=True, related_name="%(class)s_children", verbose_name="Yuqori tashkilot", ) class Meta: abstract = True class BaseOrganizationFactory(factory.django.DjangoModelFactory): """Base organization factory""" name = factory.Faker("company") juridical_address = factory.Faker("address") phone_number = factory.Faker("phone_number") parent = factory.SubFactory( "myapp.tests.factories.BaseOrganizationFactory", ) @pytest.mark.django_db class TestBaseOrganization: @pytest.fixture(autouse=True) def setup(self): self.base_organization = BaseOrganizationFactory( parent=None ) ` if i call BaseOrganizationFactory in setup method it caused RecursionError: maximum recursion depth exceeded while calling a Python object -
Django web application cannot load a page
I am currently building a Django web app(A toy store). But some pages just won't load. After I log in or register to the web app, and I choose the category of ages 10-14, there appears the toys available, when I click on a toy it is supposed to take me to the details page but, for some reason it keeps loading and never opens. It worked yesterday when I ran it. I run it on localhost. Here is all the code for my project: https://github.com/MosheM123/Toys -
Parsing nested JSON in Django Rest Framework
I am trying to serialize a geometry dict which also contains a location dict and map that dictionaries values to my model. The data comes in two levels deep and is mapped to a single model, because its from an external API. How I've done it so far is with source='*' but this requires a new ModelSerializer for every nested object. Is there a way to "skip" to the nested object I want? For example here is some input data: { ... geometry: { location: { lat: ..., lng: ..., } } ... } Then I map it to a model like this: class MyModel(models.Model): ...other attributes from 1 level deep latitude = CharField() longitude = CharField() And my current serializer do that like this: class GeometrySerializer(serializers.ModelSerializer): latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES) class Meta: model = models.Location fields = ['latitude', 'longitude'] class GeometryLocationSerializer(serializers.ModelSerializer): location = GeometrySerializer(source='*') class Meta: model = models.Location fields = ['location'] class LocationSerializer(serializers.ModelSerializer): # Nested obj from json req, geometry: { location: { lat: ..., lng: ...} ....} #latitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lat') #longitude = serializers.DecimalField(max_digits=globals.MAX_DECIMAL_DIGITS, decimal_places=globals.MAX_DECIMAL_PLACES, source='geometry.location.lng') geometry = GeometryLocationSerializer(source='*') class Meta: model = models.Location fields = ['id', 'addr_address', 'business_status', 'formatted_address', 'formatted_phone_number', 'icon', … -
DateTime conversion (March 5, 2024, 5:33 a.m. to datetime.datetime(2024, 3, 5, 5, 33))
i have raw date = March 5, 2024, 5:33 a.m. is it possible to convert it in datetime.datetime(2024, 3, 5, 5, 33) using python I have tried from datetime import datetime date_string = "March 5, 2024, 5:33 a.m." date_object = datetime.strptime(date_string, "%B %d, %Y, %I:%M %p") desired_datetime = datetime(2024, 3, 5, 5, 33) print(desired_datetime) -
Expected out is not coming in Django python
I am new to python! I was trying to scrap menu structure of any website! the out is coming fine when I tried in VScode! here is the code for i in menu_items('https://natureshair.com.au/'): print(json.dumps(i, indent=6)) And this is the output, Script can scrap all the menu Now I am trying to collect this website and display results using Django! the strange thing is if I use the same website the output is empty! here is the code : def product(request): finaldata=request.GET["title"] finaldata1=request.GET["title1"] finaldata2=request.GET["title2"] results = list( item #for link in ('https://natureshair.com.au/', 'https://www.trafficradius.com.au/') for link in (finaldata,finaldata1,finaldata2) for item in menu_items(link)) return JsonResponse({'results': results}) Output: Note: it not working for a few websites like 'https://natureshair.com.au/' and this is working fine in VS code! Not sure where I am wrong here is the link to my project My projrct -
module 'django.apps' has no attribute 'get_model'
I am writing a funciton to delete object, with only by sending it's app_name and model_name in from url. here is my function. def deleteobject(request, app_name, model_name, id): print(app_name, model_name, id) print(type(app_name), type(model_name), type(id)) try: model_class = apps.get_model(app_name,model_name) except LookupError: model_class = None print(model_class) if model_class: try: obj = model_class.objects.get(id=id) print(obj) obj.delete() except model_class.DoesNotExist: return HttpResponseBadRequest("Object not found.") else: return HttpResponseBadRequest("Invalid model name.") return redirect(request.META.get('HTTP_REFERER', '/'))` it returns this error message: AttributeError at /projectmanagement/delete/ProjectManagement/task/1 module 'django.apps' has no attribute 'get_model' -
can we apply date range filter on date if date data type or dtype is text or str?
models- `class RocCharge(models.Model):` `charge_id = models.IntegerField(blank=True, null=True)` `chname = models.CharField(max_length=100, blank=True, null=True, db_index=True)` `date_of_creation = models.TextField(default=date.today)` views- `from_date = request.GET.get('fromdate')` `to_date = request.GET.get('Todate')` `if from_date and to_date: combined_data = combined_data.filter(date_of_creation__gte=from_date, date_of_creation__lte=to_date)` my date of creation in mysql as well as in models in text format , but i want to perform date range filter from to range without changing date data type , my date in mysql like-21-12-2019 -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
This question is getting flagged as a duplicate, however the other question's problem is very different than mine in that the person did not run migrations. I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = … -
Why am I getting 'OperationalError at /account/me/ no such table: main_enroll' if I have the table clearly in main/models? [duplicate]
I have gotten the error 'Operational Error: No Such Table main_enroll' In Django, and I do not understand why as I have defined it properly: Main/Models.py: from django.contrib.auth.models import AbstractUser from django.conf import settings from django.db import models class Course(models.Model): course_name = models.CharField(max_length=30) course_slug = models.CharField(max_length=70) # Other course-related fields def __str__(self): return self.course_name class Enroll(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) course = models.ForeignKey('main.Course', on_delete=models.CASCADE) Accounts/Models.py: from django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): pass Screenshot of error: Copy & Paste view of error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/account/me/ Django Version: 5.0.2 Python Version: 3.11.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'main', 'welcome', 'userprofile', 'accounts'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\utils.py", line 105, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\backends\sqlite3\base.py", line 329, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above exception (no such table: main_enroll) was the direct cause of the following exception: File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\skeleton\userprofile\views.py", line 19, in account_page Enroll.objects.create(user=user, course=course) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\shaur\BrainBall\Website\venv\Lib\site-packages\django\db\models\query.py", … -
Incoming file from post is "fakepath"
Brand new to react. My file is sending as a fakepath. I know this is for browser sercurity but I expected it to be different in my view. When I deserialize the request.body with json.loads I get this FileNotFound error. fitz.FileNotFoundError: no such file: 'C:\fakepath\HW 3 CPSC 332.pdf' When I deserialize the body with my own serializer it returns that the object is not valid. I am assuming this is due to the same issue with the fake file path. request.body b'{"title":"sdfg","content":"","file":"C:\\\\fakepath\\\\HW 3 CPSC 332.pdf"}' views.py @api_view(['POST']) def createPost(request): serializer = SinglePostSerializer(data=request.body) if serializer.is_valid(): serializer.save() return Response({'message': 'File uploaded successfully'}, status=status.HTTP_201_CREATED) else: return Response({'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) serializers.py class SinglePostSerializer(ModelSerializer): class Meta: model = Post fields = '__all__' models.py # Create your models here. class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=50) likes = models.IntegerField(default=0) comment_count = models.IntegerField(default=0) pdf_file = models.FileField(upload_to='media/pdfs/') images = models.ManyToManyField(SheetMusicImage) comments = models.ManyToManyField('Comment', blank=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.pdf_file.name CreatePostPage.js import React, { useState, useEffect} from 'react' const CreatePostPage = () => { const [formData, setFormData] = useState({ // Initialize form fields here // For example: title: '', content: '', }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value, }); }; … -
Websocket connection doesn't work with redis cluster
I'm trying to establish a websocket connection but it doesn't seem to work due to my redis server which is a cluster from elasticache. Here are the logs: Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/consumer.py",> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await handler(message) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels/generic/webso> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/shipninja/shipninja/shipninja/consumers.py", line 36, in> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.channel_layer.group_add("inventory", self.channel_name) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/channels_redis/core.py> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.zadd(group_key, {channel: time.time()}) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/client.p> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: conn = self.connection or await pool.get_connection(command_name, **optio> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await self.ensure_connection(connection) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: await connection.connect() Feb 27 03:54:24 ip-172-31-40-162 python[12684]: File "/home/ubuntu/venv/lib/python3.10/site-packages/redis/asyncio/connecti> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: raise ConnectionError(self._error_message(e)) Feb 27 03:54:24 ip-172-31-40-162 python[12684]: redis.exceptions.ConnectionError: Error -2 connecting to rediss://clustercfg.> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: Future exception was never retrieved Feb 27 03:54:24 ip-172-31-40-162 python[12684]: future: <Future finished exception=gaierror(-2, 'Name or service not known')> Feb 27 03:54:24 ip-172-31-40-162 python[12684]: socket.gaierror: [Errno -2] Name or service not known Feb … -
Django - Problem with posting new date value to a class from models.py
I'm trying to save a date value to a datefield from the django default database but it always return a None value even if the query to add this value isn't None. I tried to convert this date to string and datetime.date type and that didn't solve my problem. I'll post the html, models.py and views.py files. -
Django sitemap.xml shows plain text
I have added sitemaps following Django 2.0 (I cannot upgrade for now) official documentation. When accessing my production site I get all the correct links with dates but as plaintext, without xml formatting. The google search console is not accepting this format. My sitemap.py code: from blog.models import Post from django.contrib.sitemaps import Sitemap from courses.models import Course, Interview, Lesson class PostSitemap(Sitemap): changefreq = 'weekly' priority = 0.9 def items(self): return Post.objects.all() def lastmod(self, obj): return obj.updated ... My urls.py code: path( "sitemap.xml", sitemap, {"sitemaps": { "courses": CourseSitemap, "posts": PostSitemap, "lessons": LessonSitemap, "podcasts": InterviewSitemap, }}, name="django.contrib.sitemaps.views.sitemap", ), How can I change it to XML format? -
Websocket connection with uvicorn/django/nginx not working
I am trying to establish a websocket connection in my app but I'm getting different errors. I'm using elasticache redis cache and my settings.py looks as follows: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": ["rediss://redis-m0rn9y.serverless.use1.cache.amazonaws.com:6379"], }, }, } I've configured my channel_layers numerous times but this one allows me to establish a connection at least before it closes: Feb 26 23:54:37 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/get_user_inventory/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/api/check_session/ HTTP/1.0" 200 OK Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Not Found: /app/inventory/styles.css.map Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: 128.6.36.223:0 - "GET /app/inventory/styles.css.map HTTP/1.0" 404 Not Found Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: ('128.6.36.223', 0) - "WebSocket /ws/inventory/" [accepted] Feb 26 23:54:38 ip-172-31-40-162 python[9623]: WebSocket connected to the group 'inventory'. Feb 26 23:54:38 ip-172-31-40-162 python[9623]: INFO: connection open Feb 26 23:54:38 ip-172-31-40-162 python[9623]: ERROR: Exception in ASGI application Feb 26 23:54:38 ip-172-31-40-162 python[9623]: Traceback (most recent call last): Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/protocols/websockets/websockets_impl.py", line 255> Feb 26 23:54:38 ip-172-31-40-162 python[9623]: result = await self.app(self.scope, self.asgi_receive, self.asgi_send) Feb 26 23:54:38 ip-172-31-40-162 python[9623]: File "/home/ubuntu/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 84, in __call__ Feb … -
Expose host port 80 of a Dockerized Django app deployed on AWS Fargate
I have a very simple Django rest framework (DRF) app that is dockerized and deployed on AWS ECS with Fargate. I created a security group to expose the port 8000 on the inbound rules and was able to see the app at public IP 12.34.56:78:8000/ I wanted to have the app run on port 80, but don't know how to. Do I need to expose 80 on the Dockerfile and specify that port when creating the task definition? Or do I need to set up nginx to pass HTTP requests to port 8000 internally? Dockerfile: # Pull base image FROM python:3.12 # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # Copy project COPY . . # Expose the Django development server port EXPOSE 8000 # # Start the Django development server CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Task definition: { "taskDefinitionArn": "arn:aws:ecs:us-west-1:123:task-definition/app-task:12", "containerDefinitions": [ { "name": "container-name", "image": "dockerhub/app:latest", "cpu": 0, "portMappings": [ { "name": "default", "containerPort": 8000, "hostPort": 8000, "protocol": "tcp", "appProtocol": "http" } ], "essential": true, "environment": [], "mountPoints": [], "volumesFrom": [], "logConfiguration": { "logDriver": "awslogs", "options": … -
Is there a way to temporarily remove items from a session and re-add after code has run
I am working on an e-commerce site, using Django. I am trying to add a custom order to the bag which is happening, however now I cannot add other products to the bag when the custom order is in the bag. I was thinking if I removed the custom_order from the session, it would allow the other code to run, in order to add products to the bag. context.py from decimal import Decimal from django.conf import settings from django.shortcuts import get_object_or_404 from products.models import Product from custom_order.models import CustomOrder def bag_contents(request): bag_items = [] total = 0 bag = request.session.get('bag', {}) print(bag) if 'custom_order' in bag: custom_order_id = bag['custom_order'] custom_order = CustomOrder.objects.get(pk=custom_order_id) total += custom_order.price bag_items.append({ 'product_id': custom_order.product_id, 'custom_order_id': custom_order_id, 'category': custom_order.category, 'material': custom_order.material, 'individual_total': custom_order.price, 'quantity': 1, 'product_name': custom_order.product_name }) else: for product_id, quantity in bag.items(): product = Product.objects.get(pk=product_id) if isinstance(quantity, int) and isinstance(product.price, Decimal): total += quantity * product.price individual_total = quantity * product.price product_count += quantity bag_items.append({ 'product_id': product_id, 'quantity': quantity, 'product': product, 'individual_total': individual_total, }) grand_total = total context = { 'bag_items': bag_items, 'grand_total': grand_total, } return context View to add product to bag def add_to_bag(request, product_id): """ Add a quantity of the specified product to … -
How to save multiple values from dropdown with foreign key
I want to save multiple store ids in Test table in store_id column. What is the best way to design model to save multiple store ids in Test table models.py class Store(models.Model): store_name = models.CharField(max_length=100, verbose_name="store") def __unicode__(self): return '%s' %(self.name) def __str__(self): return self.name class Test(models.Model): store_id = models.ForeignKey(Store, on_delete=models.CASCADE, db_column='store_id') def __unicode__(self): return '%s' %(self.id) Forms.py class TestForm(ModelForm): def __init__(self, *args, **kwargs): self.fields['store_id'] = ModelChoiceField(queryset=Store.objects.all(), widget=SelectMultiple(attrs={'class':'form-control'}) class Meta: model = Test fields = ('store_id',) -
How to setup cookiecutter-django to run functional tests with Selenium?
I am using Cookiecutter Django with Docker and Webpack. I'm struggling to use Selenium for functional tests with the way Cookiecutter Django template is set up. I have added a Selenium container: selenium_chrome: image: selenium/standalone-chrome:latest container_name: local_selenium_chrome ports: - '4444:4444' volumes: - /dev/shm:/dev/shm I am using Django StaticLiveServerTestCase in my functional test. This is launching a live Django server on a random port, which I can access like this: self.browser.get(self.live_server_url). However, the static files are missing (CSS and JS) because they are served from a node container in the Cookiecutter Django local setup. What is the correct way to update my Cookiecutter Django template to be able to run Selenium tests with full static assets available? -
Djangosaml2 implementation with azure SSO with an existing Django app having independent Login
I am a new comer in Django field. I have an existing Django application with independent login implemented. The task is to integrate Azure AD Single Sign On using SAML protocol. The flow is user request for application url, it will redirect to the Azure portal, Signed in using federated credential automatically and redirect to the requested url or a specific app url after authorize. I am using djangosaml2 librery. I am able to redirect to the Azure portal but while authenticating I am getting "csrf verification failed" error. Basically I have zero knowledge about how django authentication works and how to integrate the response from azure in django. Any one please help me out with a through walkthrough of the SSO authentication process with SAML. How to get the attributes from SAML and how to authenticate and authorize. My current project structure is given below. my-project templates app1 login home proj settings.py remote_xml_metadata.xml urls.py views.py app1 urls.py views.py` -
How to pass AWS ELB health check with Django ALLOWED_HOSTS = [my-site.com]
I have a Django application deployed on AWS via ECS (Dockerized) using gunicorn and nginx. As the DEBUG=False for Django deployment I've configured a logging setting to receive logs on WARNINGs & above via mail_admins. With a standard setup on nginx configuration (below) I started to receive tons of logs (mails) with 'BadRequest' or 'DisallowedHost' errors (most probably scanning/scraping bots) which were rejected by Django as I have set my ALLOWED_HOSTS=[my-site.com]. nginx.conf upstream django-backend { server 172.17.0.1:8000; } server { listen 80; location / { proxy_pass http://django-backend; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_redirect off; } } I followed examples from following solutions to block the traffic hitting my Django application: by @Brent O'Connor from here by @Janusz Skonieczny from here nginx docs here Having ultimately nginx.conf updated with: server { listen 80; server_name ""; return 444; } server { listen 80; server_name my-site.com; # Rest of configuration } This worked quite well, however, I couldn't setup the nginx in such way to allow AWS ELB to perform the Health check and I had following logs in AWS: xxx.xx.xx.xx - - [26/Feb/2024:19:30:03 +0000] "GET /health HTTP/1.1" 444 0 "-" "ELB-HealthChecker/2.0" "-" xxx.xx.xx.xx - - … -
Are there any best practices for handling arbirary rules by US State?
This question is incredibly hard to google because of what state means in software development. I am creating a web app that handles specific laws based on State. These laws often have nothing to do with each other on a State by State bases. For example if it was laws on food sales, one State might say "you can only sell ice cream on Tuesdays" and another might say "every receipt for vegetable sales must be green". Are there any best practices for arbitrary specific rules in a code-base? Obviously, I could throw if statements in for every use case but it will make the code super messy. I am thinking of creating a service class that can point to the State requirements for different from one location but will keep State logic separate from the core shared logic. For reference it is a pretty typical infrastructure with a React-based front-end, Django back-end and mysql DB. -
I'm having trouble verifying my reCAPTCHA
I have a project with django, and I have a signup template, in this I put a recaptcha so that when it is completed it validates it, but when I was testing, I filled out the form and it told me "reCAPTCHA error, try again later" So I have view: def signup(request): if request.method == 'GET': return render(request, 'signup.html', {'form': UserSignUpForm()}) else: form = UserSignUpForm(request.POST) if form.is_valid(): if verificar_recaptcha(request.POST.get('g-recaptcha-response')): if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user( username=request.POST['username'], password=request.POST['password1'], first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'] ) user.save() login(request, user) return redirect('mensaje') except IntegrityError: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'El usuario ingresado ya se encuentra registrado' }) else: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'Las contraseñas no coinciden' }) else: return render(request, 'signup.html', { 'form': UserSignUpForm(), 'error': 'Error de reCAPTCHA. Por favor, inténtalo de nuevo.' }) else: return render(request, 'signup.html', {'form': form}) I have another file that does the verification import requests def verificar_recaptcha(token): secret_key = 'secretkey' url = 'https://www.google.com/recaptcha/api/siteverify' payload = { 'secret': secret_key, 'response': token } response = requests.post(url, data=payload) data = response.json() if data['success']: return True else: return False I tried changing the views but nothing happens. -
from django.urls import path ImportError: cannot import name 'path' from 'django.urls'
I am very beginner in Python. I have project in Python 3.8 and Django. When I try update my old Django to Django 1.11 i have error: ** from django.urls import path ImportError: cannot import name 'path' from 'django.urls' (/home/ds/.local/lib/python3.9/site-packages/django/urls/init.py)** My file: from django.urls import path from django.contrib.auth.views import login from .views import * urlpatterns = ['', path(r'^$', 'go.insurance.views.index'), path(r'^abc/', include('go.abc.urls')), path(r'^help/', include('go.help.urls')), path(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt')), ] if settings.DEBUG: urlpatterns += ['', path(r'^media/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': settings.MEDIA_ROOT, }), ] What i make: update: requirements/base.txt => Django==1.11.29 /mnt/c/Project/.venvs/bin/python3 -m pip install --upgrade pip /mnt/c/Project/.venvs/bin/pip3 install django==1.11 /.venvs/bin/python3 manage.py runserver in folder requrements When i run my app i have error: ./.venvs/bin/python3 manage.py runserver I have error: Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x7fdc2c9b91f0> Traceback (most recent call last): File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/base.py", line 356, in check all_issues = self._run_checks( File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/mnt/c/Project/.venvs/lib/python3.9/site-packages/django/utils/functional.py", line 35, … -
TemplateDoesNotExist at Django python issue
I am new to Python and trying work on Django framework! as a basic I am trying to fetch values from HTML but I am getting the error "TemplateDoesNotExist at" My code is : def home(request): return render(request,'/templates/home.html') path of the file shown in this image is i am giving wrong path ? -
Django Content-Disposition not working as expected
I'm trying to build a functionality with Django, Gunicorn and Nginx where a user can request for a pdf download by submitting their email, after which a custom download link will be sent to their email. Clicking on the custom link should prompt the user to download the pdf. However, I keep getting "Page not found error". Below is my models.py file: from django.db import models import string import random class BrochureToken(models.Model): email = models.EmailField(blank=True) token = models.CharField(max_length=20, unique=True) # Random token is_used = models.BooleanField(default=False) # Flag to track if the token has been used def generate_token(self): length = 20 chars = string.ascii_letters + string.digits self.token = ''.join(random.choice(chars) for _ in range(length)) def save(self, *args, **kwargs): # Generate token before saving if it's not already set if not self.token: self.generate_token() super().save(*args, **kwargs) def __str__(self): return self.email Below is my views.py file: class BrochreRequest(generics.CreateAPIView): queryset = BrochureToken.objects.all() serializer_class = BrochureSerializers permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = BrochureSerializers(data=request.data) if serializer.is_valid(): print("Serializer is valid") serializer.save() email = request.data.get("email") token, created = BrochureToken.objects.get_or_create(defaults={'email': email}) download_link = f'https://api.mysite.com/api/filedownload/brochure/{token.token}' send_mail( 'Download The OIC Brochure', f'Click the link to download the brochure: {download_link}', settings.EMAIL_HOST_USER, [email], fail_silently=False ) return Response(serializer.data, status = status.HTTP_200_OK) else: return …