Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which frame work to use to build a web app [closed]
I have a desktop application that used to work with the tkinter package. But I need to turn it into a web application, so I have to rewrite it. I don't know which framework to choose between Django, Turbogears, Web2py and Cubicweb, as I'm not familiar with any of them. My application has 4 pages, the home page and 3 other pages accessible via buttons on the home page. These tabs contain large graphs in the form of a network and a map with numerous filters, everthing is built using data loaded when the application is launched (the data are loaded using an url link). The application also features images, help buttons that open a help pdf, and buttons to return to the home page. I have no idea which framework would be best suited to my problem and at the same time the easiest to use. From what I've read, I'd go for Django, even if it's a bit complex, especially as there are lots of tutorials on youtube. Thanks ! -
Django and react router shows blank page without content
I am using react inside django. I use npx create-react-app and npm run build to create react . The structure looks like this frontend main mysite In react I have two components. Form and App. App is the one that renders all other components. In settings I have configured frontend/build to be the templates. main/views.py def createUser(request): return render(request, 'index.html') main/urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('register/', views.createUser), ] frontend/src/App.js import Form from './Form'; import { BrowserRouter as Router, Routes, Route} from 'react-router-dom'; <Router> <Routes> <Route exact path='/register' element={<Form/>} /> </Routes> </Router> When I go to /register I get a blank page with the css that I wrote for form.js but nothing else shows. -
I don't understand why the code is not working
here is the error: >>> from blog.models import Post >>> user = User.objects.get(username='admin') Traceback (most recent call last): File "<console>", line 1, in <module> NameError: name 'User' is not defined >>> here is the model: from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250) author = models.ForeignKey( User, on_delete=models.CASCADE,related_name='blog_posts' ) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2,choices=Status.choices,default=Status.DRAFT) class Meta: ordering = ['-publish'] indexes = [models.Index(fields=['-publish']),] def __str__(self): return self.title I tried to change this part of the code ' 'to this 'from django.contrib.auth.models import User' but it did not help -
Django React Heroku
I have this problem {status: 'PARSING_ERROR', originalStatus: 200, data: '<!doctype html><html lang="en"><head><meta charset…pp.</noscript><div id="root"></div></body></html>', error: SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON} data : "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><link rel=\"icon\" href=\"favicon.ico\"/><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/><meta name=\"theme-color\" content=\"#000000\"/><meta name=\"description\" content=\"Chisfis | Online Booking – a responsive React template theme with Online booking, Real Estate, and booking system for accommodation, tours, travel experiences, cruises, car rentals, real estate, and travel agencies\"/><link rel=\"apple-touch-icon\" href=\"./logo192.png\"/><link rel=\"manifest\" href=\"./manifest.json\"/><title>Chisfis || Hotel booking Template</title><script defer=\"defer\" src=\"/static/js/main.6b24de68.js\"></script><link href=\"/static/css/main.c71aaa5c.css\" rel=\"stylesheet\"></head><body><noscript>You need to enable JavaScript to run this app.</noscript><div id=\"root\"></div></body></html>" error : "SyntaxError: Unexpected token '<', \"<!doctype \"... is not valid JSON" originalStatus : 200 status : "PARSING_ERROR" [[Prototype]] : Object How do solve this problem? -
ckeditor don't appear in django form
I designed a web with Django . I use CKEditor for content of a model but after I connected my site to bucket storage, box CKA editor disappeared and won't upload so I can upload text, what's the problem? enter image description here what do I do? -
List view for user specific data?
I am a beginner in django . I am trying to get build a notesapp, but when a user logged in they are able to see all the all notes that are present in the admin panel. when I tried the below view function im just getting a blank page.How to write a view function such that a particular user can see the notes only they made . I have the following views.py @login_required(login_url='login') def Viewall(request): notes = NotesModel.objects.filter(user=request.user).all() return render(request, "Viewall.html", {'notes':notes}) models.py class NotesModel(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE,null=True) title=models.CharField(max_length=255,unique=True) note=models.TextField() time=models.DateTimeField(auto_now_add=True) viewall.html {% for data in notes %} <div class="col"> <div class="card note_card"> <h5 class="card-header">{{ data.title }}</h5> <div class="card-body"> <h5 class="card-title"></h5> <p class="card-text">{{ data.note|truncatechars:50}}</p> </div> </div> </div> {% endfor %} -
How to set download directory?
def download_video(url, save_path): loader = instaloader.Instaloader() try: post = instaloader.Post.from_shortcode(loader.context, url.split("/")[-2]) video_url = post.video_url response = requests.get(video_url, stream=True) if response.status_code == 200: with open(save_path, 'wb') as file: response.raw.decode_content = True shutil.copyfileobj(response.raw, file) print("Video downloaded successfully!") else: print("Failed to download the video.") except Exception as e: print("Failed to download the video:", str(e)) I created this function to download instagram video from it's url, i add this on my website. Problem: Its was working fine when i wasn't using on my website, i want it available for everyone online, Error : Failed to download the video: [Errno 13] Permission denied, How can i fix it, so that it can download in users downloads folder and on mobile. Thanks help me to solve the error. -
ImproperlyConfigured: settings.DATABASES error in Django project
I made simple reservation website in django. And It works just fine in dedicated server but it returns this error when i try to migrate it in local machine. django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I haven'touched anything in DATABASES. So it looks like this DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } Is there any possible solution for this problem? I've tried some solutions that i found online such as adding from .database import * But it didn't work at all for me. -
converting HTML to PDF using wkhtmltopdf Python
I am converting HTML to PDF. PDF downloaded success but it return blank pdf pages not showing any converted content. in my HTML file have Shopify CSS links. if convert minimum content HTML file then it converted correctly from django.shortcuts import render from django.http import HttpResponse import pdfkit from django.conf import settings def convert_html_to_pdf(request): if request.method == 'POST': rendered_template = render(request, 'newundergrace.html') HTML file options = { 'enable-local-file-access': '', 'orientation': 'landscape', 'page-size': 'Letter', 'page-size': 'A4', 'margin-top': '0', 'margin-right': '0', 'margin-bottom': '0', 'margin-left': '0', 'dpi': 96, } rendered_content = rendered_template.content.decode('utf-8') pdf = pdfkit.from_string(rendered_content, False, options=options) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=output.pdf' response.write(pdf) return response return render(request, 'index1.html') -
Docker, Django(gunicorn) + Nginx | django's admin CSRF 403 error
I confused this situations. :( I want to run Docker compose Django + Nginx at AWS EC2/ALB the docker compose and nginx.conf, AWS setup is below, django is gunicorn example_mvp.wsgi -b 0.0.0.0:8000 then, nginx listen 80 to proxy_pass http://example_mvp:8000 nginx.conf http { server { listen 80; include /etc/nginx/mime.types; client_max_body_size 16M; location /favicon.ico { return 204; access_log off; log_not_found off; } location /static/ { alias /staticfiles/; } location / { proxy_pass http://example_mvp:8000; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } } AWS EC2, security group inbound 80,443 port open. and AWS ALB setup, (generate domain SSL via AWS Certificate Manager) 1. https:443 -> http:80 2. http:80 -> redirect:443 so, my domain connect ALB. problems I access the admin page, but CSRF 403 error. my product's settings attach the CSRF_TRUSTED_ORIGINS settings.py DEBUG = False CSRF_TRUSTED_ORIGINS = ["https://mydomins.com"] but access admin page or POST forms, always return 403 error. I check the ALB setup, 2. http:80 -> http:80, and access admin page ok. (not 403 error) I don't know what's the problems -
How to Subcribe to an update of database django
When using Django model, I have an table name "AppConfig". What I want is that whenever there is an update on AppConfig table (inluding create,modify,delete) the result will log into a file. Is there an convenient way to do it. I can do this by adding log function to every point that I update the Config table in code. But it is quite messy and there is potential of mistake. -
"connection timeout expired" in PostgreSQL15
requirement: try to connect pgAdmin4 to Server, and it need to insert password, and I'm sure the password what i insert (I have reinstalled it again and again but i can't work) processing: so first when i installed postgre15 and pgAdmin4, that's all no block, and it let me customize password and i made it. when it come to finish for pgAdmin and postgreSQL, I select the pgAdmin4 to create database, the error is comming, below is troubleshoot. shotimage I want to connect to Server in pgAdmin4 first. -
Fallback or Error Handling for Secondary Django Database
I have a second database in my Django application. However, I need a VPN to connect to it. If my VPN is not enabled psycop2 will throw an operational error back at me. However, I would like the ability for that database to fail silently and fallback to the default database in case the connection is refused. Is there a way to do this? I cant seem to find a default way and it seems like a very basic functionality to have. I have tried to implement something through routers suggested in stackoverflow before, but at startup my application will simply say OperationalError: Connection Refused and then crash the rest of the startup procedure. class OVIRouter: """ A router that takes all of the reads, writes and changes to the OVIDevice model (also known as "ovidevice" once the model is translated to SQL), and sends them to the OVI database (The database configured in settings.py through the "ovi_db" entry in the DATABASES constant). """ db_name = 'ovi_db' def db_for_read(self, model: Model, **hints: Any) -> Optional[str]: """ Attempts to read the OVIDevice model go to the OVI device database. If the connection to the OVI device database fails, the default database … -
Unable to add an image in Django Admin page hosted on EC2 with Apache2 server
I am learning Django deployment on EC2 with Apache server. I am able to serve static files. But when I try to add an image via Admin page, I am getting below error. The permissions for media_root is as below I am able to add image with Django server inside the instance, but with Apache server I am getting error. Apache2 is configured as below Alias /static/ /home/ubuntu/testing/dummy/static_root/ Alias /media/ /home/ubuntu/testing/dummy/media_root/ <Directory /home/ubuntu/testing/dummy/static_root> Require all granted </Directory> <Directory /home/ubuntu/testing/dummy/media_root> Require all granted </Directory> WSGIScriptAlias / /home/ubuntu/testing/dummy/dummywebsite/wsgi.py <Directory /home/ubuntu/testing/dummy/dummywebsite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess loserprocess python-home=/home/ubuntu/testing/testingenv python-path=/home/ubuntu/testing/dummy:/home/ubuntu/testing/testingenv/lib/python3.10/site-packages/ WSGIProcessGroup loserprocess WSGIApplicationGroup %{GLOBAL} I have given the permission as mentioned here, but still I am facing issue. Can you please let me know what I am missing here. Thanks -
POST 403 Forbidden Django Vue Js
I am using Vue JS and Django Rest Framework and I am trying to add a feature to add a blog post. I am not sure why I am getting a 403 forbidden error in the console. I am getting the following error: Forbidden (Origin checking failed - http://localhost:8080 does not match any trusted origins.) Any direction would be appreciated I am not sure if this is a CORS related error but I have CORS_ALLOWED_ORIGINS = ['http://localhost:8080'] in my settings.py. I have also enabled the middleware. I have a login page that works and assigns the user a token when logged in (I am using djoser). I have made sure that the user has permissions to add a blog entry. here is my code for submitform if relevant: submitForm() { const postData = { title: this.title, author: this.author, body: this.body, }; const token = localStorage.getItem('token'); // Retrieve the authentication token from local storage axios.post('/api/v1/posts/add-post/', postData, { headers: { Authorization: `Token ${token}`, // Include the token in the request headers }, }) .then(response => { console.log(response.data); // Handle success, e.g., show a success message or navigate to another page }) .catch(error => { console.log(error); // Handle error, e.g., show an error … -
Error on testcase after update from django 2 to 4
I'm updating my entire project from Django 2.2 to Django 4.2.3. I have already read the entire deprecation timeline and done regression tests, and everything is working. But, using the TestCase, I found a difference: tear_down isn't flushing the database after each test, and when it runs, models that are created in migrations are removed as well. Does anyone know what has changed between those versions that can affect tests, teardown, and flush? I tried debbug testcase source code while running my tests, and read changelogs and deprecation list from django docs but without any tip. -
Real Estate Project - Error in Pagination Code
I am a web developer student and I am currently working on a real estate project. I have created a pagination system that allows users to view a list of properties in pages of 10. However, I am getting an error when I try to load the second page of properties. The following is the code that I am using for the pagination: def get_properties(page_number): if page_number is None: page_number = 1 start_index = (page_number - 1) * 10 end_index = start_index + 10 properties = Property.objects.all().order_by('-list_date')[start_index:end_index] return properties The error that I am getting is: Page Not Found (404) The requested page could not be found. I have tried debugging the code, but I cannot seem to find the source of the error. I am hoping that someone can help me troubleshoot this issue. -
Nginx + Gunicorn + Django: displays Nginx default page every 3 times
I have a Django app on Gunicorn 20.1.0 (:8000), served with Nginx 1.18.0 as the main server (link to the website) on Debian 11.2: Nginx <-:8000-> Gunicorn <-> Django The server displays the Nginx default template every three times (1st request, 4, 7, 10, so on). Here is a snippet of the Nginx access log (notice the pattern in the bytes sent): 89.xx.xxx.xx - - [05/Jul/2023:11:37:23 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:51 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:52 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:53 -0400] "GET / HTTP/1.1" 200 396 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" 89.xx.xxx.xx - - [05/Jul/2023:12:01:54 -0400] "GET / HTTP/1.1" 200 6723 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0" ... There's no error in Nginx or Gunicorn error.log files (both server and site specific logs are blank. previously I had some errors so I'm assured that the logging is … -
Issue with Google Sign-In using Django-allauth and React
I am using bellow development environment: OS = Ubuntu 22.04.2 Python = 3.10.6 Django = 4.2.2 djangorestframework = 3.14.0 django-allauth = 0.54.0 I am running the the Django server on localhost 8000 with SSL and the React server on 3000 The authentication is being handled by django-allauth and I am only using google and the local a local model for authentication. I have registered both the front-end and back-end URLs with google credentials. The Google credential configuration looks like google credential configuration I am running the server with gunicorn with below command: gunicorn --certfile=certs/server.crt --keyfile=certs/server.key mt_backend.wsgi:application When I try to login with google using the URL: /accounts/google/login/. I am able login successfully. However when I try to POST the request to the same endpoint from my react app it throws 304(Forbidden) error with backend logging: Forbidden (CSRF cookie not set.): /accounts/google/login/ Here's the code snippet for login function used in react app: const handleGoogleLogin = () => { axios .post("https://127.0.0.1:8000/accounts/google/login/") .then((response) => { console.log(response); }) .catch((error) => { console.error(error); }); }; I have tried compare both the session and found out, there is one additional csrfmiddlewaretoken getting passed on paylod when I tried to use the django url , but … -
Permission Denied Nginx CSS File Django-Gunicorn Local VM
can helpme? My application in django does not load the css when I use gunicorn + nginx below I have permission error: 2023/07/05 16:29:51 [error] 18862#18862: *1 open() "/home/victor/helpme/tickets/static/css/style.css" failed (13: Permission denied), client: 192.168.0.106, server: 192.168.0.113, request: "GET /static/css/style.css HTTP/1.1", host: "192.168.0.113", referrer: "http://192.168.0.113/ticket_list/" My socket file: [Unit] Description=gunicorn helpme socket [Socket] ListenStream=/run/gunicorn_helpme.sock [Install] WantedBy=sockets.target ~ ~ ~ My Service File: [Unit] Description=gunicorn daemon Requires=gunicorn_helpme.socket After=network.target [Service] User=victor Group=www-data WorkingDirectory=/home/victor/helpme ExecStart=/home/victor/helpme/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn_helpme.sock \ ticket_system.wsgi:application [Install] WantedBy=multi-user.target Nginx: ps auxf | grep nginx victor 18883 0.0 0.0 6476 2308 pts/0 S+ 16:34 0:00 | \_ grep --color=auto nginx root 18860 0.0 0.0 55196 1716 ? Ss 16:29 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on; www-data 18861 0.0 0.2 55864 5596 ? S 16:29 0:00 \_ nginx: worker process www-data 18862 0.0 0.2 55864 5596 ? S 16:29 0:00 \_ nginx: worker process Sites-enabled server { listen 80; listen [::]:80; index index.html index.htm index.nginx-debian.html index.php; server_name 192.168.0.113; location /static/ { root /home/victor/helpme/tickets; } location /media { alias /home/victor/helpme/tickets/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn_helpme.sock; } location ~ /\.ht { deny all; } location ~ /\. { access_log off; … -
Having error during adding a search feature in my ecommerce Django website
I put this command to my powershell: python manage.py startapp search And I am getiing this error again again: Traceback (most recent call last): File "C:\Users\ASUS\OneDrive\Desktop\Django_Prac\Hello\manage.py", line 22, in <module> main() File "C:\Users\ASUS\OneDrive\Desktop\Django_Prac\Hello\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\apps\config.py", line 193, in create import_module(entry) File "C:\Users\ASUS\AppData\Local\Programs\Python\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1142, in _find_and_load_unlocked ModuleNotFoundError: No module named 'search' What can I do now? Please help! I want to know how to troubleshoot this? -
Django StreamingHttpResponse not streaming on production API
I'm trying to stream an OpenAI response from a Django server to the browser. I have a view in Django that looks like this (assume that generate_thing returns a stream from OpenAI): @api_view(['POST']) def generate(request): data = json.loads(request.body.decode('utf-8')) result = generate_thing(data) return StreamingHttpResponse(result) Whenever I run this locally, it works exactly as expected. When I upload my Django code to EC2 and try to call it directly on its IP address, it works exactly as expected. However, when I run it through a proxy like API Gateway or Nginx, it waits until the stream has completely finished to return a response. I tried setting Content-Type to text/event-stream before returning it like response = StreamingHttpResponse(result) response['Content-Type'] = 'text/event-stream' return response and it had no effect. -
Preload unique related object in Django
This works just fine and only performs one DB query: qs = Blog.objects.filter(post=Subquery( Post.objects.filter(blog=OuterRef("pk")) .order_by("-date").values("pk")[:1] )) for bt, pt in qs.values_list("title", "post__title"): print(f"The latest post in {bt} is about {pt}") However, how can I have Django construct Blog and Post objects out of such a queryset without needing additional queries? Something like the following: for blog in qs.select_related("post"): print(f"The latest post in {blog.title} is about {blog.post.title}") Assume it’s not possible to reverse the queryset (Post.objects.select_related("blog")), because, for example, there are other related models that need the same treatment as Post. -
Export df to csv in Django
I am new to Django I currently already have a df in the views.py, I pull the data from the MSSQL database which already connected. Views.py def CaseTest(request) dfa_query=""" Select * from database """ dfa=pandas.read_sql_query(dfa_query,connection) dfa_html=dfa.to_html(index=False,table_id='dbtable") return render(request,'CaseTest.html') CaseTest.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CaseTest</title> </head> <body> {% load site_extra %} <h2> CaseTest DF </h2> <div style="height: 500px; overflow: auto;"> {{itba | safe}} </div> </body> I want to add a button to html, when the user click it, they can download the df. How can I realize this. Any help is really appreciated! -
Python FileNotFoundError even though file is in same directory
I'm trying to use pickle to load a file within the same directory but I am getting FileNotFoundError for some reason. This is my code in views.py: from django.shortcuts import render from django.http import HttpResponse from django.core.files.storage import FileSystemStorage import pickle model = pickle.load(open('braintumor.pkl', 'rb')) def say_hello(request): return render(request, 'hello.html', {'name:': 'Alisha'}) def index(request): return render(request, 'index.html', { 'a' : 1}) And this is my file structure: webapp views.py braintumor.pkl It's a django app so is more complex than this but it wasn't important to list every file and directory, there is definitely no spelling errors and the pkl file is definitely in the same directory as views.py. I also tried a file structure like this: webapp views.py models -braintumor.pkl And then I tried using the import statement: "from models import braintumor" but that didn't work because I got an error saying that there is no such file or directory 'models'. I also tried loading it with the statement: "model = pickle.load(open('models/braintumor.pkl', 'rb'))" but still get FileNotFoundError! It seems no matter what I do, python simply cannot load anything and I have no idea what to do. I see nothing wrong with any of the solutions I tried. Please help, …