Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to connect already existing PostgreSQL database with Heroku?
I deployed my app using Heroku, but while deploying Heroku created a new PostgreSQL database. Now I need to change that to my already existing PostgreSQL database(I am using Django framework in VsCode), which I used while running in the localhost. Does anyone have an idea, please help me with this?. -
Django form not getting the select field selection. Dropdown dependant
so, I have a very complex way in wich I ask a database within my own project for the State, County and Neighborhood throuh Ajax, with the help of the forms.py, now, I have it for registering a room (which is related to these locations), and it goes through a CreateView, with this one I have no issues, but, when wanting to make a queryset to perform a search of my rooms and their respective locations, it just seems like it´s not picking up what is selected on the field, this I know because I asked it to print the request and it prints 'None', here is my code: models.py class PostRoom(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE,default=1,related_name='room_author') colonia = models.ForeignKey(Colonia, on_delete=models.SET_NULL, blank=True, null=True) cp = models.ForeignKey(CP, on_delete=models.SET_NULL, blank=True, null=True) municipio = models.ForeignKey(Municipio, on_delete=models.SET_NULL, blank=True, null=True) estado = models.ForeignKey(Estado, on_delete=models.SET_NULL, blank=True, null=True) the CreateView where everything works perfectly: class RoomSubmitCreateView(LoginRequiredMixin, CreateView): model = PostRoom form_class = PostRoomForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) The ajax code through which I send the selected fields to my location.views.py: <script> $("#id_estado").change(function () { var url = $("#roomForm").attr("load-municipios"); // get the url of the `load_cities` view var estadoId = $(this).val(); // get the selected country … -
How to use dropify in image/file fields in Django admin?
I want to use dropify for image/file upload in Django admin. But I have not found any usage/tutorial how to use it in Django admin. Is there a way how to do it ? -
Django-Tinymce not loading
I have included django-tinymce module in my django 3.1 project. However, the tinymce editor disappeared from my pages and I don't know why. When I run the project in my localhost I get a 404 on init_tinymce.js, a folder that is not in my project and not specified in the django-tinymce project. I hardly touched anything but it suddenly did not show on my pages. Here is the log from my console: [08/Jun/2021 08:32:26] "GET /letter_head_edit/1/ HTTP/1.1" 200 14367 [08/Jun/2021 08:32:26] "GET /static/django_tinymce/init_tinymce.js HTTP/1.1" 404 179 [08/Jun/2021 08:32:26] "GET /static/django_tinymce/init_tinymce.js HTTP/1.1" 404 179 Here is my settings.py file config: TINYMCE_JS_URL = os.path.join(STATIC_URL, "js/tinymce/tinymce.min.js") TINYMCE_JS_ROOT = os.path.join(STATIC_ROOT, "js/tinymce") TINYMCE_SPELLCHECKER = True TINYMCE_DEFAULT_CONFIG = { "height": "500px", "width": "auto", "menubar": "file edit view insert format tools table help", "plugins": "advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code " "fullscreen insertdatetime media table paste code help wordcount spellchecker", "toolbar": "undo redo | bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft " "aligncenter alignright alignjustify | outdent indent | numlist bullist checklist | forecolor " "backcolor casechange permanentpen formatpainter removeformat | pagebreak | charmap emoticons | " "fullscreen preview save print | insertfile image media pageembed template link … -
Python, django: I made some codes but I think it takes time to perform. Is python slow? or my codes slow?
I would like to check and improve the codes I wrote because it takes time... slow probably I could wrote better... here are the codes at views.py def price_detail(request): if request.method == "POST": flight_date = request.POST.get('flight_date') direction = request.POST.get('direction') suburb = request.POST.get('suburb') no_of_passenger = request.POST.get('no_of_passenger') def price_cal(): if direction == 'Drop off To airport': return int(suburbs.get(suburb)) + ((int(no_of_passenger) * 10) - 10) else: return int(suburbs.get(suburb)) + (int(no_of_passenger) * 10) price_cal() price = str(price_cal()) p = Post(flight_date=flight_date, direction=direction, suburb=suburb, no_of_passenger=no_of_passenger, fare=price) p.save() data = { 'flight_date': flight_date, 'direction': direction, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price, } message = ''' Flight date: {} Direction: {} Suburb: {} No of passenger: {} Price: {} '''.format(data['flight_date'], data['direction'], data['suburb'], data['no_of_passenger'], data['price']) send_mail(data['flight_date'], message, '', ['sungkam3@gmail.com']) return render(request, 'basecamp/price_detail.html', {'flight_date': flight_date, 'direction': direction, 'suburb': suburb, 'no_of_passenger': no_of_passenger, 'price': price}, ) else: return render(request, 'basecamp/price_detail.html', {}) User put some information on html and inquiry about the price... views get objects from templates, work out the price and after that, save all the information into database and email to me the details user inquiried. After all this donw, views.py send information to other page (html) to show the results to User. it works fine... but the problem is … -
How to use filecmp.cmp() in Django for InMemoryUploadedFile objects?
The filecmp.cmp() method takes two arguments, path of file1 and path of file2. InMemoryUploadedFile objects won't have any path associated with them. So, what is the simplest method to compare two InMemoryUploadedFile objects? Thanks -
To display a dropdown and table/ list of the related content, Django SQL database
This is what I currently have, the first dropdown is faculty, second is the module. This is created with ajax. Now, I would like to create a table that shows all the modules and their respective details when I select a specific faculty. Let's say I selected Physics the table content will now show all the modules and their semester availability and credit unit. The dropdown and the content of the table have to be dynamic and change according to what is selected. The model would contain column faculty, modules, semester availability, and credit unit. I would appreciate any resources that will guide me in this! Thank you! -
Modifying a dropdown menu option in a form Django
I have a dropdown menu that i'm using to fill a field on a form, but, as i'm just starting with django and html, i'm using another form to edit and update the data of the previous form. But i cant make the dropdown menu to work on that second form. The model: class Orden(models.Model): STATUS = ( ('En espera', 'En espera'), ('En proceso', 'En proceso'), ('Terminado', 'Terminado'), ('Entregado', 'Entregado'), ) num_orden = models.CharField(max_length=20, default='') fechain = models.CharField(max_length=30, default='') fechaout = models.CharField(max_length=30, default='') instrumento = models.CharField(max_length=30, default='') marca = models.CharField(max_length=20) referencia = models.CharField(max_length=30, default='') serial = models.CharField(max_length=15, default='') encargado = models.CharField(max_length=50, default='') abono = models.CharField(max_length=15, default='') procesos = models.TextField(default='') estado = models.CharField(max_length=50, null=True, choices=STATUS) # <--- This one client = models.ForeignKey(Cliente, on_delete=models.CASCADE, default='', related_name="client") The view related to the first form: def ordenfill(request, client_id): if request.method == 'POST': orden = ordenForm(request.POST) if orden.is_valid(): orden.instance.client_id = client_id init = orden.save() return redirect('ordenview', id=init.id) else: orden = ordenForm() client = Cliente.objects.get(id=client_id) context = { 'orden': orden, 'client': client, } return render(request, 'ordenfill.html', context) The template part asociated to that dropdown menu: <form method="POST" class="post-form" action="{% url 'ordenfill' client.id %}"> {% csrf_token %} <div class="container"> <br> . . . <div class="form-group row"> <label … -
I would like to pass an array in django
I would like to pass an array in django {% include '/blocks/block-products-carousel.html' with groups= [ {title: 'All', active: true}, {title: 'Power Tools', active: false}, {title: 'Hand Tools', active: false}, {title: 'Plumbing', active: false}, ], -
Linux partition sizes for a locally-deployed (via docker) django web application with postres database
I plan to deploy, via docker, a django web application with postgres database in a local machine within a local network. I believe that docker volumes live in the /var/lib/docker/volumes directory of the host computer. My question is: I suppose this means that when I prepare the host machine, I will have to allot a large portion to the root directory? Are there ideal sizes for the partitions of the host machine? (root, swap, home) This may sound trivial, but I would like to get confirmation before I start working on the deployment. Thanks so much. -
How can i group by all data according to model in DRF?
Currently, I am working on a DFR project where can successfully get all data but i need some modify with the json data. Here Is the code class PermissionSerializers(serializers.ModelSerializer): class Meta: model = Permission fields = ['id', 'name', 'codename'] def to_representation(self, instance): return { 'model': instance.content_type.name, 'data' :{ 'id': instance.id, 'name': instance.name, 'codename': instance.codename, } } And i get this JSON format, { "next": "http://127.0.0.1:8000/en/ga/api-version/common/admin/permissions/?page=4", "previous": "http://127.0.0.1:8000/en/ga/api-version/common/admin/permissions/?page=2", "total": 33, "page": 3, "page_size": 10, "results": [ { "model": "user", "data": { "id": 25, "name": "Can add user", "codename": "add_user" } }, { "model": "user", "data": { "id": 29, "name": "Admistrative Access", "codename": "admin_access" } }, But I want to modify with something like this which has model name on top and then all available data inside a dictionary: { "model": "user", "data": { "id": 26, "name": "Can change user", "codename": "change_user" }, { "id": 25, "name": "Can add user", "codename": "add_user" }, }, -
How to change Django project settings dynamically for production and staging servers
In my current project, I have two servers: production and staging. The staging server uses the default MySQL Django connector. The production server uses a custom connector for MariaDB. The information from the database is retrieved through raw queries. I can't use ORM for this project. Both staging and production are connected to the project's git repository. If I push a commit with the specific settings for the staging server, when I git pull from production server it won't work and vice versa. I need to create a mechanism that detects if the server is production or staging and based on that it executes the specific code for MariaDB or MySQL. The conflicting files are: settings.py (no explanations needed) and db.py (contains all the logic of the database, here are implemented the functions that are responsible for making queries to the database). STAGING SERVER db.py (truncated): #!/usr/bin/python from django.db import connection import re from collections import namedtuple def get_genome_id_from_start_value(start): results = [] cursor = connection.cursor() cursor.execute("SELECT record_id FROM `db-dummy`.g_info WHERE start = %s", ('{}%'.format(start),)) columns = [column[0] for column in cursor.description] results = [] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) return results[0]['record_id'] settings.py (truncated): DATABASES = { 'default': { 'ENGINE': … -
Django login with rest framework
While working with the rest framework and frontend native client, I need to log in with both native clients and directly to the API endpoint for development and testing purpose. Native client login requires token authentication and direct API login requires session authentication. But if I put both in settings.py as default I get csrf error from the native client and if I remove session auth I am not able to login directly to API (I can still log in to the admin console). My settings .py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.AllowAny', ) } What can be done to log in from both for development and testing? Any help? -
WebSocket drops connection django channels redis docker compose
tried to connect redis with my app on docker compose and django. It starts but when i try to use websockets it falls with exception: web_1 | WebSocket DISCONNECT /comments/3/ [172.23.0.1:57474] web_1 | Exception inside application: [Errno -3] Try again web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/channels/staticfiles.py", line 44, in __call__ web_1 | return await self.application(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 71, in __call__ web_1 | return await application(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 47, in __call__ web_1 | return await self.inner(dict(scope, cookies=cookies), receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/sessions.py", line 254, in __call__ web_1 | return await self.inner(wrapper.scope, receive, wrapper.send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/auth.py", line 181, in __call__ web_1 | return await super().__call__(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/middleware.py", line 26, in __call__ web_1 | return await self.inner(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/routing.py", line 150, in __call__ web_1 | return await application( web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 94, in app web_1 | return await consumer(scope, receive, send) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 58, in __call__ web_1 | await await_many_dispatch( web_1 | File "/usr/local/lib/python3.9/site-packages/channels/utils.py", line 51, in await_many_dispatch web_1 | await dispatch(result) web_1 | File "/usr/local/lib/python3.9/site-packages/channels/consumer.py", line 73, in dispatch web_1 | … -
Celery showing django's runserver logs instead of celery logs
I have a dockerized Django project and everything works fine because Celery keeps displaying runserver logs instead of celery logs. Here's my docker-compose.yml: version: "3.8" services: api: container_name: api restart: always build: . networks: - API_NETWORK depends_on: - redis - database ports: - "8000:8000" env_file: - ./.env command: bash -c /entrypoint.sh database: container_name: postgres restart: always image: postgres:latest networks: - API_NETWORK volumes: - pgdata:/var/lib/postgresql/data/ environment: - POSTGRES_HOST_AUTH_METHOD=trust redis: container_name: redis image: redis:latest networks: - API_NETWORK celery: container_name: celery restart: always build: . networks: - API_NETWORK depends_on: - api - redis - database env_file: - ./.env command: celery -A dir_name worker -l debug celery-beat: container_name: celery-beat restart: always build: . networks: - API_NETWORK depends_on: - api - redis - database env_file: - ./.env command: celery -A dir_name beat -l debug --scheduler django_celery_beat.schedulers:DatabaseScheduler volumes: pgdata: networks: API_NETWORK: name: API_NETWORK driver: bridge ...and here's my Dockerfile: FROM python:3.9-slim-buster ENV PYTHONUNBUFFERED 1 ENV PYTHONDONTWRITEBYTECODE 1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ build-essential git gcc python3-dev \ && python -m pip install --upgrade pip RUN mkdir /dir_name WORKDIR /dir_name COPY . /dir_name RUN pip install -r ./requirements.txt RUN chmod +x ./entrypoint.sh ENTRYPOINT ["sh", "./entrypoint.sh"] The issue is instead of getting proper … -
Undefined Path In Django
I am working on a django application and everything is working fine except I am getting an error Not Found: /about-us/undefined when I visit the url 127.0.0.1:8000/about-us/ With a view as below the error is not showing: def about_us(request): if request.method == 'GET': return HttpResponse('<h1>About Page</h1>') But when I render an HTML template as shown below then the error shows def home(request): if request.method == 'GET': return render(request, 'website_files/index.html', {'home' : True}) website.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('about-us/', views.about_us, name="about-us"), path('why_us/', views.why_us, name="why_us"), path('out_team/', views.out_team, name="out_team"), path('it_solutions/', views.it_solutions, name="it_solutions"), path('it_solutions/it_management_services', views.it_management_services, name="it_management_services"), path('it_solutions/cyber_security_services', views.cyber_security_services, name="cyber_security_services"), path('it_solutions/software_dev_services', views.software_dev_services, name="software_dev_services"), path('it_solutions/networking_and_cloud_services', views.networking_services, name="networking_and_cloud_services"), path('it_solutions/it_consultations', views.consulting_services, name="it_consultations"), path('it_solutions/data_backup_and_recovery', views.backup_services, name="data_backup_and_recovery"), path('it_solutions/email_hosting', views.email_hosting, name="email_hosting"), path('it_solutions/web_hosting', views.web_hosting, name="web_hosting"), path('stories', views.blogging, name="stories"), path('contact_us', views.contact, name="contact_us"), path('find_out', views.find_out, name="find_out"), path('request_quote', views.get_quote, name="request_quote"), ] main urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # path('admin/', admin.site.urls), path('', include('website.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) What am I missing? You assistance will greatly appriciated. -
Local Django server is incredibly slow
I am trying to connect with a Django dev server running locally. HTTP requests take a minute or more! Looking for a way to speed it up. According to Chrome network monitor, Waiting (TTFB) on one of the URLs is 5.5 minutes. Similarly bad performance occurs using Firefox screenshot of chrome network monitor Server side error/logs: HTTP GET /sources/ 200 [151.03, 127.0.0.1:49420] <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90350> Application instance <Task pending coro=<AsgiHandler.__call__() running at .../djangoenv377/lib/python3.7/site-packages/channels/http.py:192> wait_for=<Future pending cb=[_chain_future.<locals>._call_check_cancel() at .../.pyenv/versions/3.7.7/lib/python3.7/asyncio/futures.py:351, <TaskWakeupMethWrapper object at 0x7fccf5c4bf50>()]>> for connection <WebRequest at 0x7fccf5f41690 method=GET uri=/sources/ clientproto=HTTP/1.1> took too long to shut down and was killed. <generator object source_list.<locals>.<genexpr> at 0x7fccf6a90250> HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] When refreshing, these two lines happen pretty instantaneously: HTTP GET /sources/ 200 [332.32, 127.0.0.1:49846] <generator object source_list.<locals>.<genexpr> at 0x7fccf695e350> And it takes a while for the Application instance <Task pending coro=<AsgiHandler.__call__()... error to occur. Environment info: OS: Ubuntu 20.04.2 LTS Python: 3.7.7 channels==2.4.0 channels-redis==2.4.2 celery==4.4.7 redis==3.5.3 Twisted==20.3.0 websocket-client==0.57.0 uWSGI==2.0.18 daphne==2.4.1 defusedxml==0.6.0 Django==2.2.7 django-celery==3.3.1 django-celery-results==1.2.1 django-channels-panel==0.0.5 djangorestframework==3.11.0 asgi-redis==1.4.3 asgiref==3.3.1 async-timeout==3.0.1 I've tried mixing and matching different pip package versions with no success. I've tried using debug=False with no success. The annoying thing is that this application works as expected … -
Nginx wont update static files for Django
I haveNginx + Gunicorn + Django server deployed on Ubuntu. It running with Debug=False settings and everything works fine. CSS is loaded fine, JS works as well. But when I try to update the css file or js file, the changes I made are not reflected when I run the server. I tried to update an old static files, also static file created after collectstatic command, I also tried clean collectstatic as well as systemctl restart nginx (and gunicorn). I also cleaned my cache in browser. But when I look a page source code, this changes are not there. this is how my nginx config looks like server { listen 80; server_name mediadbin.n-media.co.jp; client_max_body_size 500M; access_log /home/mediaroot/mediadbin/logs/nginx-access.log; error_log /home/mediaroot/mediadbin/logs/nginx-error.log; server_tokens off; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; } location /static { $ I TRIED APPLY CHANGES HERE <- NOTHING happens alias /home/mediaroot/mediadbin/mediadbin/static; } location /media { alias /home/mediaroot/mediadbin/mediadbin/media; } include global404; } HERE is my gunicorn config #!/bin/bash # Name of the application NAME="mediadbin" # Django project directory DJANGODIR=/home/mediaroot/mediadbin/mediadbin # how many worker processes should Gunicorn spawn NUM_WORKERS= $(( $(nproc) * 2 + 1 )) # … -
Keycloak Integration with Python
Does anybody know a solid tutorial of how to connect Keycloak to a Django backend? I tried to use this one: https://blog.jonharrington.org/static/integrate-django-with-keycloak But apart from the Keycloak part, the Django setup is not as easy as it made it seem. Then, I moved to this one: https://sairamkrish.medium.com/keycloak-integration-part-3-integration-with-python-django-backend-5dac3b4a8e4e And again, I got stuck in the technicality with python. Both descriptions seem so vague to me. Did anybody manage to it with the tutorials out there? -
How can I use Django signals outside the Django application?
I have a gRPC server running that responds to external requests. I also have a Django app that takes care of all other web related events. I want to send a signal to the Django app when the gRPC server receives requests. (The gRPC system was already in place. The Django app is an extension) Since using Django signals outside the app doesn't work (no context), I want another way to send some kind of notification to the app. I am aware that this is a very unlikely scenario. -
Celery Picking alternative task
While learning and implementing CELERY I noticed celery is picking my task alternatively, which means if I do the same event multiple times, for 1st-time celery doesn't pick the task, and for the second time it picks and completes the task, this goes for 3rd and 4th time and so on... Here is my output - here is my celery app - I am calling my task defined in my tasks.py (sending email for now) from my views.py, for checking, I am calling task in my list function of viewset. so when I go to URL for 1st time nothing happens and on the second visit, the mail is sent. Using rabbitmq as a broker. also have Daemonized celery. The first image is by using a manual command. WHAT AM I MISSING OR WHAT WRONG HAVE I DONE ?? -
Can't use CROS in django on production
I use nginx, gunicorn and systemd to deploy my Dajngo application on a virtual private server. and I have set all settings for CROS but it doesn't work. this is my dajngo setting CROS related parts: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'shop', 'user', 'mag', ] 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', 'corsheaders.middleware.CorsMiddleware', ] and this is my Nginx server configuration: server { listen 80; server_name 116.203.231.211 127.0.0.1 localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /www/public_html/stage/; } location / { proxy_pass http://127.0.0.1:8000; # address of the Node.js instance } location /media/ { autoindex on; alias /webapps/stage/media/; } location /api/ { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } I have also tried adding the headers like below to the nginx server but it didn't worked if ($request_method = 'GET') { # 1. Allow any origin add_header 'Access-Control-Allow-Origin' '*' always; # 2. Credentials can be cookies, authorization headers or TLS client certificates add_header 'Access-Control-Allow-Credentials' 'true'; # 3. What methods should be allowed when accessing the resource in response to a preflight request add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, PUT, DELETE, OPTIONS'; … -
Can't add an anchor tag using a url path to another Django template
I am trying to add an anchor tag using a url in Django like below: layout.html {% extends "tasks/layout.html" %} {% block body %} <h1>Tasks</h1> <ul> {% for task in tasks %} <li>{{ task }}</li> {% endfor %} </ul> <a href="{% url 'add' %}">Add Tasks</a> {% endblock %} Views.py from django.shortcuts import render tasks = ["foo", "bar", "baz"] # Create your views here. def index(request): return render(request, "tasks/index.html", { "tasks": tasks }) def add(request): return render(request, "tasks/add.html") urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] However, I keep getting the following error when setting the href using the url method, but not when I hardcode the path: Error during template rendering In template C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\templates\tasks\layout.html, error at line 0 'set' object is not reversible 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <title>Tasks</title> 5 </head> 6 <body> 7 {% block body %} 8 {% endblock %} 9 </body> 10 </html> Traceback Switch to copy-and-paste view C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\Users\User\Desktop\Coding\CS50W\Week3-Django\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\Users\User\Desktop\Coding\CS50W\Week3-Django\lecture3\tasks\views.py, line 6, in index … -
Django local and production database
Some days ago I deployed my first django project on heroku, now every time I want to change something and do some test, I'm switching between them commenting one and uncommenting the other ## Heroku DB #DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql', # 'NAME': 'FOO', # 'HOST': 'FOO', # 'POST': 5432, # 'USER': 'FOO', # 'PASSWORD': 'FOO', # } #} # LOCAL DATABASE DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'FOO', 'USER': 'FOO', 'PASSWORD': 'FOO', 'HOST': 'localhost', 'PORT': '5432' } } How to work with different databases without doing this, just putting all inside the dictionary. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'FOO', 'USER': 'FOO', 'PASSWORD': 'FOO', 'HOST': 'localhost', 'PORT': '5432' }, 'LOCAL': { FOOOOOO } } -
Django download a BinaryField as a CSV file
I am working with a legacy project and we need to implement a Django Admin that helps download a csv report that was stored as a BinaryField. The model is something like this: class MyModel(models.Model): csv_report = models.BinaryField(blank=True,null=True) Everything seems to being stored as expected but I have no clue how to decode the field back to a csv file for later use. I am using something like these (as an admin action on MyModelAdmin class) class MyModelAdmin(admin.ModelAdmin): ... ... actions = ["download_file",] def download_file(self, request,queryset): # just getting one for testing contents = queryset[0].csv_report encoded_data = base64.b64encode(contents).decode() with open("report.csv", "wb") as binary_file: # Write bytes to file decoded_image_data = base64.decodebytes(encoded_data) binary_file.write(decoded_image_data) response = HttpResponse(encoded_data) response['Content-Disposition'] = 'attachment; filename=report.csv' return response download_file.short_description = "file" But all I download is a scrambled csv file. I don't seem to understand if it is a problem of the format I am using to decode (.decode('utf-8') does nothing either ) PD: I know it is a bad practice to use BinaryField for this. But requirements are requirements. Nothing to do about it.