Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reverse a filter class in Python/Django?
I needed to filter models instances with custom function, and using Post.objects.filter(func) didnt help, I got a type error cause "object is not iterable, so I went with def filter_posts(x): if x.author in followed_author_list: return True else: return False posts = filter(filter_posts, Post.objects.all()) return render(request, 'main.html', {'posts':posts }) And it worked, but now I cant reverse the list, cause I want to order it so newest will be last. If I use list() on it, then posts stop appearing on my website at all, cause I assume its not a different type?.. Question is, how do I reverse filter class, or pull this off in general, so I get my posts filtered in reverse order? -
How do I exclude some File Types from FilerFileField (filer.fields.image)?
I'm working on Django-CMS project. For some models I need to let users upload only these types of files -> .svg, .png, .jpg, .webp (basically for images). The best solution, as I thought, was to use FilerImageField, but it doesn't allow me to upload .svg or .webp. So, what I need to do, is to exclude the possibility of uploading .pdf and other types of files to FilerImageField and allow only for .svg, .png, .jpg, .webp. Would appreciate any kind of help. from cms.models.pluginmodel import CMSPlugin from django.db import models from filer.fields.image import FilerFileField, FilerImageField class MainSection(CMSPlugin): image = FilerFileField(verbose_name="Section Image", related_name="section_image", null=True, blank=True, on_delete=models.CASCADE, help_text="Max file size: 500 kb. Recommended dimensions: 1100x650 px. Recommended file types: svg, png, jpg, webp") -
how to perform django queryset in more efficient way to get following response?
here is my model fields: staff = models.ForeignKey(StaffProfile, on_delete = models.SET_NULL, blank=True,null = True) created_at = models.DateTimeField(auto_now_add=True) category = models.CharField(max_length = 250,choices = EventStatusChoice.choices,default = EventStatusChoice.PROGRESS_NOTES) summary = models.CharField(max_length=200, blank=True, null=True) Event category choices are: class EventStatusChoice(models.TextChoices): INJURIES = 'injury','Injuries' FEEDBACKS = 'feedback','Feedbacks' ENQUIRIES = 'enquiry','Enquiries' INCIDENTS = 'incident','Incidents' PROGRESS_NOTES = 'note','Progress Notes' WARNING = "warning", "Warning" I want a response something like following: "data": [ { "staff": "admin", "injury": 0, "feedback": 2, "enquiry": 0, "incident": 1, "note": 0, "warning": 0 }, { "staff": "tutaketuw", "injury": 0, "feedback": 0, "enquiry": 0, "incident": 1, "note": 0, "warning": 0 },] I did it in my own way, and its working good. Following is my way: def get_staff_summary(self,start = None,end = None,search = None): qs = EventModel.objects.get_distinct_staff(search) data_list = [] for i in qs: data = {} data['staff'] = i['staff__staff__username'] for j in EventStatusChoice.choices: if start != None and end != None: data[f'{j[0]}'] = EventModel.objects.filter(category = j[0],staff__staff__username = i['staff__staff__username'],created_at__date__gte = start,created_at__date__lte = end).count() else: data[f'{j[0]}'] = EventModel.objects.filter(category = j[0],staff__staff__username = i['staff__staff__username']).count() data_list.append(data) return data_list Now, I want to do it in much more proper and efficient way. Can anybody please help to get above response(or any similar type of response) by using only … -
Detect changes in django-bootstrap-datepicker-plus with JQuery
I am using django-bootstrap-datepicker-plus package, and I am trying to display an alert when the date is changed. However, jquery does not seem to detect any changes to the date. Following this question Detect change to selected date with bootstrap-datepicker only works when I add the JQuery UI CDN to my code, which causes a problem as two datepickers appear. Is there a way to get JQuery to detect a change in django-bootstrap-datepicker without adding JQuery UI code? forms.py from django import forms from bootstrap_datepicker_plus.widgets import DatePickerInput class ExampleForm(forms.Form): DOB = forms.DateField(required=False, label="Date of Birth", input_formats=['%d/%m/%Y'], widget=DatePickerInput(format='%d/%m/%Y') ) Html <div class="col-12 col-md-6 mb-0 p-1"> {{ form.DOB|as_crispy_field }} </div> Rendered HTML -
PostgreSql not coming to database from Django project
I am using PostgreSql as database in my Django project. When I run it locally via pgAdmin, the data appears, but when I run it on the server, the data does not come in pgAdmin. Django settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'xxxx', 'USER' : 'xxx', 'PASSWORD': 'xxx', 'HOST': 'pgdb', 'PORT': 5432, } } docker-compose.yaml services: # CaddyServer reverse proxy caddy: restart: always image: caddy:2-alpine ports: - "443:443" command: caddy reverse-proxy --from https://xxxxxx.com --to http://0.0.0.0:8000 #volumes: # - /local/path/to/Caddyfile:/path/inside/continer/to/Caddyfile # networks: # - web # - bridge # Django web app django: restart: always build: . ports: - "80:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=xxxx - POSTGRES_USER=xxxx - POSTGRES_PASSWORD=xxxx volumes: - pg-data:/var/lib/postgresql/data/ volumes: pg-data: I am connecting via pgAdmin server ip. The pgAdmin connection is established, but the data I entered into the system is not visible on pgAdmin. -
Filter and get all the customers who had brought the authors other contents to send the notification when new content is added
I want to Filter and get all the customers who had brought the authors other contents to send the notification when new content is added This works on queryset I know but I'm Confused on how to do that. If anyone please share. Here are my models content: class Content(models.Model): title = models.CharField(max_length=1000) Author = models.ForeignKey('User',on_delete=models.CASCADE) slug = AutoSlugField(populate_from='title', unique=True, null=False) cover = models.ImageField(upload_to='course', default='nocover.jpg') catogary = models.ForeignKey(Category, on_delete=models.RESTRICT) description = models.TextField(max_length=2000, null=True, blank=True) requirements = models.TextField() price = models.FloatField() language = models.ForeignKey(Language, on_delete=models.RESTRICT) Puchased content class PurchasedContent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) course = models.ManyToManyField(Course, blank=True, related_name='course') I want all the list of Customers email who had brought a particular Authors course the Author will be authenticated while adding. We'll get the Author as request.user Here is sample ListCreateAPIView in django rest Framework class createlistcourseview(generics.ListCreateAPIView): permission_classes = [TokenHasReadWriteScope] queryset = Content.objects.all() serializer_class = ContentSerializer def perform_create(self, serializer): #Here I want to create a Function that sends mall serializer.save(author=self.request.user) -
How to pass variable from views to model in Django
Models.py from django.db import models class Voiceapi(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) voice_text = models.CharField(max_length=200,default="voice_data") Views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. from rest_framework import viewsets import requests import gdown from pydub import AudioSegment import speech_recognition as sr from .serializers import * from .models import * import time from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from urllib.request import urlopen # create a viewset class VoiceViewSet(viewsets.ModelViewSet): # define queryset queryset = Voiceapi.objects.all() # specify serializer to be used serializer_class = VoiceSerializer # print(Voiceapi.objects.values()) datas = Voiceapi.objects.values() print(datas) for i in datas: try: print("Audio File-->",i['name']) audio_url = i['name'] audio_id = i['id'] def VoiceRecognizer(audio,audio_id): r = sr.Recognizer() with sr.AudioFile(audio) as source: audio_text = r.listen(source) try: text = r.recognize_google(audio_text) print(text) Voiceapi.objects.filter(pk=audio_id).update(voice_text=text) except: print('Audio Not Clear') audio = "/home/venpep/voicetotext/messages/media/test.wav" VoiceRecognizer(audio,audio_id) except: print("Not audio file") I need to pass the variable "text" from my view.py to models.py to set the default in voice_text.Is there any solution to get the text from the view page. The text variable is a basic string that needs to pass to the models.py -
SQLAlchemy - AttributeError: 'str' object has no attribute 'body'
I need to save some data using SQLAlchemy. The Insert statement works fine when the sqlalchemy create_engine is initialize inside the file where the function lives from sqlalchemy import create_engine from sqlalchemy.sql import text engine = create_engine('sqlite:///db.sqlite3') // this will work @csrf_exempt def save(request): payload = json.loads(request.body.decode('utf-8'))['data'] payload = payload['body'] response = cu.call("externalapi/someendpoint", payload=json.dumps(payload), method="POST") id = response['id'] statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})""" with engine.connect as con: con.execute(statement) // this will not work from utils import create_consignment @csrf_exempt def save(request): payload = json.loads(request.body.decode('utf-8'))['data'] payload = payload['body'] response = cu.call("externalapi/someendpoint", payload=json.dumps(payload), method="POST") id = response['id'] statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})""" create_consignment(statement) //this will throw error `payload = json.loads(request.body.decode('utf-8'))['data'] AttributeError: 'str' object has no attribute 'body'` // If I remove the `create_consignment`, the error gone So the create_consignment method, is just lines of codes extracted to make it more reusable utils/create_consignment.py import sqlalchemy as db from sqlalchemy.sql import text engine = db.create_engine('sqlite:///db.sqlite3', connect_args={'check_same_thread': False}) def create_consignment(stmt): with engine.connect() as con: statement = text(stmt) con.execute(statement) Any Idea whats going on and how to prevent this error? -
Strip tags in django view page django admin
I have a user with view only permission in a model with richtextfield, but when viewing the data on this particular user with only view permission, the data is not formatted in html. I know, below is how to strip tags when you want to strip tags in list_display, def what_field(self, obj): return format_html(obj.what) please see attached image. -
Facing problem while trying to update a django-model
I have a requirement to update few fields of django-ORM-model ( legacy db being used is postgressql), i have tried different approaches but nothing is working please help tried approaches: 1) user = Model.objects.using('default').filter(id=ids) user.name="Gandalf" user.save() 2) user = Model.objects.using('default').filter(id=ids).update(name="Gandalf") -
DRF Filtering model by another model id
I have this models: class Organization(models.Model): name = models.CharField( "Organization name", max_length=100, unique=True ) description = models.TextField("Organization description") districts = models.ManyToManyField( "District", related_name="organizations", blank=True, ) class District(models.Model): name = models.CharField("District name", max_length=100, unique=True) And I need to filter organizations by district id, so url should be: organizations/<district_id>/ What is the better way to do it? Currently I have two solutions, first: urls.py router.register("organizations", OrganizationViewSet, basename="organizations") router.register( "organizations/(?P<district_id>\d+)", OrganizationViewSet, basename="organizations_by_district", ) views.py class OrganizationViewSet(viewsets.ModelViewSet): serializer_class = OrganizationSerializer def get_queryset(self): district = self.kwargs.get("district_id") if district: return Organization.objects.filter(districts__in=[district]) return Organization.objects.all() Second solution: urls.py urlpatterns = [ path(r"organizations/<int:district_id>/", get_orgs_by_district, name="org_by_district"), ... ] views.py @api_view(http_method_names=['GET']) def get_orgs_by_district(request, district_id): objs = Organization.objects.filter(districts__in=[district_id]) data = OrganizationSerializer(objs, many=True).data return Response(data, status=200) Both solutions work, but which is better? And maybe there is another solution that I don't know? -
Django tests - reset session or change session['session_key']
I need to test behavior when two different users access a particular URL (sequentially). User A visited URL User B visited URL for this I want to change an IP address of the self.client and also a session['session_key'] It looks like changing the session key is not so straightforward. I tried, for example: self.client.defaults['REMOTE_ADDR'] = '2.2.2.2' session = self.client.session session['session_key'] = 'abc' session.save() which did not help Do you know how to change it or reset the session? -
Filter False in a list of Booleans
I've five Product objects with 3 product's availability set to True and rest False, I'm trying to set Checkout Status Button to Out of Stock even if one product has availablity set to False. Because cart view cannot use slug, {% if product.availability %} is pointless, and can't use 'for loop' or it would create multiple checkout buttons, what's the way to fix this? Model class Product(models.Model): availablity = models.BooleanField() View def cart(request): products = Product.objects.all() Cart template {% for product in products %} <p>{product.name}</p> <p>{product.price}</p> {% endfor %} <!--Checkout Status Button--> {% if product.availability %} <a href="#">Checkout</a> {% else %} <p>Out of stock</p> {% endif %} -
Dynamic query builder django
I'm working on a project with django, and i would like to use MUI-QueryBuilder (based on react). I would like to have this output: http://tiagofernandez.com/mui-querybuilder/?path=/docs/muiquerybuilder--supported-types. The main objective for me is to make a dynamic query builder. Can someone help me ? Thanks. -
Why does my Django test don't wan't to connect me anymore?
I developped a Django app like 6 month ago and I wan't to use it again. But I ran test and all my tests that need me to log a user fails (while they were succesfull before). For example I have this : class TestViews(TestCase): def setUp(self): self.client = Client() # Setting up user self.user = UserExtension.objects.create(id=1, username="martin", email="martin@internet.net") self.user.set_password('secret') self.user.save() def test_account_detail_authenticated(self): self.client.login(username="martin", password="secret") response = self.client.get('/account/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context["username"], "martin") self.assertEqual(response.context["email"], "martin@internet.net") And it give me this error : AssertionError: 302 != 200 Why ? Because my site want to redirect me on login page, cause i can't access account page if not connected. So the problem is I can't login. For test database I use a local postgreSQL and for test I use pytest (it fail the same way if I use python manage.py test) -
Should I store images on a server or use a CDN?
Q: I'm making a website for a friend in django and I was wondering should I use a CDN (like AWS) to store images or should I just store them on the same server as the website itself? The website in question is a website for his parents' company and I doubt it would have more than a couple of tenths of visits per day. However, there would be quite a few pictures. Homepage would have 3-4 images, a portfolio page would have around 10-15 projects with a main picture and upon clicking on each project a new page would open which would have ~8 pictures of the project itself. Let's say that at any given time there would be about 100 pictures on the website. Since I don't have much experience with web-dev I'm not sure which approach is better or should I say, CDN is a better approach but I'm unsure if it's needed in this case. -
Access key value model in django for dynamic template
the goal is to make texts in static templates like "about us" page dynamic with a model so that it can be edited easily later on. My first approach was to create a static model in which I had to set a field for each data I intend to put on my templates, such as "main_page_intro" or "about_page_company_info" and so on. But a friend of mine suggested that this approach is static itself and is not right. He proposed that I create a model with only two fields, “key” and “value”. “key” to name where the text is supposed to used (e.g. main page introduction) and “value” to write the actual text which should be displayed. So now I have this model: models.py from django.db import models class SiteDataKeyValue(models.Model): key = models.CharField(max_length=200, verbose_name="Text place") value = models.TextField(verbose_name="Text") def __str__(self): return self.key Now I have problems continuing this route and using this model. Suppose that I created an object in this model, with a key = "main page introduction text" and a value of = "some text here". How am I supposed to write a view for this and how should I use these key and values in my template? P.S.: … -
How to select the half last elements in the result record set by using an attribute in django queryset?
I want to select the half last elements in the result record set by using an attribute somethingelse stored in MyModel. I tried without success with: MyModel.objects.filter(something="foobar")[:F("somethingelse") // 2)] -
How can i keep Django summit form and show a message to user?
I want to create a user when an article submit in Django admin form. I want to check a user is existed or not. After it, I want to show a message to user that user is existed, and he can change username to create. Article model fields: family username . . -
checklist not getting value django form
When I try to edit info on my table. Everything works perfectly except for the fact that my checklist does not get value. All other fields get value when the edit modal is loaded. Note that when I tried getting value on a separate page instead of a modal it still did not work. I have cut my code to make it more readable. If you want to see more please let me know. Here is my code. forms.py: class TraineeForm(forms.ModelForm): GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ('Other', 'Other') ] EDUCATION_CHOICES = [ ('P', 'Primary'), ('J', 'Junior'), ('S', 'Senior') ] TraineePic = forms.ImageField(label="Image :", required=False, widget=forms.ClearableFileInput()) Name = forms.CharField(widget=forms.TextInput(attrs={'class':'col-sm-4'}), label='Name :') Course = forms.ChoiceField(widget=forms.Select(attrs={'class':'col-sm-4'}),choices=course_choices, label='Course :') BatchNo = forms.CharField(widget=forms.NumberInput(attrs={'class':'col-sm-4', 'placeholder':'Numbers only'}), label='Batch No :') Gender = forms.ChoiceField(widget=forms.RadioSelect(attrs={'class': 'col-sm-4 form-check-inline', 'id':'id_Gender'}),label='Gender :', choices=GENDER_CHOICES) Education = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple(attrs={'class': 'col-sm-4 form-check-inline','id':'id_Education'}), label='Education :', choices=EDUCATION_CHOICES) class Meta(): model = Trainee fields = ("Name","Course","BatchNo","Gender","Education",) views.py: def updateTrainee(request, id): trainee = get_object_or_404(Trainee, pk=id) if request.method == "POST": form = TraineeForm(request.POST,request.FILES,instance=trainee) if form.is_valid(): form.save() return HttpResponse(status=204, headers={'HX-Trigger' : 'changeDetected'}) else: form = TraineeForm(instance=trainee) return render(request, 'MyTestApp/save.html', {'form':form}) save/edit.html: <form class="modal-content" enctype="multipart/form-data" hx-post="{{request.path}}" autocomplete="off" > {%csrf_token%} <div class="modal-header"> {% if trainee %} <h5 class="modal-title"> Edit a Trainee </h5> … -
django.db.utils.IntegrityError: UNIQUE constraint failed: When creating a new profile with post_save signal from django.contrib.auth.models.User
Is anything wrong with this code? from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: inst = Profile.objects.create( user=instance ) Any time I try adding a user the profile creation fails with the error below. This is true even if I clear the db django.db.utils.IntegrityError: UNIQUE constraint failed: Accounts_profile.user_id -
JSPdf not loading issue when trying to upload image
I have created a pdf format with JsPdf and I want to add an image in it. When I try to add the same pictures to any blank pdf, the pictures are added correctly, but when I load them into the pdf I am using, there is a problem with the pictures loading. I am attaching the images like this: var logo = document.getElementById("logo").src; console.log(logo); doc.addImage(logo, "PNG", 5, 2, 20, 10); pdf size before adding image: 187 KB after adding : 3.171 KB How can I add these images here? -
I want to upload a xml file into a PostgreSQL using Django
I am new to Django and my current task is to upload a xml file with 16 fields and more than 60000 rows to a database in PostgreSQL. I used Django to connect to the Database and was able to create a table in the database. I also used XML Etree to parse the xml file. I am having trouble storing the data in the table that I created in the sql database. This is the code that I used to parse: import xml.etree.ElementTree as ET def saveXML2db(): my_file = "C:/Users/Adithyas/myproject/scripts/supplier_lookup.xml" tree = ET.parse(my_file) root = tree.getroot() cols = ["organization", "code", "name"] rows = [] for i in root: organization = i.find("organization").text code = i.find("code").text name = i.find("name").text x = rows.append([organization, code, name]) data = """INSERT INTO records(organization,code,name) VALUES(%s,%s,%s)""" x.save() saveXML2db() the code runs without any error, but I am unable to store the data into the table in the SQL database. Please help -
django collectstatic without db connection?
while I am running python manage.py collectstatic --no-input I am getting a DB connection issue. i want to collect statics without a DB connection to dockerize my Django app. with DB connection it's working fine. -
How do I apply a Bootstrap style to all form fields using widgets in Django?
I have a lengthy form so I am rendering it using fields = "__all__" in the class Meta. I was wondering if there is a way to apply a style to all fields without having to express them all individually in widgets? The style I am looking to apply to all fields is attrs={'class': 'form-control'} which is a bootstrap style. forms.py: class CompanyDirectApplication(forms.ModelForm): class Meta: model = Direct fields = "__all__" widgets = { 'completed': forms.HiddenInput(), 'important_persons': Textarea(attrs={'class': 'form-control'}), } labels = { "important_persons": "Please list all Directors, Partners, Associates and Company Secretary:", "trading_name": "Trading Name (if different)", # Many more labels follow this }