Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HTMX tags not activating when using locally-stored copy of source code in Django project
I have a Django project where I'm using HTMX to set up "cascading" SELECT widgets (i.e. the options listed in SELECT #2 are modified based on the user option from SELECT #1). I've confirmed that the HTMX tags in SELECT #1 are triggering as expected when I put this line in the HTML template header to pull in the HTMX code from their web site: <script src="https://unpkg.com/htmx.org@1.9.2" integrity="sha384-L6OqL9pRWyyFU3+/bjdSri+iIphTN/bvYyM37tICVyOJkWZLpP2vGn6VUEXgzg6h" crossorigin="anonymous"></script> Specifically, I can confirm the event is triggering because at this point the corresponding view for the target (create_itemid_2) is just a stub, and I see the printed message in my Powershell console. def create_itemid_2(request): print('HTMX event fired') context = {} return render(request,'create_itemid_2.html',context) So now I want to pull down the code, and use it locally in my Django project, so I'm not dependent on the external resource. The problem is, after I've done that, the event never triggers. I can even see the js file being successfully retrieved in my console (HTTP status 200, then 304 after that), but still the event never triggers. [14/Jun/2023 08:05:05] "GET /newitemid/ HTTP/1.1" 200 1652 [14/Jun/2023 08:05:05] "GET /static/htmx/htmx.min.js HTTP/1.1" 200 361101 [14/Jun/2023 08:09:50] "GET / HTTP/1.1" 200 515 [14/Jun/2023 08:09:52] "GET /newitemid/ HTTP/1.1" … -
How to optimize the filtering of queryset in ModelViewSet
I'd like to know if it's possible to optimize the following code (especially the part when event_wmode is passed as a parameter) class MessageViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.DjangoModelPermissions,) serializer_class = MessageSerializer filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ] filter_fields = ["device", "date", "variable", "sensor"] search_fields = [ "variable", "device__name", ] ordering_fields = "__all__" ordering = ["device", "-date"] def get_queryset(self): if self.request.user.is_superuser: return Message.objects.all() else: return Message.objects.filter(device__users=self.request.user) def list(self, request, *args, **kwargs): if not self.request.GET.get("event_wmode"): return super().list(request, *args, **kwargs) else: # remove duplicate wMode in result queryset = self.filter_queryset(self.get_queryset()) currentwMode = None excluded_pks = [] for item in reversed(queryset): if item.variable == "wMode": if item.message not in ["1", "4", "8", "9", "10"]: excluded_pks.append(item.pk) continue if currentwMode == None: currentwMode = item.message continue elif currentwMode == item.message: excluded_pks.append(item.pk) else: currentwMode = item.message queryset = queryset.exclude(pk__in=excluded_pks)[:100] # paginate the result page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The purpose of this mode is to remove unnecessary wMode. What I want is to keep only the wMode when it changes, and only the values 1 4 8 9 and 10 (for variable=wMode only). Let's imagine I have this message sequence: [{ message: … -
django only show the highest value of m2m in template
Hej! I have a table view with multiple columns one of them contains a m2m field from the model. I dont want all values (if multiple values/entries are given for that m2m) only the highest. Example: 1890 bonbons 30 bonbons 300000 bonbons i only want to show the 300000 bonbons in that cell and not all 3 values. {% for candymarket in mall %} <td> {% for bon in candymarket.bonbon_color.all %} {{bon.value}} | {{bon.color}} {% endfor %} </td> {% endfor %} How can I filter inside the template? I still want to be able to get all values in a detail view. Is there something like {% if bon.value|length > 200 %} only with is max? Any help or link to a documentation is appreciated! :) class CandyMarket(models.Model): name = models.CharField( max_length = 500, unique = True ) bonbon= models.ManyToManyField( Bon, verbose_name = "BON", through = "BonForCandyMarket", blank = True, related_name = "bonbon_in_market" class BonForCandyMarket(models.Model): market= models.ForeignKey( Candymarket, on_delete = models.PROTECT, related_name = "bonbon_color" ) bon= models.ForeignKey( Bon, on_delete = models.PROTECT, related_name = "market_with_bonbon" ) value= models.PositiveSmallIntegerField( blank=True, null=True ) class Bon(models.Model): description_english = models.CharField( max_length = 500, unique = True ) -
Django admin url shows "table or view does not exist" while using oracledb
I am very beginner to django & oracle. Trying to connect oracledb from django using hr schema. Data is availabe to django model from database but it shows "table or view does not exist" when browsing admin url. I have the following tables on the database. DJANGO_MIGRATIONS DJANGO_CONTENT_TYPE AUTH_PERMISSION AUTH_GROUP AUTH_GROUP_PERMISSIONS AUTH_USER AUTH_USER_GROUPS AUTH_USER_USER_PERMISSIONS DJANGO_ADMIN_LOG Does django automatically migrate admin to the oracle database or I need to create them manually? -
Issues running Django Channels in Docker container
I am running Django application in Docker container. The command I use to start Django application is daphne -b 0.0.0.0 -p 8000 main.asgi:application. However, I get an error that ModuleNotFoundError: No module named 'main'. Here is my asgi.py file: import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') django.setup() from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from modules.chat.urls import ws_urlpatterns as chat_ws_urlpatterns application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(chat_ws_urlpatterns)) }) What is wrong in my asgi.py configuration? -
i keep getting the error "Parameter "form" should contain a valid Django Form." when i try to create form from class in models
i need to add comment to class Course and when i try to make form from the class it show this error models.py class Course(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=7, decimal_places=2) period = models.DecimalField(max_digits=5, decimal_places=2) instructor = models.CharField(max_length=50) description = models.TextField(max_length=250) image = models.ImageField(upload_to='courses/') category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100, blank=True, null=True) user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateField(auto_now_add=True) comment = models.ManyToManyField(Comment, related_name=("user_comment")) def __str__(self): return self.name forms.py class CommentForm(forms.ModelForm): class Meta: model = Course fields = ['comment'] views.py def comment_add(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): myform = form.save(commit=False) myform.user = request.user myform.save() return redirect('home:home') else: form = CommentForm cont = {'form': form} return render(request, 'desc.html', cont) desc.html <form method="post" class="pt-4"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-info text-white w-100" type="submit">comment</button> </form> i tried to solve the error but i can't -
Save Django attachments from a form
Good morning, I would greatly appreciate your help, I am starting to use Django and I am making a web application that allows workers in a job to attach their documentation (files) through a form. The problem is that at the moment of pressing the submit of the form with the attached files, these are not saved, however, the name and other fields of the Charfield type are saved correctly. The only way to save the files is to attach them from the admin portal, but the idea is that each user enters from a url generated with their id that will be sent by email. Also, the files should be saved with the naming (DSR_”rut”-”name”-”filename (form label)”-0-”extension), but I still can't configure the naming of the file name instance. file, according to the label of the form. models.py: class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=upload_directory_name, null=True, blank=True) certificado_antecedentes = models.FileField(upload_to=upload_directory_name, null=True, blank=True) hoja_de_vida_conductor = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_residencia = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_afp = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_salud = models.FileField(upload_to=upload_directory_name, null=True, blank=True) … -
Create new column in the existing table that has value as other column in sql using django ORM
I want to add new column in existing table that cannot be null and should have value as other column in the table. My attempt: In my django app models, I have added the new field and migrated using migrations: order_id = models.IntegerField(null=True) Ran the below sql query in database Update order_data_table SET order_id=id Again removed null=True from models so as to set it as non-nullable field and migrated Is there a better way to do? -
Search based application using Elasticsearch
I want to make search based application using python and elasticsearch. I want to create web application for this i will python but which framework i should use Django or Flask i don't know. -
Reliable django-river alternatives?
I like the workflow functionality that django-river provides, but its performance is inappropriate and occasionally it fails to find the next available choices. Do you know any fast and reliable django-river alternatives that would use Python code instead of database relations for workflow states? -
Converted PDF is downloadable on both mobile (375px) and lg devices (1024px) but it is not visible on mobile devices. It is not clickable on mobile
This is my views.py to convert html template to pdf from datetime import datetime from io import BytesIO import os from django.conf import settings from django.http import HttpResponse from frontend.views.task_shifts import valid_task_date from frontend.views.utils import * from django.contrib.auth import logout from django.shortcuts import redirect, render from django.contrib.auth import logout from xhtml2pdf import pisa from django.template.loader import get_template from django.contrib.auth.decorators import login_required def render_to_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf_path = os.path.join( settings.BASE_DIR, 'pdf_files', 'Rating_report.pdf') pisa_status = pisa.CreatePDF(html, dest=result) if pisa_status.err: return HttpResponse('We had some error') with open(pdf_path, 'wb') as f: f.write(result.getvalue()) return pdf_path @login_required(login_url='login_user') def get_pdf(request): if request.user.is_authenticated == False or request.session.get('station_code') is None or request.session['station_code'] is None: logout(request) return redirect("login_user") if (request.method == 'POST'): date1 = request.POST.get('date') date = datetime.strptime(date1, '%Y-%m-%d').date() context = {'date': date } pdf_path = render_to_pdf('front/pdf/pdf.html', context) pdf_file = os.path.basename(pdf_path) with open(pdf_path, 'rb') as f: response = HttpResponse(f.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename="{pdf_file}"' return response else: messages = [] messages.append('Enter date to see pdf') return render(request, 'home.html', {'messages': messages}) and my html template is {% load custom %} {% load static %} {% block body %} <h1> pdf demo</h1> <p>for : {{date}}</p> {% endblock %} and the form to submit the … -
django.db.utils.DataBaseError: database disk image is malformed
I am getting the above error in my terminal. My db.sqlite3 file is explicitly re-assigned to plain text. I want to fix that thing. Please guide me regarding this issue. This error is with the database file. This is displaying me a warning in the db.sqlite3 file as "This file is explicitly re-assigned to plain text". -
Image not shown in debug for false in django
I want to run always in debug=false in django. However, it works only when i turned to debug to true. Otherwise not. In setting.py DEBUG = False also, in setting.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' MEDIA_URL = '/media/' if DEBUG: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] else: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In main urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('mysite.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have directory of media, static, staticfiles in the directory where manage py is located. If i put code exactly in apache will my code works. P.S In development also i want to fix debug as false always. -
passing websocket messages from django consumers.py to html, then respond back to backend
The problem i'm having is The only way i can find to pass messages from consumers.py which recieves the message to index.html where its needed is with this line. async_to_sync(self.channel_layer.group_send)( self.room_group_name, {"type": "chat_message", "message": message} ) this sends the message to index.html AND back to my backend... i dont want it to bounce the message back to my backend. how can i send a response back to my backend from index.html because i need to send info on what the user has entered into an in? here is an example of how the system currently works how websockets currently work and heres how i want them to work how i want websockets to work how can i stop bouncing the message back to my backend and still pass the message onto my html, then respond from my html back to my backend? ################ below is the code js in my index html const colorSocket = new WebSocket( "ws://" + window.location.host + "/ws/endpoint/chat/" ); colorSocket.onopen = function() { console.log("Connected! (" + this.readyState + ")"); }; colorSocket.onmessage = function(event) { let data = JSON.parse(event.data); console.log(data.message); // etc........... } consumers.py import json import random from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class … -
Django template: Set same data in tables cell matching to header
I have below view.py c0 = date.today().replace(day=16) c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) datadump = data.objects.filter(user=request.user,ret_prd__gte=datetime.now() - relativedelta(months=5)).order_by('type','user','-ret_prd') return render(request,'rethome.html',{'datadump':datadump,'c0':c0,'c1':c1,'c2':c2,'c3':c3,'c4':c4,'c5':c5}) And below template code: {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> <table> <tr> <th>user</th><th>{{c0|date:'M Y'}}</th><th>{{c1|date:'M Y'}}</th><th>{{c2|date:'M Y'}}</th><th>{{c3|date:'M Y'}}</th><th>{{c4|date:'M Y'}}</th><th>{{c5|date:'M Y'}}</th> </tr> {% regroup type.list by user as userlist %} {% for user in userlist %} <tr><td>{{user.grouper}}</td> {% for data in user.list %} <td>{{user.ret_prd}}</td> {% endfor %} </tr> {% endfor %} </table> {% endfor %} I am getting below result: Is there any way I can show for each user row cells under same column heading? -
I created a new Django project but I did not get a new one. Although I create new ones, it gives me one of my previous projects
enter image description hereenter image description here These two images were not the same project but they were giving me the same project. They were totally new projects. But when I run the project they did not return me a new Django project as usual Working on project. Once remembered create virtual environment and try to create. But I think I, I could not create virtual env properly. After that I am able create new project on django. All new projects will be created the same project as above. -
How to initialize a custom model field for testing?
I've got a custom model field class VaultField(CharField): which is used to store values in Vault. Used like so: class MyClass: secret = VaultField(max_length=200, blank=True) The custom field is using self.model.__name__. My plan was to unit test this field by initializing it and calling the methods (from_db_value, to_python, etc.): field = VaultField(blank=True) field.to_python() But because the field is using self.model it's erroring on: AttributeError: 'VaultField' object has no attribute 'model' How do I get a model into the VaultField? This does not work: VaultField(max_length=200, blank=True, model=MyModel) -
How to get Redis cache info from requests_cache
I'm using requests_cache library with Redis and i want to know how to get info from redis cache. My task is to send info from 3rd party API json in Redis with celery every 5 minutes and get info from redis in my view. How can i do that? celery.py @app.task def get_project_budget(): backend = requests_cache.RedisCache(host=config('REDIS_HOST'), port=config('REDIS_PORT'), password=config('REDIS_PASSWORD'), ttl_offset=259200) session = requests_cache.CachedSession('project_cache', backend=backend, stale_if_error=True, expire_after=360) url = 'http://3rd_party_api.com' response = session.get(url) views.py import requests_cache class ProjectList(ListView): def get_queryset(self): # How can i call Redis cache there by name queryset = [] return queryset -
How do i get the value from returned JSON object?
I am trying to implement like function on my site, so when user likes the post,like button changes to unlike button and vice versa. So i wrote a function in my django app side that returns True/False if post is liked/unliked. I get this response: {like: true} How do i get just this true value without anything else? -
Django regroup a regrouped data not working
I have below D table: type month user First 2023-05-01 1 second 2023-04-01 1 second 2023-05-01 1 First 2023-03-01 1 second 2023-02-01 1 First 2023-02-01 1 second 2023-02-01 1 In view: datadump = db.objects.filter(user=request.user) In template I am trying to achive something like this: **type** User - list of all months I have tried below code and I am able to group by type but not able to group by user again. {% regroup datadump by type as ret_type %} {% for type in ret_type %} <h1>{{ type.grouper }}</h1> {% regroup type.list by user as userlist %} {% for user in userlist %} <h4>{{user.grouper}}</h4> {% endfor %} {% endfor %} If I try above code I am getting user list multiple time, instead of grouping user. -
JavaScript Separator
I want to receive data from DJANGO and change HTML VALUE according to the data with JAVASCRIPT. BUT JAVASCRIPT not work. I'll send you what I've made up. I don't know what's wrong ##django view def message(msg): time.sleep(1) return f'{msg} ' def get_data(): status_code =['AB','CD','EF','GH','IJ'] for i in status_code: time.sleep(0.5) print(i) yield message(i) def test_stream(request): stream = get_data() # stream = db_restore_test() response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream') response['Cache-Control'] = 'no-cache' return response def jobs(request): return render(request, 'jobs/index.html') #html (javascript) const arr = oEvent.target.responseText.split(' ') log(arr.reverse()[1]) const data = arr.reverse()[1] if (data == 'AB'){ document.getElementById('step1_status').innerHTML = '시작'; log('1') } else if (data == 'CD'){ document.getElementById('step1_status').innerHTML = '완료'; document.getElementById('step2_status').innerHTML = '시작'; log('2') } else if (data == 'EF'){ document.getElementById('step2_status').innerHTML = '완료'; document.getElementById('step3_status').innerHTML = '시작'; log('3') } else if (data == 'GH'){ document.getElementById('step3_status').innerHTML = '완료'; document.getElementById('step4_status').innerHTML = '시작'; log('4') } else if (data == 'IJ'){ document.getElementById('step4_status').innerHTML = '완료'; log('5') } } WEB Console I dont understand why result only '2'. -
Date fixed but variable month and year in python
I have below code: from datetime import date, datetime, timedelta from dateutil.relativedelta import relativedelta c0 = date.today() c1 = c0 - relativedelta(months=1) c2 = c0 - relativedelta(months=2) c3 = c0 - relativedelta(months=3) c4 = c0 - relativedelta(months=4) c5 = c0 - relativedelta(months=5) Now date today is 2023/06/14, however what I am trying to achieve is that no matter what date it is, I should get 16 as day, and actual current month and year. I have tried adding int to current date but since current date is not fixed, I am not able to get 16 as day. Please suggest a way where I can convert below to a date: day = 16 month = current month year = current year date = year/month/day -
return '<SimpleProducer batch=%s>' % self.async while using KafkaProducer
Here's run.py from app import create_app if __name__ == '__main__': app = create_app() app.run(host='0.0.0.0', port=8000, debug=True) Here's the /app/app/__init__.py from flask import Flask from flask_cors import CORS from app.config import Config from threading import Thread from app.consumer.kafka_consumer import consume_messages def create_app(): app = Flask(__name__) app.config.from_object(Config) app.config['SQLALCHEMY_DATABASE_URI'] = Config.MYSQL_DATABASE_URI app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False CORS(app) consumer_thread = Thread(target=consume_messages) consumer_thread.start() # Register blueprints from app.controller.segmentation_controller import segmentation_bp app.register_blueprint(segmentation_bp) return app Here's the /app/app/consumer/kafka_consumer.py from kafka import KafkaConsumer from app.config import Config from app.service.segmentation_service import SegmentationService def consume_messages(): segmentation_service = SegmentationService() consumer = KafkaConsumer( Config.KAFKA_TOPIC, bootstrap_servers=['localhost:9092'], auto_offset_reset='latest', # Start reading from the latest available offset enable_auto_commit=True, group_id='my-group', value_deserializer=lambda x: x.decode('utf-8'), ) for message in consumer: segmentation_service.process_messages(message) Here's the error message 2023-06-14 11:44:43 Traceback (most recent call last): 2023-06-14 11:44:43 File "run.py", line 1, in <module> 2023-06-14 11:44:43 from app import create_app 2023-06-14 11:44:43 File "/app/app/__init__.py", line 5, in <module> 2023-06-14 11:44:43 from app.consumer.kafka_consumer import consume_messages 2023-06-14 11:44:43 File "/app/app/consumer/kafka_consumer.py", line 1, in <module> 2023-06-14 11:44:43 from kafka import KafkaConsumer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/__init__.py", line 23, in <module> 2023-06-14 11:44:43 from kafka.producer import KafkaProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/__init__.py", line 4, in <module> 2023-06-14 11:44:43 from .simple import SimpleProducer 2023-06-14 11:44:43 File "/usr/local/lib/python3.8/site-packages/kafka/producer/simple.py", line 54 2023-06-14 11:44:43 … -
django terminology for the two project files
In django, what is the terminology for the two project files created with the same name? Chat gpt says it is Project Directory \ Project Configuration Files. Is this correct? tried googling, but nothing. Thank you in advance! -
Django combine 2 querysets without changing the original order
def get_queryset(self): normal_posts = Post.objects.filter(field1=‘value1’).order_by('another_field_1’) featured_posts = Post.objects.filter(field2=‘value2’).order_by(‘another_field_2') all_posts = (normal_posts | featured_posts) #does not preserve the order return all_posts I'm using DjangoFilterBackend and along with filterset_class for paginated query results. Hence not able to use below. normal_ads.union(featured_ads) #django.db.utils.NotSupportedError: Calling QuerySet.filter() after union() is not supported. I tried using from itertools import chain also, however its not much helpful as its returning a list and not query set. Please suggest.