Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uploading pdf file from docx2pdf to database table in python
I want to upload a generated pdf to my database table. I am using doxc2pdf to convert a docx file to a pdf file in python: convert("input.docx", "output.pdf") So the output file that is generated is called "output.pdf" now i want to upload this to my "generated_report_file_upload" in my Report_File_Upload_Table DB table: Report_File_Upload_Table.objects.create(generated_report_file_upload=output) The problem is that i am getting an error saying that name 'output' is not defined. full code of the function is below: doc = docx.Document() doc.add_heading("no text") doc.save('thisisdoc.docx') convert("thisisdoc.docx", "output.pdf") Report_File_Upload_Table.objects.create(generated_report_file_upload=output) -
Django: Bootstrap classes loading but not my style.css
Here is my HTML file: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>{% block title %}{% endblock %}</title> <!-- Link to Bookstrap and stylesheet --> <link rel='stylesheet' href="{% static 'css/bootstrap.min.css' %}"> <link rel='stylesheet' href="{% static 'css/style.css' %}"> <script src="{% static 'js/bootstrap.min.js' %'}"></script> </head> <body class="bg-blue"> <div class="container"> <div class ="row"> <div class ="col-lg-4 col-lg-offset-4"> <br/> <br/> <br/> <div class="panel panel-body"> <div class="panel-body"> <h3 class="text-center text-uppercase"><b> {% block heading %}{% endblock %}</b></h3> <br/> {% block content %}{% endblock %} </div> </div> </div> </body> </html> I want to use the "bg-blue" class defined in my style.css. .bg-blue{ background-color: #3F3F63; } However it doesn't work. My boostrap and style.css are in the same folder. The Bootstrap loads, for example my text in centered and uppercase and the font is different. -
Connecting Django to Docker Postgres instance raising django.db.utils.OperationalError
I'm trying to execute a django project on my local machine, the project requires Postgres. I know close to nothing of docker. I pulled postgres image from docker hub and executed the followin command, as suggested by the instructions in postgres docker hub page. $ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres The docker container is up: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 402180487f68 postgres "docker-entrypoint.s…" 2 hours ago Up 2 hours 5432/tcp some-postgres But I can't make Django to connect to it. (Django is running on my local machine, not on docker) Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'mysecretpassword', 'HOST': 'localhost', 'PORT': 5432, } } If I execute migrations with the settings above the error is: django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? I assume the connection is not beign refused, because if I stop the container the error is the same. Some tutorial/answer suggested HOST should be the container … -
How to find an optimal price combination , given two arrays of Django model objects with different prices?
I am working on a project (Django) and stuck on one point. In nutshell, I have scraped data about the flights and hotels to my DB. Each flight, hotel (on each date) has several options (price differs). I need to receive a minimum and maximum amount of money a user would like to spend. Considering his input I need to give minimum, optimal, and maximum expenditure combinations of flight (to), hotel, and flight (back), in range of his max and min amount. So, my question is, what python technology would be the best option for my case. If you had the same or at least similar task, your way of solving would be a tremendous help! Thanks in advance. -
To handle 10000 request per second in django what should be CONN_MAX_AGE
I am expecting around 10000 - 12000, request per second(or every 10 seconds but in worst case 1 sec) on a site. I am using PostgreSQL database and in every request I am fetching data from database, what should be CONN_MAX_AGE value, and how do you calculate this value and on what basis. I have seen a bit about pooling using PgBouncer, should I go with it, and how can I integrate this in existing Django project. And I am hosting my site on Heroku, as PostgreSQL where number of max connections at a time is 120-400 connections, How should I manage this traffic on my site. -
How to sort by date if status is true in elastic search bool query
I have a json like as follows in elastic search index. How to sort data if advertisement does not expire and status is true then sort them as desc. How can I achieve this? I tried using end_date sort but it did work. Also i need to show all expired data which end_date are expired. advertisement = [ { "id": 1, "name": "test", "status": True, "start_date": "2020-08-09", "end_date": "2020-09-09", }, { "id": 2, "name": "test2", "status": False, "start_date": "2020-08-09", "end_date": "2020-08-09", }] This is my elastic search method. def elastic_search(category=None): client = Elasticsearch(host="localhost", port=9200) query_all = { 'size': 10000, 'query': { "bool": { "filter": [ { "match": { "name": "test" } }] }, }, "sort": [ { "end_date": { "type": "date", "order": 'desc' } } ] } resp = client.search( index="my-index", body=query_all ) return resp -
Add a 'self' model to a ManyToManyField in Django
I created a Word model which keeps synonym and antonym for each words like this: class Word(models.Model): word = models.CharField(max_length=64, primary_key=True) synonyms = models.ManyToManyField("self", related_name="syn+") antonyms = models.ManyToManyField("self", related_name="ant+") I tried to add a new word and then relate it to its synonyms, but it would be added to antonyms as well. This is part of my view function which is responsible to add the newWord to synonyms field of wordModel. synWordModel = Word.objects.get_or_create(word=newWord)[0] synWordModel.save() wordModel.synonyms.add(synWordModel) -
ImportError at / main doesn't look like a module path
возникла проблема никак не пойму как решить: Когда я запускаю сайт на django выскакивает ошибка ImportError at / main doesn't look like a module path Папки и файлы проекта: -taskmanager -main -migrations -templates -mainp index.html init.py admin.py apps.py models.py tests.py urls.py views.py -taskmanager init.py asgi.py settings.py urls.py wsgi.py -db.sqlite -manage.py settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parent.parent SECRET_KEY = 'n@ugerqwpc434335344bg6nsbu65debqh^4!om@z#q&^l@- t8*b&-1+7g9#c_ie!+n1c^' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'taskmanager.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [r'C:\User\pythonProject\taskmanager\main\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', 'main', ], }, }, ] WSGI_APPLICATION = 'taskmanager.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'ru' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True STATIC_URL = '/static/' Надеюсь вы поможете , если понадобится ещё какая-та информация пишите. -
How do I test the frontend of my django/react app?
I have a Django/React app that I'd like to integrate some pre-deployment testing into. I can build tests in django for python specific stuff, but how would I go about building some robust testing for my frontend? Do I need to build some Selenium functions that test my react app in the browser? Or is there a more efficient way to do this in react? -
How to save data when working with multiple Django forms
I'm new to Django and trying to implement a detailed HTML/JS form that I have into the django framework for the admin, server, and database functionality. My current HTML/JS displays a dynamic form in which certain answers lead to specific question routes that are validated with jquery at 3 different times due to there being 3 different forms before adding all the answers to a JS object. What I am trying to do is store that JS Object in the sqlite db to be accessed through admin. Does Django add further validation security on top of csrf tokens? Should I rewrite the whole thing in models and forms or would making the JS object a JSON string and passing that to the Django db be secure enough? If rewriting in models/forms, how can the data from each form be temporarily saved before passing it all into the db as one entry. I realize this is a very naive question, but the Django documentation doesn't seem to be focused on quite what I'm trying to do and I'm having a hard time applying the available documentation to myself. Thank you! -
Random characters being added to file upload name in django
I have a sqlite database table that takes a file upload. Each day in my django admin I select the file and delete it and upload the new file. My problem is that the file name of the new file i upload adds some random characters to the the name of the file. This is because the old file and new file name have the same name. so I guess that django is just trying to compensate for this. This would be fine normally however i have some logic in the site that uses the specific file name. so at the moment i am going into the code and adding these new random characters to my logic code. I m only hosting locally at the moment. but will be launching via GitHub & heroku in the future. Is there a way to just to stop this? -
no django package in pipfile (windows 10)
Hello i started my first Django project yesterday and after some tests i started a new "serious one" i created a new directory created a new virtual enviroement , installed django a created a new project, it works but on the pipfile i don't see Django..... what i did in the new directory i created is: pip install pipenv pipenv shell pip install Django==3.1 django-admin startproject secondtest . python manage.py runserver on the pipfile i had from the very first project i created i had django among the list of the packages [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==3.1" [requires] python_version = "3.8" while on the second one [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] [requires] python_version = "3.8" i also did pipenv install requests and it adds it in the packages list.... could it be that i messed up something? -
How to get the desired value for lat,long to display only the required portion of the map with Leaflet.js?
I am trying to display a portion of a map with this amount of code:- <div id="mapid" style="height: 280px; width: 1143px;"> <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script> <script> var mymap = L.map("mapid").setView([5, 120], 13); L.tileLayer("http://{s}.tile.osm.org/{z}/{x}/{y}.png", { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors', }).addTo(mymap); </script> </div> But that displays this portion of the map:- But I am trying to get this portion of the map:- is there any tool I can optimize my code to do so:- -
can be use the same django backend in web and mobile?
i have not a real problem but i have a question, i want to start learning mobile development, and i saw that you can make a mobile application with react and have a Django back-end, so, is possible to have a web application and a mobile application with the same Django back-end? how is it possible or which should use? I have seen some videos about how to make a Django back-end for a mobile app, and for a web app too, but i don´t understand how to do both in the same back-end. i would appreciate if you give me some tips, or another back-end framework to make it. -
How do I set TensorFlow to load a model on AWS?
I'm having issues loading my TensorFlow model. This works locally (when running gunicorn --bind ...) and on that server. However when I move onto the AWS I get the following error: { "error": "there was an error Unable to open file (file read failed: time = Wed Aug 12 19:02:14 2020\n, filename = '/home/ubuntu/ambdjango/leadmanager/assets/model11', file descriptor = 13, errno = 21, error message = 'Is a directory', buf = 0x7fff3b251850, total read size = 8, bytes this sub-read = 8, bytes actually read = 18446744073709551615, offset = 0)" } As far as I am aware both my local host and the AWS EC2 instance are running the same version of TensorFlow (2.3.0), however when I type "which TensorFlow" into the EC2 instance no response is given which is strange. The code for my backend is below, if anyone has any ideas it would be massively appreciated. from tensorflow.keras.models import load_model @api_view() def model (self): try: BASE_DIR = Path(__file__).ancestor(2) Mmodel_DIr = os.path.join(BASE_DIR, 'assets/model11') model = load_model(Mmodel_DIr) sp = int(self.GET.get('sp', '')) ran = float(self.GET.get('ran', '')) testinverted = 1/sp testran = [normran(ran)] testinverted = [norminverted(testinverted)] dataframetest= pd.DataFrame() dataframetest['ran']= testran dataframetest['invertedodds']= testinverted chance = (model.predict(dataframetest)[0]) chanceep = 0.04 if chance < 0.04 and sp<10 … -
how to have a video be shown after a certain date
I made a category in my database called 'show_after_date', which is a DateTimeField, and I want to have have the view say that the videos should only be shown if the show after date is earlier then the current date. How can I do that? thanks! -
Django TypeError: Object of type User is not JSON serializable
So I was trying to make an ajax call in django but this happend Internal Server Error: /ajax/new_notification/ Traceback (most recent call last): File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\berna\Desktop\Python & Javascript\Web development\MiFamiliaEsUnDesastre\mifamiliaesundesastre\chat\views.py", line 71, in new_notification return JsonResponse(user, safe=False) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\http\response.py", line 561, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\serializers\json.py", line 104, in default return super().default(o) File "C:\Users\berna\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type User is not JSON serializable HTTP GET /ajax/new_notification/ 500 [0.15, 127.0.0.1:64660] the code that is raising this error is here, also I am new in django so maybe the solution can be ver obvious def new_notification(request): user = request.user user.profile.notifications = user.profile.notifications + 1 user.save() return JsonResponse(user, safe=False) thank you for the help -
The recipient email does not receive any message in django
I have a web application and I would like to be able to send an automatic email to any user in case of need. I am testing it and everything seems to be fine but I noticed that the recipient email does not receive any message. Below is my configuration in the settings.py file. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'beaubien.web-dns1.com' EMAIL_PORT = 465 EMAIL_HOST_USER = 'med.abdillah@massiwatechnology.com' EMAIL_HOST_PASSWORD = '###########' EMAIL_USE_SSL = True EMAIL_USE_TLS = False Here is views.py file. def send_email(request): send_mail('Bonjour cher personnel', 'Hello there,Ceci est un message automatique.', 'med.abdillah@massiwatechnology.com', ['abdillah@buaa.edu.cn'], fail_silently=False, ) return render(request, 'courriers/send_email.html') Please, assist me. Thank you in advence -
Django timezone isn't working as expected
I am trying to create an entry app. One of the pages takes entry from the user, the current date and time of my timezone(I have set TIME_ZONE = 'Asia/Kolkata') and saves it in the database. View function of this page: def new_entry(request): date = timezone.now() date = date.replace(second=0, microsecond=0) just_date = date.strftime('%d %B %Y') just_time = date.strftime('%H:%M') if request.method == 'POST': content = request.POST.get('content') ent = Entry(user=request.user, date=date, content=content) ent.save() return redirect('user') return render(request, 'mainapp/new_entry.html', {'date':just_date,'time':just_time}) Then in another page I fetch and display all these dates from the database..The view function of that page: def user(request): if request.method == 'POST': user_entries = Entry.objects.filter(user=request.user) return render(request, 'mainapp/user.html', {'user_entries':user_entries}) In the template of this page I access the date attribute. The problem is when I view the date in the template of the first page it is displayed in UTC and the date on this second page is displayed in the way I want(i.e. Asia/Kolkata timezone). Why is this difference of timezone occuring even though I have clearly set the timezone? -
No module named psycopg2 even after installing it
Im trying to push my django app to heroku master but im getting this error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2' I've done pip3 install psycopg2 and pip3 install psycopg2-binary I have also put them in my requirements.txt: dj-database-url==0.5.0 psycopg2==2.8.5 psycopg2-binary==2.8.5 But the problem doesnt seem to go away. I have installed them all in my venv and always commit. This is a Django app. Any ideas? -
Django sqlite "Database is locked" when writing to STATIC_ROOT
I have customized the save() method of my Django model to write some data into a file. I want to write the data into a file in STATIC_ROOT so nginx can serve it. When I write data into a file inside Django project root everything is OK but when I try to write to STATIC_ROOT I get "Database is locked error". What is the problem with that? -
update current Date Time every time I change any other field in Django models
I have a situation wherein I have a model class with various variables of different data types along with a ForeignKey and I want to update DateTime every time a change is made to any one of the variables inside that class. The code is : `class Career(models.Model): job_title = models.CharField(max_length=400) job_location = models.CharField(max_length=100, null=True) job_category = models.CharField(max_length=100, null=True) functional_area = models.CharField(max_length=100) job_description = models.TextField(null=True) roles_responsibilitis = models.TextField(null=True) qualification = models.TextField(null=True) additional_info = models.TextField(null=True) perks = models.TextField(null=True) company_description = models.OneToOneField(General, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) posted_on = models.DateTimeField('posted_date')` I want to update 'posted_on' with the current DateTime after every update to any of this fields in the database. Thanks in advance. -
Is it possible to set default at DB level using Django ORM?
I see in this post that adding a default without null=True creates a series of alter, update, alter, and alter SQL commands. I've read the bug pointed to in the post in which this functionality is verified and the OP's additional question at the end is my question - is there some way to add a DB level default to a column using Django ORM migrations, that is maybe not documented? It sounded like this may be an existing feature request at that time and something may have changed since then. Without the null=True, those series of SQLs are issued. With null=True, no commands are issued: -- Alter field foo_field on footable -- COMMIT -
Django built-in server can receive/respond HTTPS calls?
Django built-in server can receive/respond HTTPS calls? What do I need to setup in order to do that? -
django website where user download exe file
I made mini project like book store (used Tkinter for GUI and sqlite for database) that run locally Q.1) Now i want to make local website using django so user can download that book store exe file. Q.2) Or just able to use my mini project book store on that local website directly. is it possible? so far my simple thinking want me to do this. I'm new to django (just started). so can provide me some learning resource material or give me some suggestion