Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Format data queryset result to use in form.ModelChoiceField queryset option
I have a project in Django, where i have data in a postgres database. I want to create a form with a ModelChoiceField where i can select the data obteined in a previous queryset. When I make the queryset to get data from database: list_result_queryset = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct() I get this result: <QuerySet [('PEDRO',), ('JUAN',), ('ANDRES',), ('PABLO',), ('SOFIA',)]> And when I show the results into de template, they are showed but with "dirty" format like parentesis, coma, etc. Please, How i can show in the form.ModelChoiceField query option only the names PEDRO, JUAN, PABLo, etc and not ('PEDRO',), ('JUAN',), etc.? This is my form.py code from django import forms from .models import BdimMaestraDatos, lista_queryset_nombres_activos = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct() print('Resultado Queryset values list: %s' %lista_queryset_nombres_activos) class MaestraDatosForm(forms.Form): Seleccionar_Nombre = forms.ModelChoiceField(label="Nombre", queryset=lista_queryset_nombres_activos) Thanks -
DRF hisotry of all changes
How to make it possible to save the history of user actions in drf? I need a table in the database that will store: user, entity (on which changes were made), state before changes, state after changes That is, I just need to track their changes associated with the database I thought it must be some kind of middleware, but I couldn't write it -
Automatic button pressing without confirmation Django + JS
tell me, please, there is a button, you select a number and click "send", the number is saved, how to do it so that you just click on the number and it is automatically saved template <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="submit" value="Send"> </form> let me know if you need more code to help me. -
Django - How to create a form to add a product and a variation to the cart?
I'm developing an e-commerce app to hone my django skills and I've reach the part where its time to add product with variations to the cart. What would be the best approach for this? My models structure is as follows: from django.db import models from ckeditor.fields import RichTextField from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey # Create your models here. class Brand(models.Model): title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) brand_logo = models.ImageField(upload_to='media/PRODUCTS/BRANDS/LOGOS/') def get_absolute_url(self): return reverse('catalog:brand', args=[self.slug]) def __str__(self): return self.title class Category(MPTTModel): title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class MPTTMeta: order_insertion_by = ['title'] def __str__(self): return self.title def get_absolute_url(self): return reverse('catalog:category', args=[self.slug]) class Keywords(models.Model): product = models.CharField(max_length=300) def __str__(self): return self.product class MetaKeywords(models.Model): product = models.CharField(max_length=300) Keywords = models.ManyToManyField(Keywords) def __str__(self): return self.product class ProductMetas(models.Model): product = models.CharField(max_length=300) meta_title = models.CharField(max_length=300) meta_description = RichTextField(max_length=300) meta_keywords = models.ForeignKey(MetaKeywords, related_name='meta_keywords', on_delete=models.CASCADE) def __str__(self): return self.product class ProductImages(models.Model): product_image = models.ImageField(upload_to='media/PRODUCTS/FEATURED_IMAGES/') def __str__(self): return str(self.product_image) class ProductImageGallery(models.Model): product = models.CharField(max_length=300) images = models.ManyToManyField(ProductImages) def __str__(self): return self.product class ProductAttribute(models.Model): attribute = models.CharField(max_length=300) def __str__(self): return self.attribute class ProductAttributesSet(models.Model): product = models.CharField(max_length=300) attributes = models.ManyToManyField(ProductAttribute) def __str__(self): return self.product class ProductDetail(models.Model): detail = models.CharField(max_length=300) def … -
Django queryset icontains filter but "vise versa"
I have a Model: class Sources(models.Model): ... vendor = models.CharField(max_value=128, blank=True, null=True) ... And for example some data: select id, vendor from "webgui_sources"; id | vendor ----+----------------- 6 | oracle 5 | microsoft Then I have a string like "oracle;microsoft;apache" and I need to check are there models where vendor value is included to this string. So basically I need to collect all vendors which vendor value is included to "oracle;microsoft;apache". Whereas Sources.objects.filter(vendor__icontains='oracle;microsoft;apache') produces the following SQL-query: SELECT * FROM "webgui_sources" WHERE UPPER("webgui_sources".vendor) LIKE UPPER('oracle;microsoft;apache') I need to swap the fields and get something like this: SELECT * FROM "webgui_sources" WHERE UPPER('oracle;microsoft;apache') LIKE UPPER("webgui_sources".vendor) I tried to use extra and it did the job, but since using extra is not advised I tried to create custom lookup: class IContainsReverse(PatternLookup): lookup_name = "icontains_reverse" def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) params.extend([self.rhs]) return "%s ~* {}".format(lhs_sql), params Field.register_lookup(IContainsReverse) This lookup allows me to produce a query like this: Sources.objects.filter(vendor__icontains_reverse='oracle;microsoft;apache') select * from "webgui_sources" where 'oracle;microsoft;apache' ~* "webgui_sources".vendor; More or less it works but it looks clunky and works only with PostgreSQL. I hope that there is a more Django-way solution to do that, could somebody advice any more Django-way alternatives? … -
Django Serializer with multiple database
I have a Django application. I have two databases in the backend, One is PostgreSQL and one is Redshift. I am using serializer concept in DB operation. I need to process each DB in different scenarios. But when I check the insertion in Django, getting below error, '{'care_gap_fact_id': [ErrorDetail(string='This field is required.', code='required')]}' But this field is a primary key and auto increment. below are the other details, data = { #"care_gap_fact_id": 7, "start_date_id": 10, } seriali = CaregapfactSerializer(data=data) if seriali.is_valid(raise_exception=True): try : instance = seriali.save(using='postgres') except Exception as ex: print(ex) 'postgres' is one of my databases. I tried the below method as well, database_name = 'your_database_name' database_connection = connections[database_name] # Create the serializer and save the object using the specific database connection serializer = YourSerializer(data=request.data) if serializer.is_valid(): obj = serializer.save(using=database_connection) # Process further if needed else: # Handle serializer validation errors But this is also not working. Below is my model class, class CareGapFact(models.Model): care_gap_fact_id = models.IntegerField(primary_key=True) start_date_id=models.IntegerField(null=True, blank=True) Below is my serializer class, class CaregapfactSerializer(serializers.ModelSerializer): class Meta: model = CareGapFact fields = ["care_gap_fact_id","start_date_id"] If I have removed "care_gap_fact_id" from serializer fields, I am getting the error below, Got a `TypeError` when calling `CareGapFact.objects.create()`. This may be because you … -
Send Mail using django with html template
I trying to send mail with HTML template using django. Mail send properly but can't get html tempalte **This is my View.py file ** def Mail_Send(request): name = "Shyam" mydist = { 'name': name } html_template = 'mail_template.html' render_html = get_template(html_template).render(mydist) email = EmailMessage('Welcome', render_html, settings.EMAIL_HOST_USER, ['itsupport@synergyhospital.co.in'], ) email.content_subtype='html' email.send(fail_silently=False) tesddting = { 'mailsend':'mailsend' } return render(request,"index.html",tesddting) This is my Html File <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>Hello This is testing</h2> <p>Hi {{name}}</p> </body> </html> **the html file is in template folder** -
Django - Abstract Models cannot be instantiated
I created two models MailGroup and Recipient (shown below). I set Recipient's abstract property to true. When I try to list the MailGroup objects using the mailGroups = MailGroup.objects.all(), I'm getting the following error TypeError: Abstract models cannot be instantiated. This is my models.py file: from djongo import models class Recipient(models.Model): recipientName = models.CharField(max_length=255, null = False) recipientMailId = models.EmailField(max_length = 255, unique = True, null = False) class Meta: abstract = True class MailGroup(models.Model): mailGroupName = models.CharField(max_length = 255, unique = True, null = False) recipients = models.ArrayField( model_container = Recipient ) class Meta: abstract = False serializers.py from rest_framework import serializers from dashboardServer.models import MailGroup class MailGroupSerializer(serializers.ModelSerializer): class Meta: model = MailGroup fields = ["id", "mailGroupName", "recipients"] views.py @api_view(["GET", "POST", "PATCH", "DELETE"]) def mailGroupsView(request): if request.method == "GET": mailGroups = MailGroup.objects.all() #throws the error which I mentioned above serializer = MailGroupSerializer(mailGroups, many = True) return JsonResponse({ "status": "success", "info": "Mail groups fetched successfully", "title": "Success", "data": serializer.data }, status = 200) I'm currently using django version 4.1.9, sqlparse 0.2.4 and djongo 1.3.6 -
How to overide the CSS of Django UserCreationForm and AuthenticationForm without losing in built functionality?
I'm using the AuthenticationForm class to log users in, and the UserCreationForm to allow users to create accounts. Everything worked when I was just rendering the default form (using {{ form.as_p }} in my HTML files. However, I wanted to make the forms look nicer so I've over ridden the forms as so: class LoginForm(AuthenticationForm): username = forms.CharField(required=True, widget=TextInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "username", "placeholder": "Username"})) password = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password", "placeholder": "Password"})) class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, widget=EmailInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "email", "placeholder": "Email"})) password1 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password1", "placeholder": "Password"})) password2 = forms.CharField(widget=PasswordInput(attrs={ 'class': "block border border-grey-light w-full p-3 rounded mb-4", "name": "password2", "placeholder": "Confirm password"})) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] widgets = { 'username': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "username", "placeholder": "Username"}), 'first_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "first_name", "placeholder": "First Name"}), 'last_name': TextInput(attrs={'class': "block border border-grey-light w-full p-3 rounded mb-4", "type": "text", "name": "last_name", "placeholder": "Last Name"}), } However, … -
Use one docker container's URL into another container settings file
I have a docker compose file in which I am running two services: one is for django and another one is for keycloak. However, I want to access the keycloak through URL inside django settings file which I am trying to do by getting the IPAdress of the keycloak (docker inspect keycloak | grep IPAdress) container, but this does not work. Also I tried with http://localhost:8080/ (8080 is keycloak port) which also didn't work as well. Any suggestions or idea will be appreciated. -
ctrl+c in VSCode
I am working on a Django project at the moment and usually to stop the local server from running I press ctrl+c. However, a few days ago this stopped working. I think an extension or a VSCode update has caused this. Does anyone know how I can reset this keyboard shortcut in VSCode? -
Can´t Produce to topic in Kafka using docker and python
So I'm facing an odd situation where I can connect to my kafka broker but can´t produce to the topic I created. I have three images running on same network: zookeeper,kafka and my app. I have a simple producer in my app that goes like this: import json from kafka import KafkaProducer from loguru import logger producer = KafkaProducer( bootstrap_servers=["kafka:9092"], api_version=(0, 10, 21), ) def on_send_error(excp): logger.error(f"I am an errback {excp}", exc_info=excp) # handle exception def on_send_success(record_metadata): print(record_metadata.topic) print(record_metadata.partition) print(record_metadata.offset) def produce_to_kafka(): print(producer.bootstrap_connected()) data = json.dumps({"message": f"Produzindo para o Kafka mensagem 1"}) producer.send("test_producer", value=data.encode()).add_callback( on_send_success ).add_errback(on_send_error) producer.flush() When I try to run this code segment inside my app it prints True in the bootstrap_connected function but then gives me the following error when calling send(): ERROR | apps.my_app.producer:on_send_error:12 I am an errback KafkaTimeoutError: Batch for TopicPartition(topic='test_producer', partition=0) containing 1 record(s) expired: 30 seconds have passed since batch creation plus linger time My compose setup is the following: services: myapp: image: <my_app:latest> build: context: .. dockerfile: docker/Dockerfile args: DEPLOYMENT_MODE: develop stop_signal: SIGINT environment: ports: - "8000:8000" zookeeper: image: wurstmeister/zookeeper:3.4.6 ports: - "2181:2181" kafka: image: wurstmeister/kafka ports: - "9092:9092" expose: - "9093" environment: KAFKA_ADVERTISED_LISTENERS: INSIDE://kafka:9093,OUTSIDE://localhost:9092 KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INSIDE:PLAINTEXT,OUTSIDE:PLAINTEXT KAFKA_LISTENERS: INSIDE://0.0.0.0:9093,OUTSIDE://0.0.0.0:9092 KAFKA_INTER_BROKER_LISTENER_NAME: INSIDE KAFKA_ZOOKEEPER_CONNECT: … -
ImportError: cannot import name 'contact_view' from 'SCcontact' (app) in Django
I am new to Django. I'm trying to create a web contact form in Django that confirms by email the receipt of the enquiry to the enquirer and notifies the site owner of the enquiry details. When I do this I am getting the following error message File "C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\myproject\urls.py", line 19, in from SCcontact import contact_view ImportError: cannot import name 'contact_view' from 'SCcontact' (C:\Users\mikec\OneDrive\Documents\Conted\Web Applications with Python JavaScript and SQL\Sophie Canniffe Costume Design\myproject\SCcontact_init_.py) I have a views.py form in my app (SCcontacts) as follows: from django.shortcuts import render from django.core.mail import send_mail from django.http import HttpResponseRedirect from django.urls import reverse def contact_view(request): if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') message = request.POST.get('message') # Send email to the user user_subject = "Thank you for your enquiry" user_message = f"Dear {name},\n\nThank you for contacting us. I have received your message and will get back to you soon.\n\nBest regards,\nSophie" send_mail(user_subject, user_message, 'noreply@sophiecanniffecostumes.co.uk', [email]) # Send email to yourself admin_subject = "New Sophie Canniffe Costumes website enquiry" admin_message = f"You have received a new contact enquiry from:\n\nName: {name}\nEmail: {email}\nMessage: {message}" send_mail(admin_subject, admin_message, 'noreply@ophiecanniffecostumes.co.uk', ['sophie_canniffe@yahoo.co.uk']) return HttpResponseRedirect(reverse('contact')) return render(request, 'contact.html') and the urls.py … -
Django import ignores sys.path
A unit test module stored in /tmp is imported in my Django project. The unit test module begins like this: import tempfile import sys sys.path.insert(0, tempfile.gettempdir()) # /tmp is first in sys.path from name_like_app import foo # foo is the function to test # name_like_app.py is in /tmp # The import looks in the app instead of /tmp! The module containing foo is stored in /tmp, but happens to be named like one of the apps in my Django project. For some reason, Django looks in the app and ignores sys.path. Why does this happen? -
Django-Admin with models from external database not saving or filtering
I have a problem with a simple Django project i'm creating. What I aim with this project is administrating a database i already have with the tooling Django Admin offers. I proceed to explain what I already did and doesn't work as expected. This is my external model, generated with the inspectdb command: class Paises(models.Model): id_country = models.IntegerField(db_column='ID_COUNTRY', primary_key=True) country_name = models.TextField(db_column='COUNTRY_NAME', blank=True, null=True) country_phone_code = models.IntegerField(db_column='COUNTRY_PHONE_CODE', blank=True, null=True) class Meta: managed = False db_table = 'PAISES' verbose_name_plural = "Paises" def __str__(self): return self.country_name Then this is the admin class to register the model (as suggested at the documentation): class PaisesAdminModel(admin.ModelAdmin): using = "external" list_display = ['id_country', 'country_name', 'country_phone_code'] search_fields = ("country_name",) list_display_links = ('id_country', 'country_name') def save_model(self, request, obj, form, change): obj.save(using=self.using) def delete_model(self, request, obj): obj.delete(using=self.using) def get_queryset(self, request): return super().get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): return super().formfield_for_foreignkey( db_field, request, using=self.using, **kwargs ) def formfield_for_manytomany(self, db_field, request, **kwargs): return super().formfield_for_manytomany( db_field, request, using=self.using, **kwargs ) admin.site.register(Paises, PaisesAdminModel) I then ran python manage.py makemigrations and python manage.py migrate, everything seems to be OK, but then I find the following behavior: The model is listed correctly, all the columns and information are okay, i can even see the name of … -
Django RelatedObjectDoesNotExist User has no faculty. python (im getting this error i have also posted the screenshot of error) below code
`HI im new to python i got a project from github when i run it it says RelatedObjectDoesNotExist GitHub link = https://github.com/venugopalkadamba/Face_Verification_based_Attendance_system @login_required(login_url = 'login') def takeAttendence(request): if request.method == 'POST': details = { 'branch':request.POST['branch'], 'year': request.POST['year'], 'section':request.POST['section'], 'period':request.POST['period'], 'faculty':request.user.faculty } if Attendence.objects.filter(date = str(date.today()),branch = details['branch'], year = details['year'], section = details['section'],period = details['period']).count() != 0 : messages.error(request, "Attendence already recorded.") return redirect('home') else: students = Student.objects.filter(branch = details['branch'], year = details['year'], section = details['section']) names = Recognizer(details) for student in students: if str(student.registration_id) in names: attendence = Attendence(Faculty_Name = request.user.faculty, Student_ID = str(student.registration_id), period = details['period'], branch = details['branch'], year = details['year'], section = details['section'], status = 'Present') attendence.save() else: attendence = Attendence(Faculty_Name = request.user.faculty, Student_ID = str(student.registration_id), period = details['period'], branch = details['branch'], year = details['year'], section = details['section']) attendence.save() attendences = Attendence.objects.filter(date = str(date.today()),branch = details['branch'], year = details['year'], section = details['section'],period = details['period']) context = {"attendences":attendences, "ta":True} messages.success(request, "Attendence taking Success") return render(request, 'attendence_sys/attendence.html', context) context = {} return render(request, 'attendence_sys/home.html', context) def searchAttendence(request): attendences = Attendence.objects.all() myFilter = AttendenceFilter(request.GET, queryset=attendences) attendences = myFilter.qs context = {'myFilter':myFilter, 'attendences': attendences, 'ta':False} return render(request, 'attendence_sys/attendence.html', context) def facultyProfile(request): faculty = request.user.faculty form = FacultyForm(instance = faculty) context … -
Django Rest Framework - Custom serializer field does not appear in attrs dict when using "create" method
I created a ModelSerializer and want to add a custom field which does not belong to my model but is shown as part of serialized data when retrieving it and behave as writeable field when create method is called. I have a problem with validate method used on data passed in POST method. The field that does not belong to my model does not appear in attr dict when passed to validate method. The field I want is teams and when model instance already exists, I want this field to use method to retrieve result data (this works fine) and when the create method is called I want it to be a writeable field. Is this possible in any way? class MatchDaySerializer(serializers.ModelSerializer): #Validate if teams field exists in POST data to avoid creating Matchdays with no Players def validate(self, ): if not "teams" in attrs: raise serializers.ValidationError({"teams": "This field is required"}) return attrs #Serializer Fields matches = serializers.SerializerMethodField() teams = serializers.SerializerMethodField() class Meta: model = MatchDay fields = [ 'id', 'date', 'matches', 'teams', ] #Returns match counter def get_matches(self, obj): if not hasattr(obj, 'id'): return None if not isinstance(obj, MatchDay): return None return obj.match_counter #Return teams with list of players … -
How can I create in Django an custom absolute url for a predefined class
I need to make a blog in Django and I have a blog class declared as follows: models.py class Blog(models.Model): name = models.CharField(max_length=200, help_text='Enter name') author = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) The User class is a predefined Django class. As you can see for Blogger I don't create a class but I use a default one from Django class User. In the template blog-list.html I use the following line to display the blog author with a link to the author page: <a href="/blog/blogger/{{ blog.author.id }}">{{blog.author.first_name}} {{blog.author.last_name}}</a> wiews.py class BlogListView(generic.ListView): model = Blog ordering = ['-date'] paginate_by = 5 class BloggerDetailView(generic.DetailView): model = User urls.py urlpatterns = [ path('', views.index, name='index'), path('blog/<int:pk>', views.BlogDetailView.as_view(), name='blog-detail'), path('blogs/', views.BlogListView.as_view(), name='blogs'), path('blogger/<int:pk>', views.BloggerDetailView.as_view(), name='blogger-detail'), ] My question is how can I declare a get_absolute_url for blog.author to NOT use the manual constructed /blog/blogger/{{ blog.author.id }}? -
Django - "Not found" in log
I've got django app and some problem I can't understand/resolve. So, in my application, there is a view called: MyNotifyURL URLs.py file is ok. The view is called from outside, by payment integration api. When the payment is processed, the view is called, and it does its logic, and everything works fine. But, ... about 10 times per day (random hours), in my log files I can find: 2023-06-30 04:18:47 [WARNING ] (/home/myuser/myDevEnv/lib/python3.9/site-packages/django/utils/log.py:log.log_response 241) Not Found: /djangoapp/MyNotifyURL/ Is there any idea why is it so, or how to track the problem? -
PythonAnywere to connect postgres
**how to use postgres remotely in my pythonanywhere I need to make this kind of connection to postgres database in Anywhere but it is not supported ** ''' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'fontenariaguivala', 'USER': 'postgres', 'PASSWORD': '**********', 'HOST': 'mayhoste.com', 'PORT': '5432', } } ''' -
How'd I create filter feature that works with multiple model on Django?
So I have 2 models : from django.db import models class Profil(models.Model): nik = models.IntegerField() nama = models.CharField(max_length=40) tgl = models.DateField() kelamin = models.CharField(max_length=10) namaibu = models.CharField(max_length=40) nikibu = models.IntegerField() dusun = models.CharField(max_length=30, default='Sumberejo') def __str__(self): return f"{self.nik}, {self.nama}, {self.namaibu}" class Posyandu(models.Model): bulan = models.CharField(max_length=20, default='Januari') nik = models.ForeignKey(Profil, on_delete=models.CASCADE) tb = models.IntegerField() bb = models.IntegerField() ll = models.IntegerField() lk = models.IntegerField() ket = models.CharField(max_length=20,) def __str__(self): return f"{self.nik.nama}, {self.bulan}, {self.tb}, {self.bb}" and display them as a table with this html <table> <thead> <tr> <th>NIK</th> <th>Nama</th> <th>Tanggal Lahir</th> <th>Kelamin</th> <th>Nama Ibu</th> <th>Bulan</th> <th>TB</th> <th>BB</th> <th>LL</th> <th>LK</th> <th>Keterangan</th> </tr> </thead> <tbody> {% for profil in profils %} {% for posyandu in profil.posyandu_set.all %} <tr> <td>{{ profil.nik }}</td> <td>{{ profil.nama }}</td> <td>{{ profil.tgl }}</td> <td>{{ profil.kelamin }}</td> <td>{{ profil.namaibu }}</td> <td>{{ posyandu.bulan }}</td> <td>{{ posyandu.tb }}</td> <td>{{ posyandu.bb }}</td> <td>{{ posyandu.ll }}</td> <td>{{ posyandu.lk }}</td> <td>{{ posyandu.ket }}</td> </tr> {% endfor %} {% empty %} <tr> <td colspan="11">No data available</td> </tr> {% endfor %} </tbody> </table> aside from that I try to build a filter feature that able to filter what's displayed on the table based on months field (bulan field on Posyandu) with this views.py this views.py def riwayat(response): profils = … -
Count .docx pages Python Django
I have an application in DJango. I want to create a tool that will tell you the number of pages each file has. With PDF, excel and PPT files it works fine, but with ".docx" files it doesn't count exactly. I want you to tell me exactly how many pages that file has. I don't know, maybe by commands or by converting it to PDF but I want to have the exact number of pages. I have tried to do it by segments but it does not tell me exactly. This is my function: def count_pages(file_content, filename): file_extension = os.path.splitext(filename)[1] if filename else "" if file_extension.lower() == ".pdf": pdf_reader = PyPDF2.PdfReader(file_content) num_pages = len(pdf_reader.pages) file_type = "PDF" elif file_extension.lower() == ".docx": elif file_extension.lower() == ".pptx": prs = Presentation(file_content) num_pages = len(prs.slides) file_type = "PowerPoint" elif file_extension.lower() == ".xlsx" or file_extension.lower() == ".xlsm": wb = load_workbook(file_content) num_pages = len(wb.sheetnames) file_type = "Excel" else: num_pages = 0 file_type = "Unknown" return num_pages, file_type -
Python: ValueError: source code string cannot contain null bytes
I tried to start server and caught this: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\Admin\PycharmProjects\web-bd-project\venv\Lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Admin\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 936, in exec_module File "<frozen importlib._bootstrap_external>", line 1074, in get_code File "<frozen importlib._bootstrap_external>", line 1004, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed ValueError: source code string cannot contain null bytes Just started learn django and hard to my with error like this, because i can't understand anything from text like this ** … -
Seeking for Faster PDF/A Verification Tool in Django
I am currently working on a Django project that involves PDF file uploading and checking whether the uploaded file is PDF/A compliant. To accomplish this, I have been using an external module, VeraPDF. However, the verification process with VeraPDF takes around 3 seconds, which I find to be quite long. Therefore, I'm reaching out to the community for suggestions on any other free external modules or libraries that could potentially speed up this PDF/A verification process in a Django environment. Any advice would be greatly appreciated. Thank you in advance. Asynchronous Batch Processing for PDF/A Verification in Django -
how to create a modified table in python to download from django site
I have a django website with a database. On the site, you can add, change, delete information from the database. I made a button that, when clicked, downloads a .csv file. I open it in excel and it looks something like this: The data set does not matter, I have a different one, I took this one on the Internet for an example. I want that when I click on the "download report" button, I would create a table at least like in this example: Is it possible? At the moment, my views.py contains the following code to get data from the database and download it to an excel spreadsheet: def export_racks_view(request, id): response = HttpResponse(content_type='text/csv') response.write(u'\ufeff'.encode('utf8')) writer = csv.writer(response, delimiter=';', dialect='excel') writer.writerow([ 'Rack number', 'Name', 'Amount', 'Vendor', 'Model', 'Describe', 'numbering', 'responsible', 'financially responsible person', 'inventory number', 'row', 'place', 'height', 'width', 'depth', 'unit width', 'unit depth', 'rack type', 'place type', 'max load', 'power sockets', 'power sockets UPS', 'external ups', 'cooler', 'updated by', 'updated at', 'room name', 'building name', 'site name', 'department name', 'region name', ]) raw_report = Rack.objects.raw("""select rack.id as id, rack.rack_name, rack.rack_amount, rack.rack_vendor, rack.rack_model, rack.rack_description, rack.numbering_from_bottom_to_top, rack.responsible, rack.rack_financially_responsible_person, rack.rack_inventory_number, rack.row, rack.place, rack.rack_height, rack.rack_width, rack.rack_depth, rack.rack_unit_width, rack.rack_unit_depth, rack.rack_type, rack.rack_place_type, rack.max_load, …