Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get url for htmx get from an SSE event which itself triggers the hx-get call?
I am using django with django-channels and htmx. In certain cases, my django views will send an SSE event to a user subscribed to the relevant channel, like a notification for example. Some of those events (depending on event name) needs to trigger a modal pop-up (like a rating modal after an e-commerce order or service completes). I have implemented the requirements of the server-side event and data generation. I want to use the htmx sse extension on the frontend (django template). My problem is, I want to get an event, let's say order_complete, and use that to trigger an hx-get call to a particular url which will be sent by the sse event. That hx-get's response will then be placed in the placeholder where modal view logic exists. I have very little knowledge of JavaScript and not all that much more on htmx. I've looked at out of band swaps but I'm not sure if that's what I need. I'd appreciate any opinion or suggestions for proceeding including a non-htmx solution if it's better performing or easier. Thank you. -
How to show live streaming camera videos in django rest framework
I am building a application in django rest framework and frontend in react i want to shows streaming of multiple live camera into browsers there is any way how we can achieve it using openCV or how we can genrate response with stream of bytes in django rest framework -
Django Admin Custom Queryset. prevent e=1
I have a need to enter product ids in the url of my admin page but Django does not allow me to. This is my function that does work. def get_queryset(self, request): qs = super(LaptopStockAdmin, self).get_queryset(request) pid = request.GET.get('pid') if pid is not None: ids = [int(id) for id in pid.split(',')] return qs.filter(id__in=ids) else: return qs It gets the objects related to the ids but then Django refreshes the page and ads ?e=1 after the URL. This is a security related problem and I cannot find a suitable solution. I have tried these methods but they don't work for my specific case. Is there a way to not create a list filter and where the results are shown in the admin page? -
Configuration Error : The DNS query name does not exist:_mongodb._tcp.nonr.mongodb.net
Output with error utlis.py for extracting db list from mongo db This code works fine when run on a different python file, but I'm getting error when I run with a django project. from urllib.parse import quote_plus from pymongo import MongoClient def auth(username, password, cluster_uri): username = quote_plus(username) password = quote_plus(password) conn_str = "mongodb+srv://{}:{}@{}.mongodb.net/?retryWrites=true&w=majority".format( username, password, cluster_uri ) return MongoClient(conn_str) def getDatabaseList(username, password, cluster_address): client = auth(username, password, cluster_address) dbs = client.list_database_names() # returns a list of databases return dbs views.py from rest_framework import status from rest_framework.decorators import permission_classes from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny, IsAuthenticated from .utils import getDatabaseList u/permission_classes([AllowAny]) class TestViewSet(APIView): def post(self, request): username = request.data.get('username') password = request.data.get('password') cluster_address = request.data.get('cluster_address') dblist = getDatabaseList(username, password, cluster_address) return Response({'dblist': dblist}, status=status.HTTP_200_OK) -
Nginx responds 404 not found on Django media URL in preprod, dev ok
I have a quite standard Django application with a Vuejs frontend. I have different environments (preprod/dev) in which I have file upload/download features. For files, everything works fine because they are returned through standard API views in attachment (Content-Disposition: attachment). When it comes to images though, like profile pictures, there is a problem. In development (DEBUG=True), I have this : from django.conf import settings from django.conf.urls.static import static from django.urls import include, path from backend.applications.base.views.authentication_views import LoginAPIView, LogoutAPIView urlpatterns = [ path("api/login", LoginAPIView.as_view()), path("api/logout", LogoutAPIView.as_view()), path("api/base/", include("backend.applications.base.urls")), path("api/contact/", include("backend.applications.contact.urls")), path("api/helpdesk/", include("backend.applications.helpdesk.urls")), path("api/inventory/", include("backend.applications.inventory.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) # For serving media files when DEBUG=True and images are correctly served (no nginx in dev mode, just frontend and backend dev servers). My preprod however, is made of a nginx container which serves my built vuejs frontend, and a backend container which contains my Django (DEBUG=False) application. Before trying to serve images, I had this nginx configuration : http { client_max_body_size 5M; upstream backend_api { server backend:8000; # 'backend' is the name of the backend service in my docker-compose config } server { listen 80; include /etc/nginx/mime.types; root /usr/share/nginx/html; index index.html; location = /favicon.ico { access_log off; log_not_found off; } location /api … -
Can't access Heroku /tmp/build_{sha} build files in Github Action once build has completed
I run a Github Action that deploys my app to Heroku with two relevant steps. Build Step: push to Heroku, build (including heroku/nodejs buildpack), create JS sourcemaps (among other things). Sentry Release Step: create a Sentry release, and ideally upload the sourcemaps created in Build Step. I've noticed in build logs that my build directory is /tmp/build_{sha}/. The project is built here, and sourcemaps therefore would be found in /tmp/build_{sha}/static/dist. The problem is, I can't find the build directory or the sourcemaps in Sentry Release Step, or any step that runs after Build Step has completed. Following Build Step completion, I've examined /tmp but there's no build_{sha} folder inside. Yet when I run heroku run bash on the deployed dyno, I see sourcemaps in /static/dist and /staticfiles/dist, where I'd expect them. So where did build files go after Build Step and before deployment? Shouldn't build files be accessible throughout the Github Action? I've had success accessing sourcemaps within Build Step, by using a Sentry Sourcemap buildpack. Obviously this runs during the build. But I would prefer to have this happen in the Github Action. I've also tried the SentryWebpackPlugin but I've determined sourcemaps must be uploaded once webpack has completed … -
django admin static files keep breaking
so i have upgraded my django from 3.0.7 to 4.1 and deployed it with docker. at first everything looks good but the next day everything in django admin breaks. dark mode won't be working neither. but when i go and run collectstatic command and rewrite static files everything goes back to normal. any idea why this happen? -
Multi-User & parallel & Dynamic workflow in Django
I'm looking for the best solution for the development of workflow engine in Django (Django-Rest-Framework) by this requirement : permission checking/task assignment options Parallel workflows allow to have several active tasks at once and probably have some sort of parallel sync/join functionality dynamic workflows typically could be configuring by changing the contents of workflow database tables The approach I found: one approach is BPMN engines, and use the SpiffWorkflow package(which is python pure not Django) one other approach is to use camunda API (can create limitations) or use Django-based workflows packages that I did not find a package that supports Multi-user(permission) & Parallel & Dynamic workflows What is the best solution for this problem? -
How to use Oscar API Login with React JS or any JavaScript framework?
I use Oscar API in my project. It uses httponly cookies to log in and register and other options like add to basket. All I need is to use it with react/next js project. But I can't access cookies because of httponly cookies. So please help me with oscar API authentication. In my react js code I already use withcredentials true when fetching from API. in the Django setting I already use CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None CRSF_COOKIE_SAMESITE = None -
How to send sms to user mobile using MSG91 in django reset framework api
'''from sendsms.backends.base import BaseSmsBackend from django.conf import settings import urllib MSG91_AUTHKEY = getattr(settings, 'MSG91_AUTHKEY', '') MSG91_ROUTE = getattr(settings, 'MSG91_ROUTE', '') class Msg91SmsBackend(BaseSmsBackend): def send_messages(self, messages): for message in messages: for to in message.to: values = { 'authkey' : MSG91_AUTHKEY, 'mobiles' : to, 'message' : message.body, 'sender' : message.from_phone, 'route' : MSG91_ROUTE } print(values) postdata = urllib.urlencode(values) req = urllib.Request(url, postdata) response = urllib.urlopen(req) output = response.read() # Get Response print(response)''' -
How I can get the value of check radio button in update page
How I can get the value of check radio button in update page, it save it DB but in update page it did not show the selected radio button. in models user_role = models.CharField(max_length=25, default="USER") in add html <tr> <td class="mtrr"><b>User Role*</b></td> <td class="mtrr"><label class="radio-inline"><input type="radio" name="user_role" value="admin" checked>Admin</label></td> <td class="mtrr"><label class="radio-inline"><input type="radio" name="user_role" value="super">Super User</label></td> <td class="mtt"><label class="radio-inline"><input type="radio" name="user_role" value="user">User</label></td> </tr> in update add html <tr> <td class="mtrr"><b>User Role*</b></td> <td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">Admin</label></td> <td class="mtrr"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">Super User</label></td> <td class="mtt"><label class="radio-inline"><input {% if data.ul_role == True %} checked {% endif %} type="radio" name="user_role">User</label></td> </tr> -
Deploying Django Channels with nginx
I am trying to deploy the Django application in AWS ubuntu os with Django channels, Using Nginx. I had configured the Django server in Nginx. But I don't know how to configure channels or Redis-server in Nginx. My nginx config is as follows: server { listen 80; server_name 52.77.215.218; location / { include proxy_params; proxy_pass http://localhost:8000/ } } My settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } My requirements.txt: aioredis==1.3.1 asgiref==3.5.2 async-timeout==4.0.2 attrs==22.1.0 autobahn==22.7.1 Automat==20.2.0 certifi==2022.6.15 cffi==1.15.1 channels==3.0.5 channels-redis==2.4.2 charset-normalizer==2.1.1 constantly==15.1.0 coreapi==2.3.3 coreschema==0.0.4 cryptography==37.0.4 daphne==3.0.2 defusedxml==0.7.1 Django==4.1 django-cors-headers==3.13.0 django-templated-mail==1.1.1 djangorestframework==3.13.1 djangorestframework-simplejwt==4.8.0 djoser==2.1.0 gunicorn==20.1.0 hiredis==2.0.0 hyperlink==21.0.0 idna==3.3 incremental==21.3.0 itypes==1.2.0 Jinja2==3.1.2 MarkupSafe==2.1.1 msgpack==0.6.2 mysql==0.0.3 mysqlclient==2.1.1 oauthlib==3.2.0 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 PyJWT==2.4.0 pyOpenSSL==22.0.0 python3-openid==3.2.0 pytz==2022.2.1 requests==2.28.1 requests-oauthlib==1.3.1 service-identity==21.1.0 six==1.16.0 social-auth-app-django==4.0.0 social-auth-core==4.3.0 sqlparse==0.4.2 Twisted==22.4.0 twisted-iocpsupport==1.0.2 txaio==22.2.1 typing_extensions==4.3.0 tzdata==2022.2 uritemplate==4.1.1 urllib3==1.26.12 zope.interface==5.4.0 When I run server with python3 manage.py runserver 0.0.0.0:8000 Server running good and also connecting with redis-server but when I run server with gunicorn app.wsgi -b 0.0.0.0:800 then failed to connect with webbsocket. I also tried Hostinger VPS as well, but Same Issue. -
datetimepicker format is not working properly
I used datetimepicker to select month and year. On the first click of the page load ,datetimepicker shows months and year.But when I click on the same date field again to change the month, datetimepicker displays dates instead of months. Here I also used select2 in my code.I implemented it in Django web framework. <script> $(function(){ $('#id_from_date').datetimepicker({ format: 'MM-YYYY', }); $('#id_to_date').datetimepicker({ format: 'MM-YYYY', }); }); $(document).ready(function() { $('select').select2(); }); Can anyone suggest a solution to solve this issue? -
DoesNotExist at /thankyou/11
ApplicationModel matching query does not exist. def thank_you(request, id=0): if request.method == 'GET' and id != 0: status = stripe.PaymentIntent.retrieve(request.GET['payment_intent']) updateStatus = ApplicationModel.objects.filter(user_id = request.user.id).get(id=id) updateStatus.payment_status = status['status'] updateStatus.save() return render(request, 'thankyou.html') -
Django Enum not reflecting @override_settings()
from django.conf import settings from django.test import TestCase class Enum1(Enum): X = f'{settings.X}' @override_settings(X='abc') class Test1(TestCase): def test1(self): self.assertEqual(settings.X, Enum1.X.value) # Doesnt work I have variable X in settings.py I modify it in this test case to X='abc' But the Enum is still using its old value. Is there a way to make Enum use new value ? One workaround is if I create a func in Enum1 then it works. eg: class Enum1(Enum): @classmethod def get_x(cls): return f'{settings.X}' The overall takeaway is that any class variable doesnt reflect override_settings() changes. Only a function which is not instantiated initially when py file gets imported, reflects those changes. -
How to Change order of Modules listed in Side Bar of Django Admin
See here are some modules in alphabetical order by default in the admin sidebar Authentication and Authorization Data/Questions/Surveys/Website admin I want to rearrange the order how can I do that. ? I know in the Django world it does not matter. But our client requested to do that. So we need help with how we can do that. -
Data is empty when update to database
I had a problem when i try django, i had a function like this: def function(id): data = { a: "a", b:"b", c:"c" } model = Models.objects.get(id=id) print(json.dumps(data)) # when try to print this, there is a value model.data = json.dumps(data) # but when i tried to update my table in db, sometimes there is value, and sometimes is empty model.save() is anyone had any issues like this before? Thanks -
Django - I need to specify amount of price rows
So i need to post on page price-row like: name: medicalservice --> contains this prices ---> 1# --- name --- price --- quantity 2# --- 2name --- 2price --- 2quantity And i want to post them in one page i need to take price rows exactly declared for this medical service I cant get the idia how to get it done through admin panel (i dont know how to insert quantity value quantity into it) I created an intermidiate model (services_count) but i think its not best idea :0 from django.db import models from tinymce import models as tiny_models from django.urls import reverse class Medservices(models.Model): public = 'pub' private = 'priv' status_post = [(public,'public'),(private,'private')] position = models.IntegerField(default=1, verbose_name="Позиція") status = models.CharField(max_length=10,default=public,choices=status_post, verbose_name="Статус показу") photo = models.ImageField(verbose_name='Фото послуги або акції', upload_to='services_images', max_length=None) date_start = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False) date_expire = models.DateField(verbose_name='Дата початку', auto_now=False, auto_now_add=False) title = models.CharField(verbose_name='Назва послуги або акції', max_length=300) text = text = tiny_models.HTMLField() slug = models.SlugField(max_length=255,unique=True,verbose_name="URL",db_index=True) def __str__(self): return f"{self.price.all} - to {self.status}" def get_absolute_url(self): return reverse('service_page', kwargs={'post_slug': self.slug}) class services_count(models.Model): quantity = models.IntegerField(verbose_name='Кількість цієї послуги у сервісі') service = models.ForeignKey("medservices.Medservices", verbose_name='Послуга або акція', on_delete=models.CASCADE) prices = models.ManyToManyField("price.Price", verbose_name='Ціни') admin panel: from django.contrib import admin from medservices.models import … -
How to create a table from fetchall dictionary variable? Django
I have a dictionary being created from the result of a query using cursor. I have defined "dictfetchall(cursor):" in order to convert the result into a dictionary as shown below enter image description here This is the code where the variable is created This is my index.html table code The data gets called correctly but the table never appears -
How to submit form which has data that is prepopulate and posted data
I have a form which has 2 types of inputs, prepopulated and data and data that requires to be added in the input. I am trying to submit the form but I am getting nothing in the data base. I have found several related answers but they are old and require that either all the data to pre-populated or all data to be added, but in my form it is a mix of both. Here is the views: def addlog(request, pk): url = request.META.get('HTTP_REFERER') if request.method == 'POST': form = LogForm(request.POST) if form.is_valid(): data = Log() data.log_workout = form.cleaned_data['log_workout'] <------ prepopulated in template data.log_repetitions = form.cleaned_data['log_repetitions']<------ not prepopulated in template data.workout_id = Workout.pk data.save() return HttpResponseRedirect(url) return HttpResponseRedirect(url) Template: <form class="review-form" action="{% url 'my_gym:addlog' workout.id %}" method="post"> {% csrf_token %} <input hidden type="text" name="log_workout" value="{{ object.name }}" required id="id_log_workout"> <input name="log_repetitions" required id="id_log_repetitions"> </div> <button type="submit"> </button> </form> -
Django manytomanyfield field request error
My participants fields is Manytomanyfield. I will create new chat. What do should add participants in my request? this User models.py: class User(AbstractUser): phone = models.CharField(default=None, max_length=11, verbose_name='Telefon Numarası', blank=True) photo = models.ImageField(default=None, verbose_name='Profil Fotoğrafı', blank=True, null=True) company = models.ForeignKey(Company, null=True, blank=True, on_delete=models.CASCADE, verbose_name="Firma") models.py: class Chat(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, verbose_name="Proje") name = models.CharField(max_length=255, verbose_name="Sohbet Adı") cover = models.ImageField(blank=True, verbose_name="Kapak Fotoğrafı") participants = models.ManyToManyField(User, verbose_name="Katılımcılar") def __str__(self): return self.name serializers.py: class Meta: model = User fields = ['id'] class ChatSerializer(serializers.ModelSerializer): is_perm = serializers.SerializerMethodField('get_is_perm') participants = UserSerializer(many=True) class Meta: model = Chat fields = '__all__' view.py: class ChatList(generics.ListAPIView): serializer_class = ChatSerializer permission_classes = [permissions.IsAuthenticated] filter_backends = [filters.SearchFilter] search_fields = ['name'] def get_queryset(self): queryset = Chat.objects.all() project = self.request.query_params.get('project', None) if project: queryset = queryset.filter(project__id=project) return queryset def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) my request: -
Can't reset index in view function
I am calling a view function and that view function calls another function on a 1 min timer. The issue I am having is resetting the 'i' value. Can someone help me figure out how to fix this or or come up with a new way for me to do this. I want to call the getABC function on a one minute timer and have it loop through the 'listOfStrings' and then have it start the list back over once it reaches the end. I have a feeling I am looking over something and making it much more complicated than it needs to be. def viewfunction(request): listOfStrings = [...list Of Strings ] i = 0 def func(): for each in range(i-60, i-1): getABC(listOfStrings[each], each) if listOfStrings[each] == 'ZYXI': i = 0 return schedule.every(1).minutes.do(lambda: func()) while True: i += 1 schedule.run_pending() time.sleep(1) The issue with the code above is the 'i' in "for each in range(i-60, i-1):" gets the UnboundLocalError: local variable 'i' referenced before assignment. So then I try to pass in the i as a param and then return it but idk how would I access that variable if func(i) being called how it is. def viewfunction(request): listOfStrings = … -
Why is django losing session after save any python file?
I'm really stuck in my project, I explain: Every time I save a file, (no matter what it is) with a .py extension, I know that Django uses StatReloader to check for changed files. My problem is that it removes the logged in user (I don't know if it's a problem with the session) This has consequences for me, such as not being able to save and test things quickly, since I have to log in every time I save a file. It would be very helpful if someone can give me a hand! -
roku config:set DISABLE_COLLECTSTATIC=1 Django
$ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_01f62511/manage.py", line 22, in main() File "/tmp/build_01f62511/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/init.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/init.py", line 386, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 92, in getattr self._setup(name) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 79, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.10/site-packages/django/conf/init.py", line 190, in init mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.10/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "/tmp/build_01f62511/main/settings.py", line 25, in SECRET_KEY = config("SECRET_KEY") File "/app/.heroku/python/lib/python3.10/site-packages/decouple.py", line 243, in call return self.config(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/decouple.py", line 105, in call return self.get(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/decouple.py", line 90, in get raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) decouple.UndefinedValueError: SECRET_KEY not found. Declare it as envvar or define a default value. ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ … -
Is it possible to recover my heroku postgressql hobby-dev DB after a deletion?
I recently upgraded hobby-dev to hobby-basic on heroku using all the step of this link upgrade hobby-dev to hobby-basic I forgot to remove the hobby-dev DB, my django app so were attached to 2 heroku postgres DB. May be my app continued to store data into the hobby-dev. Yesterday on heroku platform I deleted the hobby-dev without knowing, I lost a lot of precious data. I want to know if I can recover my first hobby-dev. Please help!