Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Descriptive Financial Statement Approaches
Consider a financial system, where the customer demands a financial statement consisting of | opening_balance | amount_credited | amount_debited | closing_balance | remarks. Two approaches to doing this are: Store the above details (opening_balance, amount (+/-), closing_balance, remarks) during transaction entry Just record the amount(+/-), remarks and get my final statement from performing window queries in SQL (specifically LEAD() and LAG() functions) Challenge: Consider 5 entries 1, 2, 3, 4, 5. There are high chances that middle entries will change at any time. For example, if the transaction_amount of 2nd entry changes, then it will affect the closing_balance of 2nd entry, in return it will affect the opening balance & closing_balance of 3rd entry, and so on, sort of a chain. Which approach better suits the current scenario? PS. I'm using Django, but I don't really care about this, because my concern is the concept of implementation -
ORM Statement Performance Issues
bills = hydrogen.models.Bill.objects.filter(miniapp=django.db.models.OuterRef('pk'), is_paid=False).order_by('billing_cycle') When querying, the CPU reaches 90%, how to optimize -
Adding another are in django's send_email parameters
basically i'm sending an email through contact page, inputs are name, email, phone number, subject and message. so far i did this; def contact(request): if request.method == "POST": name = request.POST['Name'] email = request.POST['Email'] phone = request.POST['Phone'] subject = request.POST['Subject'] text = request.POST['Message'] the structure i want in mail is; "Sender's name:" + name + "<br>" + "Sender's phone:" + phone + "<br>" + "Sender's email:" + email + "<br>" + text since html tags are not allowed, i failed to manage it and need help at this point. any help is appreciated, thanks! PS: please don't downvote if i did something bad just edit it so i can i learn what i did wrong. -
What could be the cause when the API populates in Console but fails to populate in frontend?
I am new to react and have tried to following various tutorials however i am stuck at this point and just sure something silly is just the cause. I can't get the data to display in frontend. My API works fine on Postman and is Django Rest Framework- made. The data populates to console. Below is the code 1.Note.js 2. App published Notes 3. App.js 4. Note Model : import React from 'react' import { Box, Flex } from '@chakra-ui/core' import NoteDetail from './NoteDetail' export default function Note({note}) { return( <Flex align='center' justify='flex-end' direction='column' bg='teal' width='300px' height='300px' borderRadius='40px' margin='16px' padding='16px' > <Box as='button' size='144px' bg='white' color='teal' textAlign='center' isTruncated> {note.title} <Box as='span'> {note.display_name} </Box> <NoteDetail note={note} key={note.pk}/> </Box> </Flex> ) } import React, {useState, useEffect} from 'react' import { Flex } from '@chakra-ui/core' import axios from 'axios' import Error from './Error' import Loading from './Loading' import Note from './Note' export default function AllPublishedNotes() { const [data, setData] = useState([]) const [isError, setIsError] = useState(false) const [isLoading, setIsLoading] = useState(false) useEffect(() => { const allPublished = async() => { setIsError(false) setIsLoading(true) try { const result = await axios.get('http://localhost:8000/api/note/published_notes/') setData(result.data) console.log(result.data) }catch(error){ setIsLoading(false) setIsError(true) } } allPublished() }, []) const noData = !data … -
Have persistent connections to multiple databases django
I am working on an analytics webapp built using django and it uses multiple databases to show data to the user. Currently, I am facing performance issues and want to have persistent database connections instead of django's default behavior of establishing connection at each request. My questions are: How will the django maintain persistent connection to multiple databases? As I read in the document "Since each thread maintains its own connection, your database must support at least as many simultaneous connections as you have worker threads.", will a single thread maintain connections to each database or connections will be distributed among threads? I am using nginx+gunicorn to serve this django app and I am using only workers in gunicorn (no threads, no pseudo-threads), how will this setup handle persistent connections to multiple databases? Is this a good practice? If not, what is the ideal way of doing this? Thanks in advance! -
django.db.utils.DatabaseError using djongo to connect mongoDB
Everything was working fine up until i decided reset my migration ... when i try to make new migration it gives me django.db.utils.DatabaseError, Can't seems to figure out the problem. I'm using MongoDB as my database. Operations to perform: Apply all migrations: account, admin, articles, auth, authtoken, contenttypes, sessions, sites, socialaccount Running migrations: Not implemented alter command for SQL ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL Applying articles.0002_article_author...Traceback (most recent call last): File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 783, in __init__ self._query = self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 875, in parse raise e File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 856, in parse return handler(self, statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 888, in _alter query = AlterQuery(self.db, self.connection_properties, sm, self._params) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 425, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 84, in __init__ super().__init__(*args) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 435, in parse self._add(statement) File "/Users/username/opt/anaconda3/envs/restApi/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 598, in _add raise SQLDecodeError(err_key=tok.value, djongo.exceptions.SQLDecodeError: Keyword: int Sub SQL: ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL FAILED SQL: ('ALTER TABLE "articles_article" ADD COLUMN "author_id" int NOT NULL',) Params: ([],) Version: 1.3.3 The above exception was the direct cause of the following exception: Traceback (most recent … -
How to communicate between 2 Django separate projects?
I have two separate Django projects and want to locate them in 2 different servers. Is there a way to communicate with each other? In one projects I need to be able to upload a file and send it to second project for processing. -
upload a file in django rest framework to s3 in python
I am bit new to boto3 and django rest framework.I have a django rest framework project in some folder,and I need to upload the image from (other folder,say D drive/someFile.PNG) I am trying to access the location of it to send to a upload function of s3,But when add the location of image file to the fucntion it says it cannot find the image url,can anyone help me with this?!Thanks in advance. Here is the upload fuction of s3 for the reference def upload_file(file_name, bucket, object_name=None): """Upload a file to an S3 bucket :param file_name: File to upload :param bucket: Bucket to upload to :param object_name: S3 object name. If not specified then file_name is used :return: True if file was uploaded, else False """ # If S3 object_name was not specified, use file_name if object_name is None: object_name = file_name s3_client = boto3.client('s3') try: response = s3_client.upload_file(file_name, bucket, object_name) print('s3 response', response) key = file_name region = 'ap-south-1' url = f'https://{bucket}.s3.{region}.amazonaws.com/{key}' print('url test', url) except ClientError as e: logging.error(e) return False return True In the above file_name, if I pass the image name from other folder it is giving me the 500 internal server error saying that it cannot … -
How to run multiple django applications on IIS server?
I am new in django that runs on IIS server. I have manage to set up server that one django application/site is runnging..now I want to add another django application/site to this server. I cant find anywhere the sample web.config how to do that.. <?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <staticContent> <mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" /> <mimeMap fileExtension=".config" mimeType="application/xml" /> <mimeMap fileExtension=".pdb" mimeType="application/octet-stream" /> </staticContent> <handlers> <add name="Python FastCGI" path="/page1/*" verb="*" modules="FastCgiModule" scriptProcessor="c:\python27\python.exe|c:\python27\lib\site-packages\wfastcgi.pyc" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <add key="WSGI_HANDLER" value="page1.wsgi.application" /> <add key="PYTHONPATH" value="C:\inetpub\wwwroot\page1" /> <add key="DJANGO_SETTINGS_MODULE" value="page1.settings" /> </appSettings> </configuration>` This is my config so far, how can I add another django site that will be available on URL/page2/ ? -
Show value to HTML just like how value gets display in CMD prompt when executes print() in python
I am working on speech recognition by following this tutorial and implementing in Django. I'm wondering the way we execute print("Listening...") and print("Recognizing...") for user to understand when to speak in CMD prompt, is it possible to send value (Listening, Recognizing) in HTML page each time when user speaks something ? def takeCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source) audio = r.listen(source) print(audio) try: print("Recognizing...") query = r.recognize_google(audio, language ='en-in') print("User said:",query) except Exception as e: print(e) print("Unable to Recognizing your voice.") return "None" return query -
How do I add Manage.py ClearSessions to crontab to automatically clean up expired sessions?
How do I add Manage.py ClearSessions to crontab to automatically clean up expired sessions? django manage.py clearsessions -
Is a Django model with parents that have a parent and child relationship among them?
To elaborate, I wish to set up a model where a blog post can have a like and a comment on the post can also be liked. I could build two models, post_like and comment_like where they would both be children of blog post and comment respectively. Is there a way through which I could implement the above functionality with a single model? Something more generic. Where 1 model can be used to implement the like functionality? class Like(models.Model): post = models.ForeignKey(post..., default = None) comment = models. ForeignKey(comment...default = None) like_type = models.CharField(choices, default = None) -
How to access Django's single set item?
I ran the following code in python shell: from main.models import ToDoList ls = ToDoList.objects.all() ls output: <QuerySet [<ToDoList: First List>, <ToDoList: Second List>]> but when I use: ls = ToDoList.objects.get(id=1) it says: main.models.ToDoList.DoesNotExist: ToDoList matching query does not exist. -
Issuing long commands in container deployments k8s
I want to issue django management commands via kubernetes deployment.yaml in a container (like command: ["/bin/sh","-c"] args: ["command one; command two && command three"]) on startup for user object creation such as python manage.py createuser --last-name xyz --email ij@test.com .... Since the user object I want to create has a large number of properties (almost 20), the command may become very long. Is there a better way of achieving this? -
Best way to store cv2.imencode information from Django into a Postgresql database table
I am performing object detection on live/recorded video feed using PyTorch Yolo algorithm. The inference output cv2.imencode('.jpg', infered_image)[1].tobytes() from machine learning model is feed into the Django view using StreamingHttpResponse into an img tag. This all works fine. Code Snippets. **views.py** def gen(camera): while True: with torch.no_grad(): frame = camera.detect() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def video_feed(request): return StreamingHttpResponse(gen(VideoCamera(source=r"C:\Users\Downloads\aircraft.mp4")), content_type='multipart/x-mixed-replace; boundary=frame') Output from **detect.py** class VideoCamera(object): def __init__(self): ... def detect(self): ... ret, jpeg = cv2.imencode('.jpg', im0) return jpeg.tobytes() Now I want to store this inferred images data into a database table. What is the best approach to store such data? Use ImageField or BlobStorage or any better approach. I am ok to store ``cv2.imencode('.jpg', infered_image)[1]` or the entire bytes information to database. -
Do you know why pip list shows one installed version but then python shell shows another?
I have created a virtual environment. I activate it with conda activate my_venv. I do pip list and check statsmodels version. result -->0.12.1 I do pip freeze. The same result. I get inside of the python shell and execute the next code: import sys import statsmodels print(sys.prefix) print(statsmodels.__version__) the output: '/home/skootik/anaconda3/envs/prodenv' '0.10.2' Does anybody know why? Thank you in advance -
aggrigate on many to many fields
i want to create a report for sum of duration that a adviser advise on this month. my model : class Adviser(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='adviser') patients = models.ManyToManyField('patient.Patient', through='adviser.AdviserPatient', related_name='advisers') class AdviserPatient(models.AbstractBaseModel): adviser = models.ForeignKey('adviser.Adviser', on_delete=models.PROTECT, related_name='adviser_patient') patient = models.ForeignKey('patient.Patient', on_delete=models.PROTECT, related_name='adviser_patient') duration = models.SmallIntegerField() assign_date = models.DateField(auto_now_add=True) release_date = models.DateField(null=True, blank=True) class Patient(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='patient') my query : ended_advise_this_mouth = Adviser.objects.annotate( total=Case(When( adviser_patient__release_date__gte=start_of_month(), adviser_patient__release_date__lte=end_of_month(), then=Sum('adviser_patient__duration')), default=Value(0), output_field=IntegerField())) but with this query i get response like that : <QuerySet [<Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [2 vahid imanian]>]> as you see adviser 1 repeat 6 time with separate total . when i use method values('id') or use distinct() not effected in result . my db is mysql and cant use distinct('id'). please help me . is there any way to use django-rest-framework serializers for this queryset? -
Deleting newline by python (Django) by taking string by textarea in html but the answer is wrong. WHY?
print(newlineremove) print(djtext) if newlineremove == "on": analyzed="" print(djtext) for char in djtext: if char !="\n": analyzed=analyzed + char print(analyzed) suppose newlineremove is on and the input in textarea(html) is: dam dam djtext=request.GET.get('text','default') OUTPUT: on dam dam dam dam dam but it should have been: on dam dam dam dam damdam -
Use condition in update_or_create of django (DRF)
Here is my Serializer for API: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = [ 'name', ] def create(self, validated_data): from django.db.models import F, Case, When instance, created = self.Meta.model.objects.update_or_create( merchant=validated_data.pop('merchant'), client_id=validated_data.pop('client_id'), defaults={ 'name': Case( When(is_synchronizable=True, then='test'), default=F('name') ) } ) return instance I want to update the name just when is_synchronizable is True. But I get this error: django.core.exceptions.FieldError: Cannot resolve keyword 'test' into field. -
Django REST api Parent and child componet to use react js form submit as it is DRA?
guys i am beginner React js. i want get as it is rest API drop-down list box have to create in react. so how to do it ? could you guy please give way method -
How to create slug of many to many fields in django?
I want to make slugs on post save for my model using three fields one charfield and two ManytoMany Fields but getting error during saving. Here is my code: Heading ##class product(models.Model): id = models.AutoField(primary_key=True) image = models.ForeignKey(all_images, verbose_name='Product Images', on_delete=models.CASCADE, related_name='proimages') ProductName = models.CharField(max_length=200, null=False,default="None", blank=False,verbose_name="Product Name") CategoryName = models.ManyToManyField(category,related_name='procat', blank=False,verbose_name="Category Name") SubcatName = models.ManyToManyField(subcategory,related_name='prosubcat', blank=False,verbose_name="Sub-category Name") description = RichTextUploadingField(blank= False,verbose_name="Description") price = models.IntegerField(default=100, null=True, blank=True, verbose_name='Price') slug = models.SlugField(max_length=55, blank=True, null=True) def get_slug(self): slug = self.ProductName try: for items in self.SubcatName.all(): slug +=items.name try: for items in self.CategoryName.all(): slug +=items.CategoryName except: pass except: pass return slugify(slug) def save(self, *args, **kwargs): if not self.slug: self.slug = self.get_slug() super(product, self).save(*args, **kwargs) -
How can I see all possible attributes of an context variables in django templates
I am trying to use double model form at once in one single view, I am using django-betterforms to merge those, It merged all fields from two model in one single form. I know I can use different class and id to separate them, But I can't extract them in template form, like {{ form }} it will place full form in template, I can render all field like this {% for field in form %} {{ field }} or anything {% endfor %} My question is how can I know all the possible attributes of this field like {{ field.* }} *=anything kind of dir(field). This is a problem I have facing but what will be solution to find all attributes or separate two forms in two side. Basically I need to separate two model, those will save in same time with same view but in front-end those will be different. Thanks in advance!!! -
Post gis raw query returns empty set on st_asmvt
I am trying to generate dynamic mvt tiles using django. I used the sql query given in the documentation to generate the tiles. I changed the z,x,y as per my requirements. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon WHERE ST_Intersects(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; This gives empty result. But if i only run the following query it returns the results: SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon And if i try to run the following query it again returns the empty set. WITH mvtgeom AS ( SELECT ST_AsMVTGeom(feat_polygon.geom, ST_TileEnvelope(19, 369963, 215620)) AS geom, u_id FROM feat_polygon ) SELECT ST_AsMVT(mvtgeom.*) FROM mvtgeom; -
How to upload gist(CSV) file to Django app database?
Good day! I need to upload info from gist file(Myfile.CSV) to my Django app database? Can anybody give me suggestion how to do it more correctly? I have gist file which is located on github. It's a csv file wich containes 3 columns(number, name, colour) and several rows. So I need to upload(save) to existing Django project info from this file and after it change names of columns to different one. -
AttributeError: 'WindowsPath' object has no attribute 'endswith'
When I run my project this error comes. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\management\base.py", line 396, in check databases=databases, File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\checks.py", line 9, in check_finders finder_errors = finder.check() File "C:\Users\Mowgli\anaconda3\envs\surajDjangoEnv\lib\site-packages\django\contrib\staticfiles\finders.py", line 81, in check if prefix.endswith('/'): AttributeError: 'WindowsPath' object has no attribute 'endswith'