Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-compressor UncompressableFileError
I have started to implement django-compressor to see how it would apply to the project I'm developing. So far, I have been testing it only locally in dev mode and it would be later ported to heroku. For now, I keep getting the following error and related solutions found online so far di not solve it. UncompressableFileError at / 'static/main_site/js/footer/some_js.js' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed here are my specific settings.py #... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJ_STATIC_DIR = os.path.join(BASE_DIR,"main_site","static") #... INSTALLED_APPS = [ #..., 'compressor', ] #... # heroku whitenoise forever-cacheable files and compression support STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', # django-compressor ] STATIC_URL = '/static/' MEDIA_URL = '/users/' LOGIN_URL = '/login/' # COMPRESS_ROOT = STATIC_ROOT COMPRESS_STORAGE = STATICFILES_STORAGE COMPRESS_URL = STATIC_URL COMPRESS_ENABLED = True # not DEBUG # django-compressor COMPRESS_FILTERS = {'css': ['compressor.filters.css_default.CssAbsoluteFilter'], 'js': ['compressor.filters.jsmin.JSMinFilter'] } The I have nested templates as following index.html: {% extends 'main_site/base.html' %} {% block head %} {% block meta %} {% include 'main_site/meta.html' %} {% include 'main_site/favicon.html' %} <meta name="description" content="{{ index.description }}" /> <title>{{ index.title }}</title> {% endblock %} {% block ressources_head_css %} {% for stylesheet in style_list %} <link href="{{ stylesheet }}" rel="stylesheet"> {% … -
Django - Bullet points removal when printing errors
When printing errors in html page, errors displayed with bullet points. I read in some articles to use style="list-style:none but i do not know how to successfully implement it in my case. Please help. html template <!-- LogIn --> <section class="our-log bgc-fa"> <div class="container"> <div class="row"> <div class="col-sm-12 col-lg-6 offset-lg-3"> <div class="login_form inner_page"> <form action="{% url 'login' %}" form method="POST"> {% csrf_token %} <div class="heading"> <h3 class="text-center">Login to your account</h3> <p class="text-center">Don't have an account? <a class="text-thm" href="{% url 'register' %}">Sign Up!</a></p> </div> {% if messages %} <div class="alert alert-success"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </div> {% endif %} <div class="form-group"> <input type="username" class="form-control" id="exampleInputEmail3" placeholder="Username" name="username"> </div> <div class="form-group"> <input type="password" class="form-control" id="exampleInputPassword4" placeholder="Password" name="password"> </div> Please be so kind to help me. Thank you -
Best way to send image ,Django API
I'm working on a project using Angular and Django for the API, my current task is to make an endpoint for uploading images ,therefore i did some researches and i found two ways to do it like the following : 1- send the image as a file data in the request data = request.data["image"] ext = data.name.split('.')[-1] # to get the extension data = request.data["image"].read() cardpath = "/static/msgimg/" + str(uuid4()) + "." + ext if len(data) > 0: path = default_storage.save(BASE_DIR + cardpath, ContentFile(data)) 2- the second way is to send the image as base64 data (blob) : extension = data.replace("data:image/", "").split(';',1)[0] data = data.replace("data:image/"+extension+";base64,", "") data = base64.b64decode(data) path = "/static/profilepics/" + str(uuid4()) + "."+extension default_storage.save(BASE_DIR + path, ContentFile(data)) I tried both ways and they are working just fine but i have two big questions I personally liked the first way (i find it a little bit clean) but i'm working with a mobile developer (Flutter) and he couldn't manage to send the image in that same format, is that format is specific for the web frontend ? The second way is working for us both (mobile&web) but the requests are so big especially if the image has a … -
User object has no attribute customer
I am trying to create cart using django but i am getting this error. while I try to check that the user is authenticated or no i used customer = request.user.customer but it says user has no attribute customer Here is my views.py def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = OrderModel.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] context = {} return render(request, 'Home/cart.html', context) here is my models.py class CustomerModel(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, null=True, blank=True, default='') customer_name = models.CharField(max_length=1000, null=True) customer_phone = models.CharField(max_length=20, null=True) def __str__(self): return self.customer_name class OrderModel(models.Model): customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True) order_date = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False,null=True,blank=True) transaction_id = models.CharField(max_length=1000, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product = models.ForeignKey(ProductModel, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Address(models.Model): customer = models.ForeignKey(CustomerModel, on_delete=models.SET_NULL, null=True, blank=True) order = models.ForeignKey(OrderModel, on_delete=models.SET_NULL, null=True, blank=True) address = models.CharField(max_length=10000) city = models.CharField(max_length=1000) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address I am stuck here and cant understand what to do. -
I want to get the names of multiple filenames being uploaded in one OnClick(button) function in Django
I want to get the names of multiple filenames being uploaded into one OnClick(button) function. And then store it in one variable. Example: A list of files have been uploaded file1, file2, file3, file4 in which file3 and file4 have sheet names to be called. How should i get the name of all the files(file1,file2,file3,file4 & also the sheetnames)using OnClick function in Django. can anyone please help me. My code are: click.js: <script> function FileDetails() { var fi = document.getElementById('file'); } </script> -
HTML template does on exist (base.html), Pycharm interpreter is unable to import views from my app name = 'app'
enter image description here i am unable to import views for my app in urls.py -
DjangoRestAPI - Using ModelViewSet to perform database management while running your own function (like a event handler)
I am used to using flask for apis and Django for databases and I am trying to learn the DjangoRestAPI. I followed the official Quickstart and another tutorial from medium and did a lot of research but I still struggle to understand how to implement my own function (eg: Doing some calculations or making a request to the Twilio api to send a message after receiving an api request) in a ModelViewSet. I have read that APIView can also be another option but it will making accessing the database quite difficult? When I run a print function in a ModelViewSet class in views.py, or a @action function, it prints but only once at the start of the programme when the server is starting. This is my version of the code in Flask and what I have tried in Django. Which class should I inherit (APIView or Viewset or ModelViewSet and where can I look for more information about this? Thank you very much for your kind help in advance: - please note that the flask implementation is a get request @app.route('/api/upload/<uuid>/<major>/<minor>/<rssi>',methods=['GET']) def beacon_info_upload(uuid,major,minor,rssi): if 'uuid' in request.args: uuid = str(request.args['uuid']) if 'major' in request.args: major = str(request.args['major']) if 'minor' in … -
request.user.is_authenticated give always False even user is login and i also try is_authenticated() this
hi i am always getting False value of request.user.is_authenticated please help me my setting.py is """ Django settings for project_manakind project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'vou-z!ea%!1l#1h+rr%*1baigjzf8gd&4qe4ch0&a-34eiid#w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition DJANGO_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY=[ 'rest_framework', # 'corsheaders', 'knox', ] MY_APPS = [ 'user_profile', 'app_apis', ] INSTALLED_APPS=DJANGO_APPS+THIRD_PARTY+MY_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # 'corsheaders.middleware.CorsMiddleware', # 'django.middleware.common.CommonMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'project_manakind.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path.joinpath(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project_manakind.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'project_manakin', 'PASSWORD':'ABC@123.com', 'USER':'pysaundary', 'PORT':'3306', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = … -
Extract count of records from datetime field from certain time intervals in django
Now i need count of records for midnight 12 to 6am and 6am to 7am separately. here is my model class Records(TimeStampedModel): client = models.ForeignKey(Client) assigned_date = models.DateTimeField(auto_now_add=True) Now only based on assigned_date i need count of records from midnight 12 to 6am and 6am to 7am separately can you please help me to solve this in django views. -
Django REST Framewok serializer to JSON data to JS
I have a model serializer in REST Framework like so: class MySerializer(serializers.ModelSerializer): field1 = OtherSerializer() field2 = serializers.ReadOnlyField() .... class Meta: model = myModel fields = "__all__" It works fine when calling it through REST viewset.modelViewSet. Now I would like to use the same serializer in Django view, like so: def get_model(request): model = MyModel.somestuff() model_ser = MySerializer(model) model_ser_data = model_ser.data .... model_json = JSONRenderer().render(model_ser_data) .... return render(request, 'my_template.html', context={'model':model_json}) and get data in template as JavaScript object: <script> const data = '{{model}}' </script> I always get a string like object in Javascript: "b'{\"id\":null,\....'" I have tried json.dumps(...), but get error due to Decimal fields. I believe this to be a basic task, since you can do the same thing with axios.get(...). What am I doing wrong? Thank you. -
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.