Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-ckeditor5 showing question mark instead of symbols
hi recently i switched to django-ckeditor5 and in the HTML code I'm using this - my_project/ │── manage.py │── my_project/ │── app/ │ │── models.py ... ... but after saving code it is displaying like this my_project/ ??? manage.py ??? my_project/ ??? app/ ? ??? models.py ... ... why │── is replaced by ?. in development server it is showing correctly but in production there is issue that is coming. -
rerro context_processors in django
dictionary update sequence element #0 has length 0; 2 is required I have a module called context_processors that when enabled does not appear on the login page and gives an error But when I disable it, the login page appears context_processors.py: import datetime from django.contrib.auth.decorators import login_required from permission.models import UserPermission from salemali.models import Salemali from term.models import Term from user.models import Branch @login_required def date_context_processor(request): if request.user.is_authenticated: current_datetime = datetime.datetime.now() term = Term.objects.filter(status=1).order_by('-datestart') salemali = Salemali.objects.all() branch = Branch.objects.all() user_permissions = UserPermission.objects.filter(user=request.user).values_list('permission__name', flat=True) return { 'current_day': current_datetime, 'terms': term, 'salemali': salemali, 'branch': branch, 'user_permissions': user_permissions } setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'dashboard.context_processors.date_context_processor', ], }, }, ] -
How can i get the id from request body in django
def index(request): form = Postform() if request.method == 'POST': template_string = request.POST.get("body") >! here i want the id for some reason print("Original", template_string) rendered_content = render_template_content(template_string) print("Rendered", rendered_content) form = Postform(request.POST) if form.is_valid(): post = form.save(commit=False) post.body = rendered_content post.save() form = Postform(initial={'body':rendered_content}) else: form=Postform() return render(request, 'index.html', {"form": form}) I am using CKeditor in the frontend and is sending the whole text area in body {{product.name.1}} i want to extract this id -
How to limit google maps auto complete to only one country?
I have tried everything so my search input only gives autocomplete options from only Dominican Republic but I have not been able to achieve it, anyone here knows how to do this? <input type="text" id="searchInput" class="form-control" placeholder="Search for a location..." > let autocomplete; const input = document.getElementById('searchInput'); autocomplete = new google.maps.places.Autocomplete(input, { types: ['(cities)', 'geocode'], // Allow both city and address searches componentRestrictions: { country: 'do' } }); // Handle place selection autocomplete.addListener('place_changed', function() { const place = autocomplete.getPlace(); if (!place.geometry) { return; } -
django app: how to read a bit of html in javascript
I have a django app that has an design issue I'd like to fix: a script wants to inject a piece of html that contain django tags. What we have now works, but has some unfortunate aspects: Save the script as an html snippet that is nothing but a script: the first line is <script> and the last line closes that script. Pages which use this script import it just like any html snippet. This script sets a local variable to the html bit, as a long string, then finds where the html bit is wanted, and calls insertAdjacentHTML to insert it. So the snippet is an html file that contains nothing but a script, and that script in turn contains hard-coded html as a string. This is confusing to read and prevents our javascript and html linters from working on this snippet. But the code works, and the script can be used by any page by simply importing the one snippet. Is there a cleaner solution? My ideal solution would: Store the html bit in an html file. Store the script in a .js file. Allow pages that use the script to just load the script. I have tried … -
Why isn't the create method in my custom manager working?
I'm trying to create a custom manager for a model class in my Django project. The model classes Story and Plot have a one-to-one relationship. I want a new Plot instance to be automatically created when a new Story instance is created. Right now I do this through the view function, but it fails when testing Story object creation without the view function. I know there are a few ways to accomplish this, but I've decided to use a custom manager to add this post-creation logic by overriding the objects.create method. The relevant code is below: class Story(models.Model): ... other fields objects = models.Manager() class Plot(models.Model): ... other fields story = models.OneToOneField(Story, on_delete=models.CASCADE, null=True, default=None, related_name='plot') class StoryManager(models.Manager): def create(self, **kwargs): story = super().create(**kwargs) plot = Plot.objects.create( ... other kwargs, story_id=story.id ) return story # Assign the story manager to the Story model Story.objects = StoryManager() Now I'm getting the following traceback while running tests that use the Story.objects.create method: File "C:\Users\jacob\documents\programming\story-builder\storybuilder\app\models.py", line 221, in create story = super().create(**kwargs) File "C:\Users\jacob\documents\programming\story-builder\.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\jacob\documents\programming\story-builder\.venv\Lib\site-packages\django\db\models\query.py", line 669, in create self.model._meta._reverse_one_to_one_field_names ^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute '_meta' I'm new to the concept … -
Read data json in django
I am currently working on a project where users will be able to authenticate themselves thanks to a form that I protected with a csrf token, but for now I only take care of the server side party, here is the code: @api_view(['POST']) @csrf_protect @permission_classes([AllowAny]) def login(request): if request.method != "POST": return JsonResponse({"error": "Seules les requêtes POST sont autorisées."}, status=status.HTTP_405_METHOD_NOT_ALLOWED) try: # Lecture sécurisée des données data = json.loads(request.body) username = data.get("username") password = data.get("password") if not username or not password: return JsonResponse({"error": "Nom d'utilisateur et mot de passe sont requis."}, status=status.HTTP_400_BAD_REQUEST) # Recherche de l'utilisateur dans les deux tables user = None role = None try: user = Administrateur.objects.get(username=username) role = "admin" except Administrateur.DoesNotExist: pass if not user: try: user = Employes.objects.get(username=username) role = "employe" except Employes.DoesNotExist: pass if not user or not check_password(password, user.password): return JsonResponse({"error": "Identifiants incorrects."}, status=status.HTTP_401_UNAUTHORIZED) # Génération des tokens refresh = RefreshToken.for_user(user) # Réponse sécurisée response = JsonResponse({"username": user.username}) # Stocker le JWT dans un cookie HttpOnly sécurisé response.set_cookie( key='access_token', value=str(refresh.access_token), httponly=True, secure=True, samesite='Strict', max_age=3600 ) # Stocker le rôle pour le frontend response.set_cookie( key='user_role', value=role, httponly=False, secure=True, samesite='Strict', max_age=3600 ) return response except Exception as e: return JsonResponse({"error": f"Erreur inattendue : {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) … -
Why I am getting htmx:targetError when calling form.requestSubmit?
I am using htmx to load some content when openning an accordion in my django template. I initially include the cover card partial template and when I close the accordion I remove the whole partial template. Then whenever the accordion opens I dispatch a custom event to trigger the htmx swap and return the same partial template in the response. The code looks like this initially: ... <details open id="cover-card-section" hx-get="{% url 'update-cover-card' object.id %}" hx-swap="outerHTML" hx-target="#temp-cover-card-form" hx-trigger="open-cover-card-section"> <summary > Cover Card </summary> {% include "path/to/cover_card.html" %} {% comment %} Element to be replaced by actual cover card form {% endcomment %} <div id="temp-cover-card-form" style="display: none; align-items: center; justify-content: center; width: 100%; height: 200px;"> <svg width="40" height="40" stroke="rgba(0, 0, 0, 0.5)" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_V8m1{transform-origin:center;animation:spinner_zKoa 2s linear infinite}.spinner_V8m1 circle{stroke-linecap:round;animation:spinner_YpZS 1.5s ease-in-out infinite}@keyframes spinner_zKoa{100%{transform:rotate(360deg)}}@keyframes spinner_YpZS{0%{stroke-dasharray:0 150;stroke-dashoffset:0}47.5%{stroke-dasharray:42 150;stroke-dashoffset:-16}95%,100%{stroke-dasharray:42 150;stroke-dashoffset:-59}}</style><g class="spinner_V8m1"><circle cx="12" cy="12" r="9.5" fill="none" stroke-width="3"></circle></g></svg> </div> </details> ... The cover card partial template looks like this: <div class="container" id="cover-card-form-container" style="max-width:700px;" puny-settings> <style> ... </style> <div> <form id='image-upload-form' hx-swap="none" hx-encoding='multipart/form-data' hx-post='/en/home/upload-card-image/'> {% csrf_token %} {{ form.image.errors }} {{ form.image.label_tag }} {{ form.image }} <div style="display: none; width: 100%; align-items: center; gap: 8px; margin-bottom: var(--pico-spacing)" id="progress-container"> <progress style="width: 50%; margin-bottom: 0" id="progress-bar" value="0" … -
How to make the function stop immediately, when in websocket stop requested?
I want to stop running the generating function immediately, whenever stop_requested in the websocket. class ImageGeneration(BaseAIGeneration): async def process(self, websocket, prompt): if websocket.stop_requested: return None await super().process(websocket, prompt) if websocket.stop_requested: return None response = await self.generate_image(prompt=prompt, model=self.model, size=size) if websocket_instance.stop_requested or not response: return None if response and isinstance(response, list): image_url = response[0].url return image_url And generate_image function currently is synchronous function async def generate_image( prompt: str, model: str, size: str = "1024x1024" ): response = await client.images.generate( model=model, prompt=prompt, size=size, n=1 ) return response.data Currently it waits until generate_image fully runs, and only then stops. I was thinking of creating a task, that will gonna check if the response: while not task.done(): if websocket_instance.stop_requested: task.cancel() await asyncio.sleep(0.1) But for me this solution looks weird, and I do not think it is the correct way, how to make the function stop immediately, when in websocket stop requested? -
Deploying Django API with Render keeps loging 400 bad request
I am trying to host my Django API with renders free tier I have specified all the env variables including renders domain in allowed origins but I still get 400 Bad Request responses from renders logs. logs: 127.0.0.1 - - [24/Feb/2025:22:47:56 +0300] "HEAD / HTTP/1.1" 400 143 "-" "Go-http-client/1.1" ==> Your service is live 🎉 127.0.0.1 - - [24/Feb/2025:22:48:09 +0300] "GET / HTTP/1.1" 400 143 "-" "Go-http-client/2.0" my settings.py ALLOWED_HOSTS = env.list("ALLOWED_HOSTS") CSRF_TRUSTED_ORIGINS = env.list("TRUSTED_ORIGINS") CORS_ALLOWED_ORIGINS = env.list("CORS_ALLOWED_ORIGINS") all env variables are supplied on renders environment tab but it still fails -
Django/Celery SQLite database locked on concurrent access
I have a local Django 5.1/Celery 5.4 project that is using SQLite. I am the only user. Certain model saves trigger a Celery task that queries (SELECT) for the updated record (using the Django ORM), then runs an API call to update a remote record based on the local data, and then runs another UPDATE locally. The task wraps all this inside of with transaction.atomic():. (The Celery worker is configured to run tasks in serial.) While this task is running, any attempts to write to the database result in a "database is locked" OperationalError. I have configured Django/SQLite with the latest "production-ready" settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DB_DIR / 'db.sqlite3', 'OPTIONS': { 'init_command': """ PRAGMA foreign_keys=ON; PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA busy_timeout = 5000; PRAGMA temp_store = MEMORY; PRAGMA mmap_size=134217728; PRAGMA journal_size_limit=67108864; PRAGMA cache_size=2000; """, 'transaction_mode': 'IMMEDIATE', 'timeout': 20, }, }, } I was under the impression that with these settings, concurrent access was possible. "SQLite in Production" is the latest hotness, and these settings, especially the new-to-Django 5.1 'transaction_mode': 'IMMEDIATE' in OPTIONS, would allow writes to queue. What am I missing? -
dynamically instantiate database django
In a django web application, when logging in I am saving the name of the database in the session. I need a method to dynamically instantiate the database using this name that is saved in the user session. I dont't want to use "using()" because my aplication is already done, and it would give me a lot of work, neither by configuring multiple databases in your settings (because my databases are being createded dinamically) if there is another way i would like to know. Maybe it's not possible, i understand if it's the case... I tried middlewares, routes, threading, decorators but maybe a think i would have done something wrong. I exhausted my attempts. As far as I could go i get logged in the right database until the second screen of my application, when i am browsing in the application the 3 screen i pass the database goes back to default. middleware: import re from django.utils.deprecation import MiddlewareMixin from django.db import connections from .thread import set_banco_academia class DatabaseMiddleware(MiddlewareMixin): def process_request(self, request): """ Middleware que define dinamicamente o banco de dados a ser usado com base na sessão do usuário e adiciona a conexão ao Django. """ if not hasattr(request, … -
Django form doesn`t appear in page
I want to add posts in adding system from user profile page (without creating another page to adding). To profile page including html file for creating post I created model, form, view and html but have no idea why it isn`t working. The form doesn`t appear in page (except bottom "publish") include is working forms from django import forms from .models import Post, Comment class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text', 'photo', 'video'] views from django.shortcuts import redirect, render from .models import Post, Comment from .forms import PostForm, CommentForm # Create your views here. from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_GET, require_POST @login_required(login_url='users:login') def create_post(request): if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() return redirect('user:profile') else: form = PostForm() context = {'form': form} return render(request, 'post/create_post.html', context) create_post.html <div class="posts-section"> <div class="new-post"> <form method='post' enctype="multipart/form-data"> {{form.as_p}} {% csrf_token %} <button>Publish</button> </form> </div> </div> user_profile.html {% extends "base.html" %} {% load profile_tags %} {% block content %} </div> <div class="profile-info"> <p><strong>Email:</strong> {{ user.email }} </p> <p><strong>About:</strong>{{ profile.about }}</p> </div> {% include "post/create_post.html" %} </div> {% endblock content %} -
Is there any way to take add tooltip to the select2 li items?
i work on a django project where i also use bootstrap and select2. I have this HTML: {% load i18n %} <select id="{{ select_id }}" name="{{ select_name }}" class="form-control"> <option value="">{% trans 'Alege TVA' %}</option> {% for vat_rate in vat_rates %} {{ vat_rate.text_tooltip }} <option value="{{ vat_rate.actual_value }}" title="{{ vat_rate.text_tooltip }}"> {{ vat_rate.full_name }} </option> {% endfor %} </select> and this in JavaScript: $('#id_vat_value').select2({ placeholder: gettext("Alege TVA"), escapeMarkup: function (m) { return m; }, matcher: function (params, data) { return TrimSpacesSelect2(params, data); }, }) is there any way to add the tooltip to the select2 li items? I tried to add it in select2:open, but i don't think is really good, right now it is showing the tooltip but i don't know if it's the best choice. .on('select2:open', function () { setTimeout(function () { $('.select2-results__option').each(function () { var $option = $(this); var optionId = $option.attr('id'); var originalOption = $('#id_vat_value option').filter(function () { return $(this).val() === optionId.split('-').pop(); }); var tooltip = originalOption.attr('data-original-title'); if (tooltip) { $option.attr('title', tooltip); $option.attr('data-toggle', 'tooltip'); } }); $('[data-toggle="tooltip"]').tooltip({ delay: {show: 500, hide: 0}, trigger: "hover" }); }, 100); }); -
Where to deploy Next.js & Django
I have created a project that uses Next.js on the frontend and Django on the backend, the web app uses JWT for requests. Now I want to deploy the project and want to ask where I should do it? Do I have to use two different services or can I use one service for both? I have done the Next.js getting started tutorial where you get to create a dashboard app and deploy it using Vercel, that was very simple, can I do the same with this project? Also, I'd like to add that the database used currently while I'm developing is the default SQLite but I do want to switch to a "real" database like PostgreSQL, for example, later when launching. -
Django Celery: Kombu connection refused error
It seems a bit odd, maybe I'm missing something, but whenever I send tasks to celery queue it suddenly gives error: AttributeError: 'ChannelPromise' object has no attribute 'value' It works at first but if tasks are sent to the queue at a slightly higher frequency, it suddenly starts to give the above error. Looks like some kind of blocked process or something like that. Broker is aws sqs Celery settings: CELERY_RESULT_BACKEND = 'django-db' CELERY_BROKER_URL = 'sqs://' CELERY_BROKER_TRANSPORT_OPTIONS = { 'region' : 'us-south-1', #temp name 'visibility-timeout' : 3600, 'polling-interval' : 10 } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' Packages: celery = ">=5.0.5" django = "==4.2.16" kombu = "==5.4.2" django-celery-beat = ">=2.0.0" django-celery-results = ">=2.2.0" Files: project/init.py from .celery import app as celery_app __all__ = ['celery_app'] project/celery.py import os from celery import Celery from project.settings import settings # set the default Django settings module for the 'celery' program. #settings are kept inside a separate folder for multiple envs [project/settings/settings_prod.py,project/settings/settings_stag.py,project/settings/settings.py] os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.settings') app = Celery('project') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): pass Complete error trace: kombu.exceptions.OperationalError: [Errno 111] Connection refused on next try in production. complete … -
How to secure JWT tokens with a DRF backend supporting both mobile and SPA clients?
I am developing an application that uses the Django REST Framework to provide a REST API. I intend to protect it using token authentication, with the help of simple_jwt. Example API overview: /auth/login/: Supports POST, requires valid username and password, returns a JWT access and refresh /auth/refresh/: Supports POST, requires a valid refresh token, returns new access and refresh tokens /protected/endpoint/: Requires a valid access token From reading on CSRF I have gathered: CSRF is only needed if cookies are involved, so only use for the SPA client To persist the JWT token: SPA: Persist in an httpOnly cookie with secure=true and same-origin set App: Persist in however the app persistent state works So far so good, however, this would mean that my REST API needs to both require CSRF tokens for requests coming from the SPA and not require/ignore CSRF tokens for requests coming from mobile app clients. Since this is logically impossible I was first thinking of implementing 2 separate APIs. I.e.: /spa/auth/..., /spa/protected/...: For SPA clients, where all endpoints require a CSRF token /mobile/auth/..., /mobile/protected/...: For mobile clients, where all endpoints are CSRF exempt. But doing this just means that my CSRF protection is useless, since a … -
How to fetch real-time google cloud run job logs?
I am building a CI/CD kind of tool which is actually a web app. The stack is django-rest-framework on the backend and React (Vite) on the frontend. Currently the pipeline running and the actions from the stages that are running are all working, the jobs are being created, ran, deleted and it all works fine. This is all happening through the Google Cloud Run Jobs. For the app to make sense, I need to be able to get real-time logs from that specific job while it is running. Currently I have a crude temporary implementation where I am using the Google Cloud Logging API with filters to periodically get the logs for that job. This is the mentioned crude implementation: from google.cloud import logging_v2 from apps.docker_app.utils.google_credentials import get_google_credentials def _stream_job_logs(logging_client, log_filter): seen_entries = set() while True: entries = logging_client.list_entries(filter_=log_filter) for entry in entries: if entry.insert_id not in seen_entries: seen_entries.add(entry.insert_id) yield entry time.sleep(1) class GoogleLogsClient: def __init__(self): storage_credentials = get_google_credentials() self.client = logging_v2.Client(credentials=storage_credentials) def stream_job_logs(self, log_filter): for entry in _stream_job_logs( logging_client=self.client, log_filter=log_filter ): if "All stages completed successfully" in entry.payload: break timestamp = entry.timestamp.isoformat() print("* {}: {}".format(timestamp, entry.payload)) While this does work, I am limited to 60 read requests to the … -
Django Admin Not Displaying `creation_date` Field Despite Being in `list_display`
I have a Django project where I'm working on an e-commerce application. I'm using SQLite as my database, and I'm trying to add a creation_date field to my VendorProduct model so that it records when a product was created. What I Did I added the creation_date field to my VendorProduct model like this: models.py (VendorProduct Model) from django.db import models from django.utils.timezone import now from userauths.models import CustomUser class VendorProduct(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.SET_NULL, null=True, blank=True) creation_date = models.DateTimeField(auto_now_add=True, blank=True, null=True) def __str__(self): return self.title Migrations I ran the following commands to apply the migration: python manage.py makemigrations vendorpannel python manage.py migrate vendorpannel Then, I verified that the creation_date column exists in my database using: from django.db import connection with connection.cursor() as cursor: cursor.execute("PRAGMA table_info(vendorpannel_vendorproduct);") columns = cursor.fetchall() for column in columns: print(column) The output confirms that creation_date exists in my database: (7, 'creation_date', 'datetime', 0, None, 0) Admin Panel Configuration I updated my admin panel to display creation_date: admin.py from django.contrib import admin from .models import VendorProduct class VendorProductAdmin(admin.ModelAdmin): list_display = ('creation_date') readonly_fields = ('creation_date',) admin.site.register(VendorProduct, VendorProductAdmin) Problem: creation_date Not Showing in Django Admin Even after making these changes and applying migrations, the creation_date field is not appearing in … -
Cloudinary Upload Issue on PythonAnywhere: MaxRetryError
I'm developing a Django application that uses Cloudinary for image storage. When running the project locally, everything works fine, and images upload successfully. However, when I deploy the project on PythonAnywhere, I get the following error when trying to upload an image from the admin panel: Unexpected error - MaxRetryError("TCPKeepAliveHTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/di6geozk1/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x748d7df0b520>: Failed to establish a new connection: [Errno 111] Connection refused'))") Configuration in settings.py: CLOUDINARY_STORAGE = { 'CLOUD_NAME': env('CLOUDINARY_STORAGE_CLOUD_NAME', default=''), 'API_KEY': env('CLOUDINARY_STORAGE_API_KEY', default=''), 'API_SECRET': env('CLOUDINARY_STORAGE_API_SECRET', default=''), 'SECURE': True, 'API_PROXY': 'http://proxy.server:3128' } ### Things I've already checked: - The credentials (CLOUD_NAME, API_KEY, API_SECRET) are correctly set. - In my local environment, images upload successfully to Cloudinary. - In PythonAnywhere, the connection is refused. - I tried removing the 'API_PROXY' setting, but the error persists. -
wagtail empty results in pages api
I am getting empty results in wagtail api pages list. my models.py from django.db import models from wagtail.models import Page from wagtail.admin.panels import FieldPanel from wagtail.api import APIField from wagtail.fields import StreamField from wagtail.admin.panels import FieldPanel from streams import blocks class FlexPage(Page): banner_title = models.CharField(blank=True, max_length=200) banner_text = models.CharField(blank=True, max_length=2000) banner_cta_text = models.CharField(blank=True, max_length=100) banner_cta_url = models.URLField(blank=True, default="") banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) content = StreamField( [ ("youtube_block", blocks.YouTubeBlock()), ("image_block", blocks.ImgBlock()), ("section_heading", blocks.SectionHeading()), ("title_text_two_columns", blocks.TitleTextTwoColumns()), ], null=True, blank=True, use_json_field=True, ) content_panels = Page.content_panels + [ FieldPanel("banner_title", classname="full"), FieldPanel("banner_text"), FieldPanel("banner_cta_text"), FieldPanel("banner_cta_url"), FieldPanel("banner_image"), FieldPanel("content"), ] api_fields = [ APIField("banner_title"), APIField("banner_text"), APIField("banner_cta_text"), APIField("banner_cta_url"), APIField("banner_image"), APIField("content"), ] blocks.py from wagtail import blocks from wagtail.blocks.field_block import (BooleanBlock, CharBlock, PageChooserBlock, TextBlock, URLBlock) from wagtail.images.blocks import ImageChooserBlock as DefaultImageChooserBlock class ImageChooserBlock(DefaultImageChooserBlock): def get_api_representation(self, value, context=None): if value: return { "id": value.id, "title": value.title, "original": value.get_rendition("original").attrs_dict, "thumbnail": value.get_rendition("fill-120x120").attrs_dict, } class YouTubeBlock(blocks.StructBlock): url = URLBlock(required=True) class Meta: template = "streams/youtube.html" label = "Youtube" class ImgBlock(blocks.StructBlock): image = ImageChooserBlock() cta = URLBlock(required=False) class Meta: template = "streams/image_block.html" label = "Image" class SectionHeading(blocks.StructBlock): title = blocks.CharBlock(required=True, help_text="add your title") class Meta: template = "streams/section_heading.html" label = "section heading" class TitleTextTwoColumns(blocks.StructBlock): title = blocks.CharBlock(required=False) content = blocks.CharBlock(required=False) left_title … -
Unable to display data from QuerySet in Django templates
I'm trying to implement a simple search for data on a website. If we specify the a tag in the "search_results.html" template, then all the information that is in it is not displayed, but if we remove the a tag, then everything works, why can this happen? That is, this information is not displayed for me - <a href="{{ article.get_absolute_url }}">{{ article.title }}</a> file urls.py urlpatterns = [ path("search_page/", views.SearchPageView.as_view(), name="searchpageurl") ] file views.py class SearchPageView(TemplateView): template_name = "search/search_results.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) query = self.request.GET.get("q", "") context["query"] = query if query: articles = ListArticles.objects.filter( Q(title__icontains=query) | Q(text__icontains=query), is_publish=True ) context["results"] = {"articles": articles} else: context["results"] = {} return context file model class ListArticles(models.Model): title = models.CharField(max_length=100, verbose_name="Заголовок") text = models.TextField(verbose_name="Текст") images = models.ImageField(upload_to="articles/", verbose_name="Изображение") date_publsh = models.DateTimeField(verbose_name="Дата Публикации") date_modified = models.DateTimeField(auto_now=True) is_publish = models.BooleanField(verbose_name="Опубликованно/Неопубликованно") cats = models.ForeignKey( Category, on_delete=models.CASCADE, verbose_name="Категория" ) slug = models.SlugField(max_length=100, verbose_name="Слаг") tag = models.ManyToManyField(Tag, related_name="articles", verbose_name="Теги") def __str__(self): return self.title def get_absolute_url(self): return reverse("singlearticles", kwargs={"detail_slug": self.slug}) file search_results.html {% extends 'base.html' %} {% block content %} <h1>Результаты поиска для "{{ query }}"</h1> {% if results.articles %} <h2>Статьи:</h2> <ul> {% for article in results.articles %} <li><a href="{{ article.get_absolute_url }}">{{ article.title }}</a></li> {% empty %} … -
How do i publish a django on localserver publibly
I want to publish a django project on an old laptop that's been lying around for a long time. I've just installed the linux server setup. Any help is appreciated. And it's connected to a postgres database. -
Why does AWS ALB Health Checks Fail with Correct Security Group (EC2, Docker, nginx-proxy, ACM)?
I'm having trouble getting my AWS Application Load Balancer (ALB) health checks to pass when my EC2 instance's security group is configured correctly. The site works when I open port 443 to the world (0.0.0.0/0), but fails when I restrict it to the ALB's security group, even with Source/Destination Check disabled. EC2 Instance Configuration: Docker Compose runs nginx-proxy, acme-companion, Django (web), and other services. nginx-proxy is mapped to ports 80 and 443 on the host. VIRTUAL_HOST is set to my domain. VIRTUAL_PORT is correctly set to 8000 EC2 Instance Security Group: Correct Configuration (Failing): Allows inbound HTTPS (port 443) only from the ALB's security group (e.g., sg-xxxxxxxx). Temporary Workaround (Working): Allows inbound HTTPS (port 443) from 0.0.0.0/0. Source/Destination Check is disabled on the EC2 instance. Request Flow: Client Request -> Route 53 -> Application Load Balancer (HTTPS:443) -> AWS WAF -> ALB Target Group (HTTPS:443) -> EC2 Instance (port 443, nginx-proxy) -> Docker Container (port 8000, Django) ALB Configuration: Listener on port 80 (HTTP) redirects to HTTPS (443). Listener on port 443 (HTTPS) forwards to the target group. ALB Security Group: Allows inbound on ports 80 and 443 from 0.0.0.0/0. Target Group health checks: Protocol: HTTPS Port: 443 Path: /api/v1/health/ … -
drf use social auth with simple-jwt library AttributeError: Manager isn't available
I try to customize drf_social_oauth2 with drf simple-jwt I use core.models instead of standard social_oauth2 models, but got 500 status code, error "AttributeError: Manager isn't available; 'oauth2_provider.Application' has been swapped for 'core.Application'" My files: settings.py INSTALLED_APPS = [ ... 'oauth2_provider', 'social_django', 'drf_social_oauth2', 'apps.core', ... ] ... 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'drf_social_oauth2.authentication.SocialAuthentication', ), ... AUTHENTICATION_BACKENDS = { 'django.contrib.auth.backends.ModelBackend', 'drf_social_oauth2.backends.DjangoOAuth2', 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.apple.AppleIdAuth', } CTIVATE_JWT = True DRFSO2_URL_NAMESPACE = "drf" OAUTH2_PROVIDER = { "ACCESS_TOKEN_EXPIRE_SECONDS": 30 * 60, "REFRESH_TOKEN_EXPIRE_SECONDS": 24 * 60 * 60, "ACCESS_TOKEN_GENERATOR": "apps.core.oauth2_tokens_generators.generate_access_token", "REFRESH_TOKEN_GENERATOR": "apps.core.oauth2_tokens_generators.generate_refresh_token", } OAUTH2_PROVIDER_APPLICATION_MODEL = "core.Application" OAUTH2_PROVIDER_ACCESS_TOKEN_MODEL = "core.AccessToken" OAUTH2_PROVIDER_REFRESH_TOKEN_MODEL = "core.RefreshToken" OAUTH2_PROVIDER_ID_TOKEN_MODEL = "core.IDToken" OAUTH2_PROVIDER_GRANT_MODEL = "core.Grant" # GOOGLE OAUTH2 SETTINGS SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY", default="") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET", default="") SOCIAL_AUTH_APPLE_ID_CLIENT = config("SOCIAL_AUTH_APPLE_ID_CLIENT", default="") SOCIAL_AUTH_APPLE_ID_TEAM = config("SOCIAL_AUTH_APPLE_ID_TEAM", default="") SOCIAL_AUTH_APPLE_ID_KEY = config("SOCIAL_AUTH_APPLE_ID_KEY", default="") SOCIAL_AUTH_APPLE_ID_SECRET = config("SOCIAL_AUTH_APPLE_ID_SECRET", default="") core.models """ Module for defining OAuth2 models for token management. """ from django.db.models import CharField from oauth2_provider import models class Application(models.AbstractApplication): """ Customized OAuth2 Application model. Inherits from `oauth2_provider.models.AbstractApplication`. """ class Grant(models.AbstractGrant): """ Customized OAuth2 Grant model. Inherits from `oauth2_provider.models.AbstractGrant`. """ class AccessToken(models.AbstractAccessToken): """ Customized OAuth2 Access Token model. Inherits from `oauth2_provider.models.AbstractAccessToken`. Attributes: token (str): The access token value. """ token = CharField( max_length=2048, unique=True, db_index=True, ) class RefreshToken(models.AbstractRefreshToken): """ Customized OAuth2 …