Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run function at startup before requests are handled in Django
I want to run some code when my Django server starts-up in order to clean up from the previous end of the server. How can I run some code once and only once at startup, before the server processes any requests. I need to access the database during this time. I've read a couple of things online that seem a bit outdated and also are not guaranteed to run only once. -
Django error: Reverse for 'user_workouts' not found. 'user_workouts' is not a valid view function or pattern name
I'm working on my project for a course and I'm totally stuck right now. I'm creating a website to manage workouts by user and the create workout do not redirect to the user's workouts page when I create the new workout instance. views.py # View to return all user's workouts def user_workouts(request, user_id): user = User.objects.get(id=user_id) print(user) workouts = get_list_or_404(Workout, user=user.id) return render(request, "users/workouts.html", {"user": user, "workouts": workouts}) # Create workout view def add_workout(request, user_id): user = get_object_or_404(User, id=user_id) print(user) print(request._post) if request.method == "POST": workout_title = request.POST.get("workout") reps = request.POST.get("reps") load = request.POST.get("load") last_update = request.POST.get("last_update") workout = Workout(workout=workout_title, reps=reps, load=load, last_update=last_update, user=user) workout.save() print(user.id) return redirect('user_workouts') context = {"workout": workout} return render(request, "users/add_workout.html", context=context) urls.py from django.urls import path from . import views app_name = "myapp" urlpatterns = [ path("", views.index, name="index"), path("user/<int:user_id>", views.user_detail, name="user_detail"), path("user/<int:user_id>/workouts", views.user_workouts, name="user_workouts"), path("user/<int:user_id>/workouts/<int:workout_id>", views.workout_detail, name="workout_detail"), path("user/<int:user_id>/workouts/Add Workout", views.open_workout_form, name="open_workout_form"), path("user/<int:user_id>/workouts/create/", views.add_workout, name="add_workout") ] -
Django templates and css: is there a workaround for getting my preload link tags to match my css relative paths to font sources?
Background I just started using Digital Oceans Spaces for storing my static files for my Django web app (connected using django-storages library). Previously, I used link elements in the head of my base template to preload my fonts to avoid font-switching flashes while the page is loading (which is the case for 'Mona Sans') or when an element that uses a custom font is shown for the first time (I use a 'Pixelated' font in a dialog element). The Issue However, now there is a discrepancy in the url's produced by the static template tag in my Django templates and the url's produced by relative paths in my css file. The fonts get loaded just fine using the relative path in the css file, but they are missing the query parameters, so the preloaded resources (with query parameters) don't actually end up being used (causing brief font-swap flash and console warnings). Additionally, I don't know if not having the query parameters will eventually cause issues once I implement read-protection with pre-signed URLs. Django template <link rel="preload" href="{% static 'fonts/Mona-Sans.woff2' %}" as="font" type="font/woff2" crossorigin/> <link rel="preload" href="{% static 'fonts/Pixelated.woff2' %}" as="font" type="font/woff2" crossorigin/> This use of the static tag results in … -
changes made to my JavaScript files in a React project are not reflected in the UI when compiling using 'npm start'. Reflecting only when rebuilt
Initial issue faced: "Invalid options object. Dev Server has been initialized using an options object that does not match the API schema" TO resolve this issue added setupProxy.js inside src folder as follows: const { createProxyMiddleware } = require("http-proxy-middleware"); module.exports = function (app) { app.use( "/", createProxyMiddleware({ target: "http://127.0.0.1:8000", changeOrigin: true, }) ); }; After adding this file, the code works fine when built and executed. However, if any changes are made to the JavaScript files, they are not reflected in the UI when saved and compiled using 'npm start'. The changes only appear when 'npm start' is executed after rebuilding with 'npm run build'. Tried different versions of npm and react-script. Removed node modules and installed again. Expecting a solution to make the changes made in code to reflect in UI without rebuilding the code everytime. -
CSRF FAIL WITH JMETER
I have a problem with JMeter. I am trying to perform performance tests with the BlazeMeter extension. When making some requests, I get an error with the CSRF. I already tried extracting the token with a regular expression extractor, but it doesn't find it. <!doctype html> <html lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; color:#000; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Prohibido <span>(403)</span></h1> <p>Verificación CSRF fallida. Solicitud abortada</p> <p>Estás viendo este mensaje porqué esta web requiere una cookie CSRF cuando se envían formularios. Esta cookie se necesita por razones de seguridad, para asegurar que tu navegador no ha sido comprometido por terceras partes.</p> <p>Si has inhabilitado las cookies en tu navegador, por favor habilítalas nuevamente al menos para este sitio, o para solicitudes … -
When using django-storages with a cloud storage service, is there a way to make the collectstatic management command run faster?
Issue I recently connected my django app to Digital Ocean Spaces using the django-storages library, and suffice it to say I have a lot of static files (currently 2545 files, most of which are small-ish audio files). I just timed how long it took python3 manage.py collectstatic to run to copy a single static file, and it took 3 minutes 27 seconds. This was the output: USER@computer dirName % python3 manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes 1 static file copied, 2544 unmodified. Question Is there a way to speed the collectstatic process up? Can I tell it which files to collect and copy? Can it somehow interface with git to know which ones to collect and copy? -
Need solution to resolve this error: huey.exceptions.hueyexception: core_platform.worker.tasks.handle_account_change
`In my django application currently using huey queue to process tasks. Now I want to prioritise tasks in my queue based on my requirement. Found PriorityRedisHuey class in huey module. I updated my code to use PriorityRedisHuey instead of huey. I have redis server running in my system using docker. ** this is priorityredishuey** enter image description here Model changes to table I added a priority field to table to add priority to queue based on my requirement enter image description here This is my settings change to use redis server. **# Initialized priorityredishuey in settings file ** enter image description here **This is my tasks file ** This is my tasks file(https://i.sstatic.net/26jQui3M.png) ` ** This is app config file** (https://i.sstatic.net/O9VSvPU1.png) these are the changes i made to use priorityredishuey.But when i am trying to run the run_huey it is giving this exception enter image description here I want to know how to resole this error I am expecting to prioritise the tasks in my queue using PriorityRedisHuey. Let say I have 10 tasks in queue already with priority 0 then i inserted a new task 11 with priority 1 then i want new task 11(because of high priority) need … -
How to override Django Two Factor Authorization default login success response
I am using Django Two Factor Authorization in my login view. I am using a plugin manager to register the plugin TwoFactorPlugin which My problem is that although in the view I return the view's HttpResponse, it always returns the LOGIN_REDIRECT_URL. If I remove the LOGIN_REDIRECT_URL, it will always redirect to accounts/profile/, which is the two factor's default login success url. Is it possible to override this to return the HttpResponse of the view? Is there another way to do this (or any suggestion really) ? views.py: from two_factor.views import LoginView as TwoFactorLoginView @login_required def login_success(request): success_message = f"User logged in successfully." return HttpResponse(success_message) class TwoFactor_LoginView(TwoFactorLoginView): def form_valid(self, form): response = super().form_valid(form) # plugin_response is an HttpResponse return from the plugin "two_factor" plugin_response = PluginManager.perform_action( "two_factor", self.request, email=self.request.user.email, password=form.cleaned_data.get("password"), token=self.request.POST.get("token"), ) # If the plugin action returns an HttpResponse, use it instead if isinstance(plugin_response, HttpResponse): return plugin_response return response urls.py: path("login/", TwoFactor_LoginView.as_view(), name="login"), path("login_success/", login_success, name="login_success"), settings.py: LOGIN_URL = "login/" LOGIN_REDIRECT_URL = "/login_success/" -
Error message: [09/Jul/2024 20:02:20] "GET /blog/about HTTP/1.1" 404 2285 Not Found: /blog/about geting this while creating Blog app
` # **views.py** from django.shortcuts import render from django.http import HttpResponse def home(request): return HttpResponse('<h1>Blog home</h1>') def about(request): return HttpResponse('<h1>Blog About</h1>') # **urls.py (in blog)** from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'), ] # **urls.py (in django_project)** from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), ] can't get the aboutpage Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/about Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='blog-home'] The current path, blog/about, didn’t match any of these. trying to get the about page but couln't found resulted:Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/blog/about Using the URLconf defined in django_project.urls, Django tried these URL patterns, in this order: admin/ blog/ [name='blog-home'] The current path, blog/about, didn’t match any of these. -
Django Websocket receive and send arguments missing
TypeError at /ws/status/ app() missing 2 required positional arguments: 'receive' and 'send' I got only receive and send 2 positional argument error for websocket in django rest framework. How can i fix it ? Maybe version error but i tried to change django channels versions but dont works os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') django_asgi_app = get_asgi_application() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( core.routing.websocket_urlpatterns ) ) ), }) websocket_urlpatterns = [ re_path(r'ws/status/$', StatusConsumer.as_asgi()), ] Traceback (most recent call last): File "/usr/local/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/usr/local/lib/python3.8/dist-packages/daphne/cli.py", line 170, in entrypoint cls().run(sys.argv[1:]) File "/usr/local/lib/python3.8/dist-packages/daphne/cli.py", line 232, in run application = import_by_path(args.application) File "/usr/local/lib/python3.8/dist-packages/daphne/utils.py", line 12, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Application/./core/asgi.py", line 5, in <module> import core.routing File "/Application/./core/routing.py", line 2, in <module> from .consumers import StatusConsumer File "/Application/./core/consumers.py", line 7, in <module> User = get_user_model() File "/usr/local/lib/python3.8/dist-packages/django/contrib/auth/__init__.py", line 170, in get_user_model return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False) File "/usr/local/lib/python3.8/dist-packages/django/conf/__init__.py", … -
Django REST Framework Route Not Appearing in API List
I'm facing an issue with Django REST Framework where a specific route is not appearing in the API list when I access https://myserver.com/api/. Here's my setup: url.py from django.urls import path, include from rest_framework.routers import DefaultRouter from . import views router = DefaultRouter() router.register(r'myapi', views.myapiViewSet, basename='myapi') urlpatterns = [ path('api/', include(router.urls)), # Other URL patterns ] views.py class myapiViewSet(ViewSet): permission_classes = (MaintenanceCheck,) throttle_classes = [UserRateThrottle] When I visit https://myserver.com/api/, I expect to see the myapi endpoint listed, but it doesn't appear so when I can access https://myserver.com/api/myapi/ directly and it doesn't work and it shows me "Not Found\n The requested resource was not found on this server." The router is correctly included in the main URL conf. The view myapi is a proper viewset. The URL prefix api/ is used properly. I can't figure out why the myapi endpoint doesn't show up in the API list. Any insights or suggestions would be greatly appreciated! -
Logout process in Django, "next" parameter error
While logging out in Django with the "next" parameter, I use the POST request in the form. However, I use another POST request in the code I wrote. These two desires conflict. How can I fix this? [This is my html page] [(https://i.sstatic.net/JpH9USY2.png]) I'm trying to make a blog page using Django. What I want to do is for this user to be able to add a blog post after logging in. If the user is not logged in, they can only view blog posts. Error: User is logging in. When you want to share a blog post, you will be logged out after pressing the 'Publish' button. Normally, it should be directed to the page where the blog posts are located. I got this (https://stackoverflow.com/a/77928839/19535811) usage from stackoverflow but it doesn't work either. Can anyone help me with another solution? -
React Native Expo Barcode Scanner Navigation
I'm new to react native and expo and I followed a tutorial online for a barcode scanning app using expo, but it didn't cover how to navigate away from the expo camera app to another screen and I can't really figure it out. I have the scanner working and I created a django rest backend with the qrcode data, but it only applies the name of the file and I'm looking to navigate to a page that also contains the name and description that is listed in my django model. I'm sure I probably have to update my django model in some way, but I really could use some help in the code. Here is my django model: from django.db import models import qrcode from io import BytesIO from django.core.files.base import ContentFile from PIL import Image class Event(models.Model): name = models.CharField(max_length=200) description = models.TextField() qr_code = models.ImageField(blank=True, upload_to='qrcodes/') date = models.DateField() def __str__(self): return str(self.name) def save(self, *args, **kwargs): if not self.qr_code: qrcode_img = qrcode.make(self.name) canvas = Image.new('RGB', (qrcode_img.pixel_size, qrcode_img.pixel_size), 'white') canvas.paste(qrcode_img) fname = f'{self.name}.png' buffer = BytesIO() canvas.save(buffer, 'PNG') self.qr_code.save(fname, ContentFile(buffer.getvalue()), save=False) super().save(*args, **kwargs) and here is my barcode scanner screen in react: import React, { useState, useEffect } … -
How to validate an enum in Django using serializers
I'm using serializers to validate my Post data. How can I validate an Enum? I have a class like this: class DataTypeEnum(StrEnum): FLOAT = 'float' INTEGER = 'integer' BOOLEAN = 'boolean' And my Post input contains { ... "value" : <datatype> ... } where value should have the values of float, integer or boolean -
How do you deal with the id fields of forms created using Django's inlineformset_factory?
I am trying to save multiple forms via inlineformset_factory but it is not saving any data. And the formset is also returning other fields, like the ID field. inlineformfactories are also returning other foreignkey fields. As for the id field, is it a special form field or a django model field? forms.py class ImageFieldForm(forms.ModelForm): class Meta: model = ImageField fields = ('image',) class VideoFieldForm(forms.ModelForm): class Meta: model = VideoField fields = ('video',) class AdditionalFieldForm(forms.ModelForm): class Meta: model = AdditionalField fields = ('icon', 'title', 'description',) ImageFieldFormset = inlineformset_factory(Auction, ImageField, form=ImageFieldForm, extra=0, fields=('image',)) VideoFieldFormset = inlineformset_factory(Auction, VideoField, form=VideoFieldForm, extra=0, fields=('video',)) AdditionalFieldFormset = inlineformset_factory(Auction, AdditionalField, form=AdditionalFieldForm, extra=0, fields=('icon', 'title', 'description',), exclude=('id',)) views.py def auction_create(request): auction_form = AuctionForm() image_formset = ImageFieldFormset() video_formset = VideoFieldFormset() additional_formset = AdditionalFieldFormset() if request.method == 'POST': auction_form = AuctionForm(request.POST, request.FILES) image_formset = ImageFieldFormset(request.POST, request.FILES) video_formset = VideoFieldFormset(request.POST, request.FILES) additional_formset = AdditionalFieldFormset(request.POST, request.FILES) if all([auction_form.is_valid(), image_formset.is_valid(), video_formset.is_valid(), additional_formset.is_valid()]): new_auction = auction_form.save(commit=False) new_auction.owner = request.user new_auction.save() new_auction.permissions.add(request.user) user_permission = AuctionUserPermission.objects.get(user=request.user, auction=new_auction) user_permission.can_edit = True user_permission.can_delete = True user_permission.can_add_admin = True user_permission.save() for image_form in image_formset: new_image_form = image_form.save(commit=False) new_image_form.auction = new_auction new_image_form.save() for video_form in video_formset: new_video_form = video_form.save(commit=False) new_video_form.auction = new_auction new_video_form.save() for additional_form in additional_formset: new_additional_form = additional_form.save(commit=False) new_additional_form.auction … -
how to clean a model after the related models inline forms have been saved in the admin site in the transaction start?
I have such models: class Advert(CreatedUpdatedMixin): ... use_pickup = models.BooleanField( verbose_name=_('pickup'), default=False, ) use_nova_post = models.BooleanField( verbose_name=_('nova post'), default=False, ) use_courier = models.BooleanField( verbose_name=_('courier'), default=True, ) ... def clean(self): if not any([self.use_pickup, self.use_nova_post, self.use_courier]): raise ValidationError( _('One of next field must be true: use_pickup, use_nova_post, use_courier.'), 'invalid_use_fields', ) if self.use_pickup and getattr(self, 'address', None) is None: raise ValidationError( _('Address must be specified if use_pickup field is true.'), 'empty_address', ) class AdvertAddress(Address): advert = models.OneToOneField( verbose_name=_('advert'), to=Advert, on_delete=models.CASCADE, related_name='address', ) When I save a Advert model in the admin site, there is error from this part code: if self.use_pickup and getattr(self, 'address', None) is None: raise ValidationError( _('Address must be specified if use_pickup field is true.'), 'empty_address', ) because admin form check clear before saving advert and advert address. The only thing that came to mind was to modify changeform_view. Maybe there exists some another way. -
Django cant change default language
I have developed a web application in 2 languages, where users can change in-between them using the UI, and it all works fine, the language is changing. What I cant setup is the default language that is working when the application is opened for the first time. This is my settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] LANGUAGE_CODE = 'az' USE_I18N = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('az', 'Azerbaijani'), ('en', 'English'), ] urls.py urlpatterns = [ path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', include('main.urls')), # Include your app's URLs ) if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Djoser cant access extra fileds in registration
I am using Djoser and i have role field in user model as i integrated the role i cant signup a user. it works with without role but role field is import to update. in api body { "first_name":"test", "last_name":"data", "email":"testdata@gmail.com", "phone_number":"9876543210", "password":"pass@123", "re_password":"pass@123", "role":2 } i get thisAttributeError at /api/users/ 'dict' object has no attribute 'role' in social auth i cant get the first and last name My Serializers ` from .models import User from rest_framework import serializers from djoser.serializers import UserCreateSerializer class SignupSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ("first_name", "last_name", "email", "password", "role") extra_kwargs = { "first_name": {"required": True, "allow_blank": False}, "last_name": {"required": False, "allow_blank": True}, "email": {"required": True, "allow_blank": False}, "password": {"required": True, "allow_blank": False, "min_length": 6}, "role": {"required": False, "allow_blank": True}, } class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ("id", "first_name", "last_name", "email", "role") ` **Djoser and social auth settings ** ` DJOSER = { "SERIALIZERS": { "user_create": "accounts.serializers.SignupSerializer", "current_user": "accounts.serializers.UserSerializer", "user": "accounts.serializers.UserSerializer", }, "PASSWORD_RESET_CONFIRM_URL": "password-reset/{uid}/{token}", # "USERNAME_RESET_CONFIRM_URL": "username-reset/{uid}/{token}", "SEND_ACTIVATION_EMAIL": True, "ACTIVATION_URL": "activation/{uid}/{token}", "USER_CREATE_PASSWORD_RETYPE": False, "PASSWORD_RESET_CONFIRM_RETYPE": True, "LOGOUT_ON_PASSWORD_CHANGE": True, "PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND": True, "TOKEN_MODEL": None, "SOCIAL_AUTH_TOKEN_STRATEGY": "djoser.social.token.jwt.TokenStrategy", "SOCIAL_AUTH_ALLOWED_REDIRECT_URIS": config("REDIRECT_URLS").split(","), } SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("GOOGLE_CLIENT_ID") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("GOOGLE_SECRET") SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile", "openid", ] SOCIAL_AUTH_GOOGLE_OAUTH2_EXTRA_DATA … -
How to translate content with variables in Django Template?
I just took over an old project using Django 1.8 + Python 2.7. I need to refactor a feature where I have to retrieve different information based on different host information and display it on the page. Additionally, I need to internationalize this displayed information. my code looks something like this: <div> {% blocktrans with site_name=request.site.site_name %} welcome to {{ site_name }} {% endblocktrans %} </div> I want to translate this entire content, but I found that only the variable 'site_name' was translated eg:site_name = "stackoverflow" I want to translate welcome to stackoverflow, not stockoverflow. Can you tell me how to solve this problem? thanks!!!! -
Django Deploy Nginx Bad Gateway no such file or directory
So, I've been struggling for the past week to deploy my Django project on my VPS server (domains.co.za). After all this time, I managed to figure out a few things on my own. My server runs on AlmaLinux 9, and I'm connecting via the IP address 41.76.110.165. Here's what I've done so far: Gunicorn Configuration (/etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=marco Group=www-data WorkingDirectory=/home/marco/domestic_voicelogging ExecStart=/home/marco/domestic_voicelogging/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ domestic_voicelogging.wsgi:application [Install] WantedBy=multi-user.target Gunicorn Socket (/etc/systemd/system/gunicorn.socket) [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock SocketUser=marco SocketGroup=www-data SocketMode=0660 [Install] WantedBy=sockets.target Nginx Configuration (/etc/nginx/sites-available/myproject) server { listen 80; server_name 41.76.110.165; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/marco/domestic_voicelogging; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I'm encountering this error: 2024/07/09 10:11:40 [crit] 21042#21042: *8 connect() to unix:/opt/domestic_voicelogging.sock failed (2: No such file or directory) while connecting to upstream, client: 41.13.200.12, server: mydjangoserver.co.za, request: "GET / HTTP/1.1", upstream: "http://unix:/opt/domestic_voicelogging.sock:/", host: "41.76.110.165" Current Socket Status (venv) [marco@mydjangoserver domestic_voicelogging]$ ls -l /run/gunicorn.sock srw-rw-rw-. 1 marco www-data 0 Jul 9 09:37 /run/gunicorn.sock (venv) [marco@mydjangoserver domestic_voicelogging]$ I'm puzzled why the directory path in the error message shows /opt/domestic_voicelogging.sock instead of /run/gunicorn.sock. I've checked everything seems … -
Unknown command: 'collectstatic' after overriding StaticFIlesConfig
I followed the instructions on https://docs.djangoproject.com/en/5.0/ref/contrib/staticfiles/#s-customizing-the-ignored-pattern-list to override the ignore_patterns in my static files. Here are my steps: Created a new app app_staticfiles. in app_staticfiles.apps.py, this code: from django.contrib.staticfiles.apps import StaticFilesConfig class AppStaticfilesConfig(StaticFilesConfig): name = 'app_staticfiles' ignore_patterns = ["CVS", ".*", "*~", "*.map", "*.min.css", "*.min.js", "*.scss"] In original staticfiles, there is the management directory that has the following commands collectstatic and findstatic. Django project settings.py modified: INSTALLED_APPS = [ # ... # 'django.contrib.staticfiles', 'app_staticfiles', ] Now when I run collectstatic, I get error Unknown command. Obviously since I have commented out the original app from Django. Is there a way for this to run as-is without having to copy the management commands from original place to the overwriting app? -
django model add scheme to url field if not represented
I have a model with a URL field in my Django project. I want to ensure that a scheme (like https://) is added to the URL if it doesn't exist. from django.db import models class MyModel(models.Model): url = models.URLField() I've tried using the clean, save, clean_fields methods, but none of them seem to work. I feel there should be a straightforward way to accomplish this, but I can't find one. Any suggestions or best practices would be greatly appreciated. Thanks! -
Why does Request.build_absolute_uri lead to localhost instead of the real domain?
I have a website deployed on Nginx and built on Django. The Request.build_absolute_uri link there for some reason leads not to the real domain and ip which is attached to it, but to localhost:8080 of Waitress/gunicorn on which the app is running. Why? I tried Request.build_absolute_uri and request._current_scheme_host both lead to the localhost. Now, temporarily I just use the direct path like "domain.com", but it is not a very convinient decision. Could you please let me know how to solve it? -
My form validation in Django seems okay but it is not working
Template of the form Form.py models.py Views.py seetings.py Everything seems to be okay but the form is not storing data to the database, the form.py , views.py, models.py, settings.py .. For me everything seems okay but when i submit the form it doesn't store data into the database -
push reload or invoke javascript function from server
I have Django + React + uwsgi application. Uwsgi access to the database. Now I want to reload Django(React) web applicataion triggered by Database is changed. For example User open the web application Administrator use mysql command on server Insert into mytable(name) values("data") User's application will be reloaded or some javascript function be called. It's something like push reload from server. In my idea. Web application access the database to check the value is altered in every seconds. However It requires to access API every seconds. (And at most it has the one seconds delay, or requires too much api access) Is this a good practice ? Is there any good method for this purpose??