Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
drf-spectacular not recognizing file upload type
I have a Django endpoint that takes a file upload My annotations look like this @extend_schema( request=UploadObservationalSerializer, responses={ 200: GenericResponseSerializer, 400: OpenApiResponse( response=ErrorResponseSerializer, description="Validation error or parsing error" ), 500: ErrorResponseSerializer }, description="Allow user to upload observational data" ) Here is my serializer: class UploadObservationalSerializer(BaseSerializer): calibration_run_id = serializers.IntegerField(required=True) observational_user_file_path = serializers.CharField(required=True) observational_file = serializers.FileField(required=True) def validate_observational_file(self, value): request = self.context.get('request') files = request.FILES.getlist('observational_file') if len(files) != 1: raise serializers.ValidationError("Only one observational file should be uploaded.") return value But in the Swagger, drf-spectacular lists observational_file as a String, not a File Field { "calibration_run_id": 0, "observational_user_file_path": "string", "observational_file": "string" } Why is drf-spectacular not recognizing the file field? -
How can I call delay task in zappa django
In celery I can call task with <func_name>.delay() How can I do it in zappa? I have task: @task() def task_name(): pass -
Implementations of users in django
i was face with problem in implementing users logic, i have five users with the different roles. So in that five users there is admin which have all abilities of system. so i want to add another users which is called master super user. I want to have ability to login than the other users(admin and other users). so even the system is used by the owner ( admin and others) , but i can login and check details. so how can i handle that logic ? am trying to implement but the master super user is like the admin. i want to be unique -
from myshop.shop import views ModuleNotFoundError: No module named 'myshop.shop'
[enter image description here](ht[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/[enter image description here](https://i.sstatic.net/65otzFwB.png)AJ3ur5i8.png)p4Ait5fgenter image description here.png)tps://i.sstatic.net/nY8mtrPN.png) Actually, this is what my project looks like, but for some reason Django doesn't see the module, I've already tried a bunch of things, but nothing helped. Maybe there is someone faced with this ? -
Heroku Django performance issues - Request Queuing
We run a Django application on Heroku, and lately we've been seeing some performance issues. We have New Relic APM add-on installed, and I can see that any time there is a peak in response times, the time is mostly spent in what New Relic calls "Request Queuing" (see attached image). enter image description here Can someone help me figure out what the problem is here? Why are requests queued? Is this a horizontal scaling issue? It does not seem like the Python app itself is Any help welcome! Kind regards, Martijn -
An error occurred while attempting to login via your third-party account in microsoft allauth callback in django
The all auth settins for microsoft is provided here. The authedication is success and getting 200 after microsoft login. [03/Sep/2024 11:44:38] "GET /accounts/microsoft/login/callback/?code=M.C532_BL2.2.U.aec38xxxxxxx0f2ee&state=fi0hMAxxxxU2K HTTP/1.1" 200 1119 Finally page show error Third-Party Login Failure An error occurred while attempting to login via your third-party account. SOCIALACCOUNT_PROVIDERS = { "microsoft": { "APPS": [ { 'client_id': '14bb4', 'secret': 'ed91f8adc68', "settings": { "tenant": "consumers", "login_url": "https://login.microsoftonline.com", "graph_url": "https://graph.microsoft.com", }, 'SCOPE': [ 'openid', 'profile', 'email', ], 'AUTH_PARAMS': { 'response_type': 'code', }, 'OAUTH_PKCE_ENABLED': True, 'TENANT': 'common', 'LOGIN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize', 'TOKEN_URL': 'https://login.microsoftonline.com/common/oauth2/v2.0/token', 'GRAPH_URL': 'https://graph.microsoft.com', } ] } } The authendication and azure directry configuration is fine, no error description is available on the call back side from django allauth. i found that the same will work here - https://allauth.org/ but there is no specific description in this page. The callback function is not working after authentication success. -
How do I correctly render a django-view using Apphooks in django-cms?
I am building a project in Django CMS using version 4.1.2. Part of the project will be a news-section, for which I defined a Django model like this: # news/models.py from django.db import models from django.utils import timezone from djangocms_text_ckeditor.fields import HTMLField class Post(models.Model): title = models.CharField(max_length=200, verbose_name="Title") text = HTMLField(verbose_name="Text") user = models.ForeignKey('auth.User', on_delete=models.CASCADE, verbose_name="Author", blank=True, null=True) date = models.DateTimeField(default=timezone.now, verbose_name="Date") class Meta: verbose_name = "Post" verbose_name_plural = "Posts" def __str__(self): return self.title I want this model to be a django model instead of handling it with CMS-Plugins, so that editors can manage Posts using the admin-interface and to make it easier to use things like pagination. I have a little experience with Django, but not really with Django CMS. However, on the page displaying the news-section, I also want to have a header, a sidebar and a footer that should be editable using the CMS-Toolbar. Therefore I made an Apphook - from what I understand this should allow me to integrate the news-page with Django CMS. This is what my Apphook looks like: # news/cms_apps.py from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.urls import path from django.utils.translation import gettext_lazy as _ from news import views @apphook_pool.register … -
Django Template: How to connect chat script passing in Django Tag with JavaScript?
I'm working on a Django project where I need to conditionally render and execute a chat script based on user cookie consent. Here's what I've got so far: In my Django template, I have the following snippet: {% if page.page_type.chat_script %} {{ page.page_type.chat_script|safe }} {% endif %} This snippet is responsible for rendering a chat script (something like chat script code) which is set via the Django admin panel. However, I only want this script to execute if the user has accepted all cookies. I already have a separate JavaScript file (cookies_configuration.js) that handles cookie consent and injects various scripts into the head or body once consent is given (it works pretty fine when I use it with normal different scripts placed in other files). Here's a simplified example of how that injection looks (a little snippet from my code): 'injections': [ { 'location': 'head', 'code': 'initGoogleAnalytics()' }, ] Now, I want to do something similar for the chat script—essentially wrap the Django template snippet in a function like initChatScript() and then call this function only after cookie consent is granted. However, I'm not sure how to dynamically include and execute this Django template code within the JavaScript function. I've … -
Django update form sending additional field using AJAX
I have Django ModelForm contains Select2 field. I'm using jquery to send AJAX request on backend depends on select2 field choosen and return updated form with additional fields replacing the previous one (same form class but with additinal kwargs). But this causes init problems with select2 as looks like updating the form "resets" event listener on that select2. Is there a way to send not whole form but particular fields as a response for further append on existing form? -
Overriding DRF ListAPIView list() method
I have a DRF Project, wich has a ListAPIView for a model called Category. This model, has a ForeginKey to itself named parent_category and with related name of subcategories. I want my URLs to behave like this: get a list of Categories with no parent: example.com/api/categories get a list of subcategories of an object with some id: example.com/api/categories/{id_here} models.py: class Category(models.Model): name = models.CharField(max_length=100) parent_category = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='subcategories') views.py: class CategoryList(generics.ListAPIView): queryset = Category.objects.all() serializer_class = CategorySerializer And I have no idea how to write my urls.py. Do I need DRF routers? or Django path works fine? I don't know which to choose or how to use them for this project. I thought if i override ListAPIMixin's list() method, it would work, but I don't even know what to write in that. -
Django Search View Not Filtering by Subcategory Name
Problem Description: I'm working on a Django project where I have a Product model that is linked to a SubCategory model through a ForeignKey. I want to implement a search functionality that allows users to search for products by their title and subcategory name. Model Definitions: Here are the relevant parts of my models: from django.db import models from shortuuidfield import ShortUUIDField class Category(models.Model): cid = ShortUUIDField(length=10, max_length=100, prefix="cat", alphabet="abcdef") title = models.CharField(max_length=100, default="Food") image = models.ImageField(upload_to="category", default="category.jpg") class SubCategory(models.Model): sid = ShortUUIDField(length=10, max_length=100, prefix="sub", alphabet="abcdef") category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='subcategories') title = models.CharField(max_length=100) class Product(models.Model): pid = ShortUUIDField(length=10, max_length=100, prefix="prd", alphabet="abcdef") category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name="products") subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null=True, blank=True, related_name="products") title = models.CharField(max_length=100, default="Apple") description = models.TextField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True) Search View Implementation: I have implemented the search functionality as follows: from django.db.models import Q from django.shortcuts import render from .models import Product def search_view(request): query = request.GET.get('q') if query: products = Product.objects.filter( Q(title__icontains=query) | Q(description__icontains=query) | Q(subcategory__title__icontains=query) # Trying to filter by subcategory name ).order_by('-date') else: products = Product.objects.none() context = {'products': products, 'query': query} return render(request, 'core/search.html', context) Issue: The search by title works as expected, but filtering by subcategory name doesn't … -
Apache: UnicodeEncodeError when opening Django template file with non-ascii character in file name
In my Django app I had a bit code that would check if a template with some file name exists: from django.template.loader import get_template def has_help_page(name): """Return whether a help page for the given name exists.""" try: get_template(f"help/{name.lower()}.html") except TemplateDoesNotExist: return False return True The name argument is derived from a Django model's verbose name, and some models have verbose names that contain non-ascii characters (f.ex. "Broschüre"). When running locally or in a Docker container (via mod_wsgi), this works absolutely fine. But when I let Apache serve the app from a Debian machine (Apache/2.4.56 (Debian)), and when I request a page that would call the above function with a name that contains an Umlaut I get an UnicodeEncodeError: Traceback (most recent call last): File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/contrib/auth/mixins.py", line 109, in dispatch return super().dispatch(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/base.py", line 143, in dispatch return handler(request, *args, **kwargs) File "/srv/archiv/MIZDB/.venv/lib/python3.9/site-packages/django/views/generic/list.py", line 174, in get context = self.get_context_data() File "/srv/archiv/MIZDB/dbentry/site/views/base.py", line 1127, in get_context_data ctx = super().get_context_data(**kwargs) File "/srv/archiv/MIZDB/dbentry/search/mixins.py", line 62, in get_context_data ctx = super().get_context_data(**kwargs) … -
How does web development works?
I'm planning on creating a website for my project and this is my first time doing it. I browsed all over the internet and I learnt few things. However im not able to understand the logic of it. I'll explain what I understood and how I am going to approach it, if my understanding is wrong can anyone correct it? As far as I understand, to create a front end, I have to use HTML and css along with javascript and I am planning on using a jQuery framework for it. when it comes to back end, it is very confusing for me. but this is what I understood. I have to create a database which I'm planning on using Mysql for it. too all the data collected from the frontend should be stored there and any requested data from the frontend should be sent from the database, so for my frontend to communicate with my database which I created using MYSql it requires a API. Here I need a software architecture for which I am using RESTAPI however I dont understand the role of the architecture. so for me to build REST API I have to use a framework, … -
React-django npm errors
Folder Structure: (https://i.sstatic.net/oJ63TecA.png) Error message: (https://i.sstatic.net/FybPFJ9V.png) I am trying to implement the index.html I created with my react-django framework. I am using REST. From my understanding, I need to use this npm command but this is the error I'm getting. I attached my folder structure as well in case I am missing something there. Any ideas on how to proceed? I tried creating a package.json file which included the script for build but the error persisted. -
Unauthorized response to POST request in Django Rest Framework with Simple JWT
I am doing a project with REST API and Django Rest Framework. I currently have an issue in my post request where some of my endpoints return HTTP 401 Unauthorized, though all other get or update objects are returning correct responses. I am using -> djangorestframework-simplejwt==5.2.2. settings.py INSTALLED_APPS = [ # ... 'rest_framework_simplejwt.token_blacklist', # ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), 'REFRESH_TOKEN_LIFETIME': timedelta(days=50), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, "JSON_ENCODER": None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } main urls.py schema_view = get_schema_view( openapi.Info( title="Blog Backend API's", default_version="v1", description="This is the documentation for the backend API", terms_of_service="http://mywebsite.com/policies/", contact=openapi.Contact(email="sabab@gmail.com"), license=openapi.License(name="BDSM License"), ), public=True, permission_classes=(permissions.AllowAny, ) ) urlpatterns = [ path('admin/', admin.site.urls), path("api/v1/", include("api.urls")), path("", schema_view.with_ui('swagger', cache_timeout=0), name="schema-swagger-ui"), ] views.py class PostCommentApiView(APIView): @swagger_auto_schema( request_body=openapi.Schema( type=openapi.TYPE_OBJECT, properties={ 'post_id': openapi.Schema(type=openapi.TYPE_INTEGER), 'name': openapi.Schema(type=openapi.TYPE_STRING), 'email': openapi.Schema(type=openapi.TYPE_STRING), 'comment': openapi.Schema(type=openapi.TYPE_STRING), }, ), ) def post(self, request): post_id = request.data["post_id"] name = request.data["name"] email = request.data["email"] comment = request.data["comment"] post = api_models.Post.objects.get(id=post_id) api_models.Comment.objects.create( post=post, name=name, email=email, comment=comment, … -
Wagtailmenus does not seem to recognize the sub_menu tag in my install
First of all, all of these pages have the "Show in menu" item checked, and in my menu config, it has "Allow 3 levels of sub-navigation" selected. Apologies if I'm being short, but I lost this question the first time I tried to post it. The browser went into perpetual loading state. There is a tutorial in the first few pages of the wagtailmenus plug-in. I'm following that tutorial, which cuts off half-way through and instead turns into a tag reference manual. The docs are terrible due to that, and it's a little bit of divination studies based on bad writing. Based on the tutorial, however, I have in my config: ` INSTALLED_APPS = [ 'home', 'scripts', 'settings', 'triggers', 'tasks', 'schedules', ..... 'wagtailmenus', 'wagtail_modeladmin', # if Wagtail >=5.1; Don't repeat if it's there already ] ..... TEMPLATES = [ { .... "context_processors": [ .... 'wagtailmenus.context_processors.wagtailmenus', ], }, }, ]` I have this menu structure: -my dashboards (There are no sub-menus here.) -settings -Triggers -Scripts -Tasks -Schedules This is really just items created to get this displaying before I add additional items. I only want the sub-menus to display, but they won't do so. My templates are setup according to the … -
Django static url not seem to be loading css file
I'm actually new to Django and tried to load my theme into newly created project. I have a home.html template file placed at {APP_NAME}/templates/ directory of my Django project. The APP_NAME is called website here and projectname is dentist. Here is the structure top-level directory of project: dentist env (virtual environment) static website css templatemo_style.css images ... website templates home.html manage.py As you see the static files are placed in the static under the APP_NAME. Now here is the home.html: {% load static %} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>free template one - templatemo</title> <meta name="keywords" content="" /> <meta name="description" content="" /> <link href="{% static 'website/css/templatemo_style.css' %}" rel="stylesheet" type="text/css" /> </head> And this is settings.py added configuration: STATIC_URL = 'static/' STATICFILES_DIR = [ os.path.join(BASE_DIR,'static') ] But now the problem is whenever I load the project, the css file is not being loaded and the html is corrupted! I check the source code and it shows this link: <link href="/static/website/css/templatemo_style.css" rel="stylesheet" type="text/css" /> However it is not found and the page comes up this way: -
I'm getting a 400 error and the endpoint isn't even entered. Why?
I've encountered a situation with my Django Rest Framework (DRF) app in which a client mobile app is calling one of my endpoints and is getting a 400 error, but I can't debug what's going wrong. This is what appears in the log: Sep 02 11:11:29 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cBB2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=fad10208-c01d-4f64-9640-1aff889ab3ee fwd="66.246.86.216" dyno=web.1 connect=0ms service=1ms status=400 bytes=28 protocol=https If I send the same URL via Postman the endpoint returns successfully: Sep 02 11:41:48 myapp heroku/router at=info method=POST path="/users/generate_otp/?device_token=cKY2x2Y2L04qpQCbYukR31%3AAPA91bEHqCZ3ztI9wim0EzxVZ1Nv6clZMfsDxw7_6reWIVkm5dQcxuWlifnfxkn7Ope_2wTM75_TMw6BV-pAZyEYdrICz1dsk2gX6_aYJwz0-H3SDR2vLWvceiioUs21dTwXQIMwmBN1&mobile=%2B13104014335&device_type=ios" host=myhost.com request_id=4ddabe5f-619d-4665-aff5-28afb9ac277d fwd="66.246.86.216" dyno=web.1 connect=0ms service=572ms status=200 bytes=1686 protocol=https I've tried to examine the request that comes in, by making these the first lines of the endpoint: @action(detail=False, methods=["POST"]) def generate_otp(self, request): """ Text a one-time password to the given mobile number to login. If there's not yet a user with that number, register them. """ print("IN GENERATE OTP", flush=True) print("IN GENERATE OTP, request.data =", request.data, flush=True) print("IN GENERATE OTP, request.headers =", request.headers, flush=True) But those print statements never get called -- so it's as if it's not entering the endpoint at all. To try to debug what's being sent in the request further, I added this middleware: class RequestLoggingMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): print("--- … -
i'm not able to delete a model object Field 'id' expected a number but got 'not found'
Models class User(AbstractUser, PermissionsMixin): WEBSITE_ROLLS = [ ("Owner","Owner"), ("Manager","Manager"), ("Operator","Operator"), ("Customer","Customer") ] username = models.CharField(max_length=150, null=True) email = models.EmailField(max_length=255, unique=True) phone = models.CharField(max_length=16, null=True, blank=True) img = models.ImageField(upload_to="images/profile",default="images/profile/default.jpg") roll = models.CharField(max_length=30, choices=WEBSITE_ROLLS, default='Customer') is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) joined_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] class Staffs(User): class Meta: proxy = True verbose_name = "Staff" verbose_name_plural = "Staffs" What i wrote in my CBV class StaffDeleteView(View): success_url = "accounts:profile_staff_add" model = Staffs def get(self, request, *args, **kwargs): staff_obj = self.model.objects.get(id=self.kwargs['pk']) staff_obj.delete() These are my models and i'm trying to delete a staff member, staff_obj fills with the specific data but it won't let me delete it. what am i doing wrong here? -
Django collectstatic Error: MissingFileError for a File That Exists with Correct Name and Path
I'm encountering a MissingFileError while running collectstatic in my Django project. The error message is as follows: Traceback (most recent call last): File "C:\Path\To\Project\manage.py", line 22, in <module> main() File "C:\Path\To\Project\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 209, in handle collected = self.collect() File "C:\Users\Username\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 154, in collect raise processed whitenoise.storage.MissingFileError: The file 'background_image_nislex8.jpg' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x000002CCDD5DE500>. The CSS file 'styles.css' references a file which could not be found: background_image_nislex8.jpg Please check the URL references in this CSS file, particularly any relative paths which might be pointing to the wrong location. I'm getting this error despite having changed the name of the file to background_image_nislex.jpg and updating the reference in the styles.css file to the same name. How can I resolve this issue and ensure that collectstatic recognizes the updated file name? What I've Tried: Verified that the file background_image_nislex.jpg exists in the correct directory. Updated the reference in the styles.css file to match the new filename. Cleared the … -
How to get https working in DRF deployed to AWS Fargate + API GW?
I'm struggling to set up a Django Rest Framework app in AWS to use TLS. I have an API Gateway v2 proxying requests to an Application Load Balancer that reaches some ECS containers (ECS cluster created via Fargate). API GW is doing the TLS termination and the connection to the LB is in HTTP. The load balancer listens on a different port than 443. The flow/URLs are like this: https://api-gw.example.com:443 -> http://lb-internal.foo:1234 -> ecs_containers This mostly works, except from internal links that are misrepresented. For example, in the root of my DRF API the URLs returned are like http://api-gw.example.com:1234/foo instead of https://api-gw.example.com/foo. This link does not work: wrong protocol and wrong port, but correct URL. I do have SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") on my settings.py. How can I get this setup to work as expected? How to troubleshoot further? -
how to iterate through django-friendship provided template tag
I am using Django 5.1 and django-friendship library. django-friendship provides some built in template tags that work but not when I try and iterate over them. so {% friends request.user %} returns a list of friends by username. But I cant seem to get any of the template tags work work when I iterate through them. {% if request.user != profile.user %} {% if profile.user in friends_list %} <p>You are friends with {{ profile.user.username }}.</p> <a href="{% url 'remove_friend' to_user_id=profile.user.id %}">Remove Friend</a> {% else %} {% for friend_request in friend_requests %} {% if friend_request.from_user == profile.user %} <p>{{ profile.user.username }} has sent you a friend request. Check your <a href="{% url 'view_friend_requests' %}">friend requests</a>.</p> {% elif friend_request.to_user == profile.user %} <p>You have already sent a friend request to {{ profile.user.username }}.</p> {% endif %} {% empty %} <a href="{% url 'send_friend_request' to_user_id=profile.user.id %}">Send Friend Request</a> {% endfor %} {% endif %} {% else %} {# This is the current user's own profile #} <h3>Your Friends</h3> {% if friends_list %} <ul> {% for friend in friends_list %} <li>{{ friend }}</li> {% endfor %} </ul> {% else %} <p>You have no friends yet.</p> {% endif %} {% endif %} Here is a … -
How can I add multiple rows from a table to one row of an another table?
actually I've explained everything in the title. Let's say I have two tables, one of them stores specific car model names(e.g Audi s3, Ford edge etc). Another one stores tire brands. Each car model good with different tire brands and some cars good with multiple brands(e.g., s3 good with Yokohama, Bridgestone and Micheline), so I need to add these tire brands to just one row. How can I do that? Thanks for helps. Database that I use is the MySQL with the Django models. -
Django Application CSS Not Applying Correctly Despite 200 Status Code?
I am developing a web app using Django and am using external CSS in my layouts. The static files, such as images, are working properly, but the CSS and JS are not functioning correctly. When I checked the Chrome developer tools, the CSS file is loading with a 200 status code. I have tried various techniques to resolve the issue, but nothing seems to be working. I tried troubleshooting but none of them worked. -
How to Upload and Process a File in Django Admin
I am working on a Django project where I need to upload a file via the Django admin interface, process it using a specific class, and then store the processed data in different models based on the file's content. The key requirement is that the file itself should not be saved in the database or the file system after it is uploaded. Here’s a summary of what I need: Upload a file (KML format) via Django Admin: I want to create a file upload field in the admin that allows users to upload a KML file. 2.Process the file using a custom class: After the file is uploaded, it should be immediately processed by a class I’ve written (KmlLicense), which extracts geometrical data from the KML file. Store processed data in other models: The extracted data (points, lines, polygons) should be stored in different models (LicensePoint, LicenseLine, LicensePolygon), depending on the geometry. No need to save the uploaded file: I don’t want the uploaded KML file itself to be saved either in the database or in the media directory of my Django project. Questions: How can I set up the Django admin to upload a file, process it with my …