Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's makemessages generates corrupt po file
My code contains this line (beside lots more i18n texts): filter_text = _('Filter') I generate the "de" locale po file (see missing prefix "#:"): django-admin makemessages --locale de -i venv The resulting po file ist corrupt: #: .\oam\views\article\article_list.py:138 #: .\oam\views\fillup\fillup_list.py:109 #: .\oam\views\setting\setting_list.py:49 .\oam\views\stock\stock_list.py:75 #: .\oam\views\tom_article\tom_article_list.py:53 #: .\oam\views\transaction\transaction_list.py:90 msgid "Filter" msgstr "Filter" Running makemessages again of course leads into errors: CommandError: errors happened while running msgmerge c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915:3: syntax error c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "oam" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "views" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "stock" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "stock_list" unknown c:\work\pro\ceratizit\apollo\oam\locale\de\LC_MESSAGES\django.po:1915: keyword "py" unknown msgmerge: found 6 fatal errors When removing the i18n at this line the makemessages works well: filter_text = 'Filter' I'm totally lost. Any hints? Thanks! -
Button to download file and redirect to new page
How do I enable my button to download and redirect to a new page? I have tried many code combination but it just downloads and does not redirect <div class="banner"> <h3>Download your file:<br> {{ filename }}</h3> <div> {% csrf_token %} <form action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post"> {% csrf_token %} <button onclick="openTab()" class="btn btn-primary w-20" id="myBtn" tabindex="4">Download PDF </button> </form> </div> </div> <script> function openTab() { window.open('home'); } </script> -
How to add fields to serializer
I would like to add foreign key fields to DRF serializer. I need API endpoint with information of Publication details with all Comments to this publication with all Images to this publication and with Likes number to this publication. Models class Publication(models.Model): pub_text = models.TextField(null=True, blank=True) pub_date = models.DateTimeField(auto_now_add=True) pub_author = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): com_text = models.TextField(null=True, blank=True) com_like = models.BooleanField(default=False) com_author = models.ForeignKey(User, on_delete=models.CASCADE) com_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, related_name='comment_author') com_date = models.DateTimeField(auto_now_add=True, null=True) class Image(models.Model): image = models.ImageField(upload_to='images', null=True) image_to_pub = models.ForeignKey(Publication, on_delete=models.CASCADE, null=True, related_name='images') Serializers class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ['com_text', 'com_like', 'com_date', 'com_author'] class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields = ['id', 'pub_text', 'pub_author', 'pub_date'] def to_representation(self, instance): representation = super().to_representation(instance) representation['comment'] = CommentSerializer(instance.comment_author.all(), many=True).data representation['image'] = ImageSerializer(instance.images.all(), many=True).data return representation Views class PublicationViewSet(viewsets.ModelViewSet): queryset = Publication.objects.all() serializer_class = PublicationSerializer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer By my logik Like to Publication can be given by Comment author if comment was created. I used <to_represtntation> method to add fields to Publication serializer. It works as i would need but not sure … -
How does PostgreSQL handle get() in Django for exact file path matches and its performance?
I’m using Django with a PostgreSQL database, and I have a model that stores file paths (specifically S3 file paths) in a CharField, like this: class File(models.Model): file_path = models.CharField(max_length=255) I often retrieve a single file record using Django’s get() method with an exact S3 file path match: file = File.objects.get(file_path='/bucket/path/to/file.txt') This translates to the following SQL query: SELECT * FROM my_table WHERE file_path = '/bucket/path/to/file.txt' LIMIT 1; I want to understand what happens under the hood when PostgreSQL processes this query. Specifically: 1. How does PostgreSQL handle the comparison of strings when using the = operator on a CharField with an S3 file path? 2. Does PostgreSQL behave differently if there’s an index on the file_path column, and how does it decide between using an index or performing a sequential scan? 3. Is it beneficial to create an index on the file_path field for better performance, -
Creating Forms that Redirects to Different URL When Successful
So I have created two folders (Aside from my main project folder) One of my folders is the main app and the second folder is a users folder. Error Message: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/users/register Using the URLconf defined in cooknook.urls, Django tried these URL patterns, in this order: admin/ users/ register/ [name='cooknook-register'] [name='cooknook-home'] about/ [name='cooknook-about'] account/ [name='cooknook-account'] The current path, users/register, didn’t match any of these. ^^ Error Thrown So In my views.py inside of my users folder I am telling it after success: ` def register(response): if response.method == "POST": form = UserCreationForm() if form.is_valid(): form.save()` return redirect('cooknook-home') Basically, I did already try to outsource the problem and tried to implement 'reverse' function in this which did not seem to work at all. The problem is that it seems it is trying to find the urls/html(temps) inside of my cooknookapp folder which is my main app folder. I'm needing it to redirect to home.html (located inside of my main app folder) How can I get Django to look outside of the Users/ Dir for this? I was expecting for it to send me to the home page which is located in the cooknookapp … -
How to expose the drf_spectacular autogenerated documentation of a class-based view that has no direct reference in urls.py?
I have a Django app that based on specific condition, executes one or another class-based view. def compatibility_whatever_view(request: Request, *args, **kwargs) -> Response: if is_legacy: return LegacyWhateverView.as_view()(request, *args, **kwargs) else: return WhateverView.as_view()(request, *args, **kwargs) I have my WhateverView and LegacyWhateverView with fully compatible API. urlpatterns = [ path( "whatever/<uuid:whatever_id>/", compatibility_whatever_view, name="whatever_list_whatevers", ), ] I want to expose the documentation of WhateverView using drf_spectacular. Unfortunately I am failing to do so, as it seems the swagger.yml file is generated only if the class-based view is directly exposed in the urlpatterns, otherwise it does not know how to build the URL endpoint. This totally makes sense, but I would like to be able to somehow expose the automatically generated of WhateverView to the public. I have tried a bit of magic using: @drf_spectacular.utils.extend_schema(operation_id="whatever_list_whatevers") @rest_framework.decorators.api_view() def compatibility_whatever_view(request, *args, **kwargs): ... but the generated documentation was lacking the details that are otherwise present when I directly reference the class-based view. -
django CMS vs Django
We're planning to build a application tracking system with multiple role and permission. My question is : Which is the best platform django CMS or Django ? I am in the impression that Django CMS comes with all the role / Groups / Permission stuff as default, but in Django I see we have groups I don't see permission concept. Share your expert advices. -
How to mocking a function that returns some value
For example, there is a view that processes a user registration request. The view accepts a phone number and sends an SMS with a code to it. The code is generated by an additional function. Here's how to mocking this function to send the code I need? This is my view def post(self, request): serializer = ReviewerSignUpSerializer(data=request.data) serializer.is_valid(raise_exception=True) phone = serializer.validated_data.get("phone") confirmation_code = get_confirmation_code() cache.set( key=str(phone), value=confirmation_code, timeout=settings.CONFIRMATION_CODE_LIFETIME ) send_sms_task.apply_async([confirmation_code, str(phone)]) This is a function that generates a confirmation code def get_confirmation_code() -> str: seq = list(map(lambda x: str(x), range(10))) shuffle(seq) code = choices(seq, k=settings.INVITE_CODE_LENGTH) return "".join(code) Test function def test_saving_confirmation_code_in_cache(self, client, cache): phone = "+79389999999" generated_code = "9999" with patch("api.v1.authentication.utils.get_confirmation_code", return_value=generated_code): client.post(reverse('api:v1:signup'), data={'phone': phone}) confirmation_code = cache.get(str(phone)) assert confirmation_code is not None assert confirmation_code == generated_code -
Wagtail django.db.utils.OperationalError: (1463, "Non-grouping field 'numchild' is used in HAVING clause")
I'm working on a Django project and I've encountered an issue that I'm unable to resolve. When I try to run my application, I get the following error: django.db.utils.OperationalError: (1463, "Non-grouping field 'numchild' is used in HAVING clause") I'm not sure what's causing this error. I'm not explicitly using a HAVING clause in my queries, and 'numchild' is a field that's managed by Django's** Wagtail** module, not something I've added myself. I'm using the following packages: wagtail>=5.0 mysqlclient==2.2.4 Every things working fine locally using sqlite. I tried to downgrade my mysqlclient version from 2.2.4 to 2. Without sucess. I would like to have the result as sqlite. -
Redis Lock with Django unexpected behaviour
I am running redis:7.2.4 in a docker container. In Djano settings.py redis is set up like this: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://redis:6379', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', }, }} This is the implementation of a context manager for a locking (I just added thread_local=False without effect): from django.core.cache import cache LOCK_CLEANUP_TIMEOUT_SEC = 20 LOCK_AQUIRE_WAIT_TIMEOUT_SEC = 2 class RedisLock: def __init__(self, lock_id, timeout=LOCK_CLEANUP_TIMEOUT_SEC): self.lock_id = lock_id self.timeout = timeout def __enter__(self, aquire_timeout = LOCK_AQUIRE_WAIT_TIMEOUT_SEC): self.aquired = cache.lock(self.lock_id, blocking_timeout=aquire_timeout, thread_local=False) return self.aquired def __exit__(self, exc_type, exc_value, traceback): if self.aquired: cache.delete(self.lock_id) Consider the output of the django shell: >>> lock_name = 'test123' >>> with RedisLock(lock_name) as acquired1: ... if acquired1: ... print("1 acquired", acquired1) ... with RedisLock(lock_name) as acquired2: ... if not acquired2: ... print("2 not acquired (expected behavior)", acquired2) ... else: ... print("2 acquired (this should not happen)", acquired2) ... else: ... print("1 not acquired", acquired1) ... 1 acquired <redis.lock.Lock object at 0x0000023B4190BC10> 2 acquired (this should not happen) <redis.lock.Lock object at 0x0000023B4190BDF0> Does somebody have an idea why this happens? The second lock must not be acquired before leaving the context manager of the first lock. -
when i try to use "django-admin runserver" on a project that worked about a month ago (i didnt edit anything btw) this happened (on VSCode)
PS F:\filenaem\djangler> django-admin runserver Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\user\AppData\Local\Programs\Python\Python312\Scripts\django-admin.exe\__main__.py", line 7, in <module> File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 75, in execute super().execute(*args, **options) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\base.py", line 459, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\management\commands\runserver.py", line 82, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\conf\__init__.py", line 81, in __getattr__ self._setup(name) File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\conf\__init__.py", line 61, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. tried to use the django-admin runserver command and expected it to work, because its a finished project that i made with the assistance of my old teacher, but for whatever reason when i try to run it now 2 months later and after moving it to another computer via an external disk it doesnt work, any help? also "python manage.py runserver" doesnt work eighter, it just gives me this: PS F:\filenaem\djangler> python manage.py runserver C:\Users\user\AppData\Local\Programs\Python\Python312\python.exe: can't open file 'F:\\filenaem\\djangler\\manage.py': … -
Django Tenant throwing raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) error
I am working on a Django project that uses Django Channels, Daphne, and Django Tenants for multitenancy and WebSocket communication. My project structure includes a project folder and several application folders. In the project folder, I have the usual files like asgi.py, wsgi.py, settings.py, and consumers.py (for handling Django Channels). I am not using routing.py. In the application folder, I have files like models.py, serializers.py, views.py, and urls.py. The WebSocket communication works fine, but I encounter an issue when trying to import a service module in consumers.py. asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator from django.urls import path, re_path from .consumers import ABConsumer os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autobiz.settings') import django django.setup() # Initialize Django ASGI application early to ensure the AppRegistry # is populated before importing code that may import ORM models. django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": django_asgi_app, # Just HTTP for now. (We can add other protocols later.). "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter([ #path("ws/admin/", ABConsumer.as_asgi()), re_path(r'ws/server/(?P<tenant_name>\w+)/$', ABConsumer.as_asgi()), ]) ) ), }) consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json import logging **from autobiz.abshared.services import process_token ** # Setting up logging logger = logging.getLogger(__name__) class ABConsumer(AsyncWebsocketConsumer): async def connect(self): # … -
CashApp Payment Method Not Rendering in Django with Adyen Integration
I'm trying to integrate Adyen's payment methods (including CashApp) into my Django web application, but the CashApp payment method isn't rendering on the front end. Instead, I receive the following error: ERROR Error during initialization ERROR: Error during initialization at e.<anonymous> (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:460538) at P (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:41524) at Generator.<anonymous> (https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js:1:42844) This same code is rendering the card payment gateway but not working on the cashapp. My html Code: Where is used adyen sdk=5.68.0 version. Version greater than 5.69.0 gives different error that AdyenCheckout is not defined I don't know how to solve that too. <link rel="stylesheet" href="https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.css"> <div id="component"></div> <script src="https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/5.68.0/adyen.js"></script> async function startCheckout() { const checkoutSessionResponse = await callServer({% url 'sessions' %}); const checkout = await createAdyenCheckout(checkoutSessionResponse); checkout.create(type).mount("#component"); } async function createAdyenCheckout(session) { return new AdyenCheckout({ clientKey, session: session, paymentMethodsConfiguration: { cashapp: { amount: { value: 100, currency: "USD" }, countryCode: "US" } } }); } django view.py file: def adyen_sessions(request): # payments = ["card", "cashapp", "ideal"] session_response = { 'client_key': settings.ADYEN_CLIENT_KEY, 'method': 'cashapp' } return render(request, 'component.html', context=session_response) def sessions(request): if request.method == "POST": adyen = Adyen.Adyen() adyen.payment.client.xapikey = settings.ADYEN_API_KEY adyen.payment.client.platform = settings.ADYEN_ENVIRONMENT adyen.payment.client.merchant_account = settings.ADYEN_MERCHANT_ACCOUNT request_data = { 'amount': { "value": 100, # amount in minor units "currency": "USD" … -
Oauth2 doesn't redirect to my flutter application after successful login
I am trying to implement oauth2 with flutter_appauth package. After successful login the web page should redirect to my mobile application. At this moment, it just stays in web (redirecting to web home page). I'm currently getting this error Redirect to scheme 'com.app.app` is not permitted. Here is the code oauth2.dart Future<void> login() async { try { final AuthorizationTokenResponse result = await appAuth.authorizeAndExchangeCode( AuthorizationTokenRequest( 'client_id', 'com.app.app:/oauthredirect', // discoveryUrl: // "http://10.0.2.2:8000/api/oauth2/.well-known/openid-configuration", serviceConfiguration: const AuthorizationServiceConfiguration( authorizationEndpoint: 'http://10.0.2.2:8000/api/oauth2/authorize', tokenEndpoint: 'http://10.0.2.2:8000/api/oauth2/token', ), scopes: ['openid', 'profile', 'email'], ), ); print("Received Token!"); // Successfully received the token print(result); } catch (e) { print('Login error: $e'); } } build.gradle defaultConfig { applicationId "com.app.app" minSdkVersion 26 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName multiDexEnabled true manifestPlaceholders += [appAuthRedirectScheme: 'com.app.app'] } Note: login() function invoked when user clicks the login button on the login screen. Also, I've tried implementing oauth2 with discoveryUrl and it just crashes the app immediately after login() function is called. Last thing I want to mention is I have already checked redirection uri in admin panel and it's correct. Oauth2 was implemented with Django oauth2 toolkit. -
Django SVG not loading on Front-End
Images are located in: root folder -> static -> admin -> img -> logo.svg {% load static %} <a class="navbar-brand" href="/"> <img src="{% static 'admin/img/logo.svg' %}" alt="Logo"> </a> But I am getting this error: "GET /static/admin/img/devoro-logo.svg HTTP/1.1" 404 Hello, I am having an issue with my Django project, I am trying to call my newly added .svg to my base.html like so. All of the old images works perfectly, but the issue seems to lie with the newly added ones. The settings.py is configured correctly and everything seems to be correct, but for some reason I am getting this error. -
Closing Socket Reverts Database Data to Earlier State
I'm building a Django SPA, which uses HTTPS requests as well as Django Channels (Socket Communication) for real time updates. When a user logs in, the socket creates an instance(?) for that user, of which data matches the user data in the database. If you change the user data in the database (for example increment wins or change username), this data is not automatically carried over to the socket session, so I will have 2 different states representing the same user. When I then interrupt the socket instance, the database reverts back to the state it was in before the changes. I won't post code, I'm just curious about the description of this anomaly Do I have to refresh manually the user's state in the socket after each database change related to the user? Or is there some way around it? **What I've tried ** When I'm saving the new data to the websocket and also update it's in-memory data e.g: self.scope["user"].username = new_username self.user.username = username That seems to work. However I'm curious if that is necessary for every user related update, or if there is a shorcut to this problem. -
Django SMTPAuthenticationError when using the same variable name for EMAIL_HOST_PASSWORD in .env and settings.py
I am working on a Django project where I use Gmail for email services. I have the following configuration in my .env file: EMAIL_HOST_USER=gmail@gmail.com EMAIL_HOST_PASSWORD=password And in my settings.py, I load these variables as follows: EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD') When I try to send an email through my application, I encounter an SMTPAuthenticationError. However, when I change the name of the variable in the .env file, it works fine, but the password is no longer masked. How can I fix this while keeping the password masked? -
Django random post not showing on base.html
I'm trying to get ads to show on the sidebar of my website (in base.html). However the ad isn't displaying. The code I'm using is: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * import random def base(request): allSideAds=SideBarAd.objects.all() random_sideAd = random.choice(allSideAds) if allSideAds else None return render(request, 'base.html', {'random_sideAd': random_sideAd}) models.py from django.contrib import admin from django.db import models from django.urls import reverse class SideBarAd(models.Model): AdImage = models.ImageField(help_text='Enter Image Here') AdLink = models.URLField() MaxAdViews = models.PositiveBigIntegerField() AdViews = models.PositiveBigIntegerField() Approved = models.BooleanField() def get_absolute_url(self): return self.AdImage base.html {% if random_sideAd %} <a href="{{ random_sideAd.AdLink }}"> <img src="{{ random_sideAd.AdImage.url }}" alt="Ad Image"> </a> {% endif %} When I load a page, the ad that's in my database isn't shown through base.html. -
I keep getting a 405 error on my Django Blog
I'm having an issue with my Django Blog. Every time I try to turn on the About Me Page, I get a 405 Error. For context, here's my code: posts/views.py: from django.views.generic from .models import Post class AboutView(View): template_name = "aboutme.html" posts/url.py: from django.urls import re_path from .views import AboutView urlpatterns = [ re_path(r'post/aboutme/', AboutView.as_view()) ] templates/base.html: <body> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="py-2 bg-body-tertiary border-bottom"> <div class="py-2 bg-body-tertiary border-bottom"> <ul class="nav me-auto"> <li class="nav-item"><a class="nav-link" href="">Homepage</a></li> <li class="nav-item"><a class="nav-link" href="/posts">Blog</a></li> <li class="nav-item"><a class="nav-link" href="/post/aboutme/">About Me</a></li> <li class="nav-item"><a class="nav-link" href="#">Portfolio</a></li> </ul> </div> </div> </div> </nav> </div> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> For the sake of clarity, I've included the About Me page: {% extends 'base.html' %} {% block title %} About Me {% endblock %} {% block content %} <div class="center"> <p> Salutations! I'm TheBigL. A software Developer by trade. </p> </div> {% endblock %} I always seem to get a 405 every time I open the About Me page. Is there any way I can fix this issue? Is my view configured … -
Django taggit working on one form, but not the other
I have 2 forms in django, one for adding an article and one for adding a sheet, they both have a column using taggit for tags, the form for adding an article, works perfect, no issues at all, but the one for creating a sheet doesn't work at all, can't figure out why, the code is identical or both sheets only named different. Below is the code models.py from django.db import models from mdeditor.fields import MDTextField from taggit.managers import TaggableManager class Article(models.Model): title = models.CharField(max_length=255) content = MDTextField() tags = TaggableManager() def __str__(self): return self.title class Sheet(models.Model): title = models.CharField(max_length=255) file = models.FileField(upload_to='sheets/') tags = TaggableManager() def __str__(self): return self.title forms.py from django import forms from mdeditor.fields import MDTextFormField from .models import Article, Sheet from dal import autocomplete from taggit.forms import TagField class ArticleForms(forms.ModelForm): title = forms.CharField(max_length=200) content = MDTextFormField() tags = TagField(widget=autocomplete.TaggitSelect2('article-tag-autocomplete')) class Meta: model = Article fields = ['title', 'content', 'tags'] class SheetForms(forms.ModelForm): title = forms.CharField(max_length=200) file = forms.FileField() tags = TagField(widget=autocomplete.TaggitSelect2('sheet-tag-autocomplete')) class Meta: model = Sheet fields = ['title', 'file', 'tags']``` urls.py urlpatterns = [ path("add_article", views.add_article, name="add_article"), path("add_sheet", views.add_sheet, name="add_sheet"), path('sheet-tag-autocomplete/', SheetsTagAutocomplete.as_view(), name='sheet-tag-autocomplete'), path('article-tag-autocomplete/', ArticleTagAutocomplete.as_view(), name='article-tag-autocomplete'), ] views.py from dal import autocomplete from taggit.models import Tag … -
Django admin EmailField with null=True, blank=True, unique=True saves empty string ("") instead of null
When I use Django EmailField with null=True, blank=True, unique=True, admin saves empty string ("") instead of null. So I recieve "User with this Email address already exists." error. As this ticket says this problem must be solved and it's OK when I use CharField but not EmailField. Is there any way to solve this? -
email login: authentication function doesn't work
def EmailLoginVerify(request): if request.method == 'POST': if 'token' in request.POST: try: submitted_token = int(request.POST['token']) except ValueError: return HttpResponse('Invalid token format', status=400) if submitted_token == request.session.get('login_token'): email = request.session.get('email') try: target = MyUser.objects.get(email=email) print('user is', target.username, 'and password is', target.password) #export: #>>>>>>>user is maziar and password is pbkdf2_sha256$720000$CY5sjiqAL1yScKzGhzYBp9$2tUx8ScBbbuZlj+u0YfMxwTIRfz5Vfmv+58piWCAjKM= except MyUser.DoesNotExist: return HttpResponse('User Not Found', status=404) user = authenticate(request, username=target.username, password=target.password) print(user) #export: #>>>>> None if user is not None: login(request, user) return HttpResponse('good') else: return HttpResponse('Authentication failed', status=401) else: return HttpResponse('Invalid token', status=403) else: return HttpResponse('Token not provided', status=400) else: return render(request, 'login_verify.html') in the end it return 'Authrntication Failed' this code get an email from the user if a user with that email exists it send a code to the email and if user enter the correct code it should authenticate the user and log it in but it return 'Authentication Failed' enter image description here -
django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") in Django
I am building a Django application and trying to implement pagination on a large dataset for a report. When querying the database, I encounter the error: django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'"). I'm using MySQL as the database backend. order_queryset = ProformaHeader.objects.filter(process_this_order=True, status=ACTIVE) page_obj = pagination(request, order_queryset.order_, per_page=10) order_queryset = page_obj.object_list podetails = PODetail.objects.filter(proforma__in=order_queryset, po_header__is_vconfirmed=True, status=ACTIVE).select_related('proforma_detail') podetail_map = {p.proforma_detail_id: p for p in podetails} # I encounter the error this line Error occurs on this line: podetail_map = {p.proforma_detail_id: p for p in podetails} # I encounter the error this line The error is raised when attempting to create a dictionary mapping proforma_detail_id to the corresponding podetail object. It seems to be related to the combination of LIMIT and IN in the query generated by Django when retrieving the podetails. Expected Outcome: I expected this line to build a dictionary mapping proforma_detail_id to podetail without triggering an error, allowing me to reference the podetail object for each proforma_detail in the subsequent processing loop. -
Get Client IP address in Django from nginx proxy
I have the following setup to run my Django server and I want to get a client IP address in Django server but it is giving me wrong IP address Nginx proxy conf events { worker_connections 1024; } http { log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /first_access.log custom_format; client_max_body_size 50M; server_tokens off; upstream backend { server backend:8000; } server { listen 80 default_server; server_name _; return 301 https://$host$request_uri; } server { listen 443; server_name www.$ENV-api.in $ENV-api.in; ssl on; ssl_certificate /certs/server.crt; ssl_certificate_key /certs/server.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256'; location / { 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_pass http://backend; add_header X-Frame-Options "DENY" always; add_header Content-Security-Policy "frame-ancestors 'self';" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "no-referrer" always; } } } This above conf forward request to following nginx conf vents { worker_connections 1024; } http { log_format custom_format '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /second_access.log custom_format; client_max_body_size 50M; server { include "/etc/nginx/mime.types"; listen 8000; server_name django; gzip on; gzip_min_length 1000; gzip_proxied expired no-cache no-store private auth; gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript; … -
How to Enhance Fingerprint Images Without Blurring Ridges? i am using django
How to Enhance Fingerprint Images Without Blurring Ridges? i am using django. I'm currently working on a fingerprint enhancement project using OpenCV, and while my code is producing results, the ridges in the fingerprint images are coming out blurred. here is my code import cv2 import numpy as np import math import fingerprint_enhancer # Ensure this module is available from django.shortcuts import render from django.core.files.base import ContentFile from .forms import HandFingerForm from .models import ThumbImage import base64 MAX_IMAGES = 10 def remove_green(img): empty_img = np.zeros_like(img) RED, GREEN, BLUE = (2, 1, 0) reds = img[:, :, RED] greens = img[:, :, GREEN] blues = img[:, :, BLUE] # Create a mask for the areas to keep tmpMask = (greens < 35) | (reds > greens) | (blues > greens) img[tmpMask == 0] = (0, 0, 0) # Remove background from original picture empty_img[tmpMask] = (255, 255, 255) # Mask with finger in white return img, empty_img def detect_nail(gray_mask_finger): # Find contours in the mask image contours, _ = cv2.findContours(gray_mask_finger, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: # Only consider large enough contours as nails if cv2.contourArea(contour) > 100: # Adjust this threshold as needed x, y, w, h = cv2.boundingRect(contour) # …