Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Usage of .to_representation() in django-rest-framework resulting a slow response for a large(1000 records) list
I have an endpoint www.exapmle.com/list?page_size=1000 sample code looks like - class TestViewSetV10(ViewSet): queryset = Test.objects.all()#.order_by("pk") serializer_class = TestSerializerV10 filterset_class = TestFilterV10 class TestSerializerV10(serializers.ModelSerializer): #pass Backend serializers is serializers.ModelSerializer, which is calling .to_representation() in the list. This is leading to a slow response, taking around 2 min. Is there any way to optimize the above-mentioned case? -
How to fetch relation table one to another via serializer? django
I have two serializers for two models (Blog and User). This is one to many relation, User can have one or more Blog. But a Blog should belong only to one User. The goal is I want to include blogs model if I will fetch the user. vice-versa API: /user/1 response: { name: 'John Doe', blogs: [ <========== include { id: 1, title: 'First Blog', }, ... so on, so forth ] ... more field } The current situation is, the UserSerializer can incude the blogs. But in BlogSerializer it cannot include the user since "BlogSerializer" is not defined. class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = "__all__" user = UserSerializer(many=True, read_only=True) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" blog = BlogSerializer(many=True, read_only=True) Do you have idea how to fix or achieve this? I'm new in Django, I would appreciate any comments or suggestions. -
Django: query parameters in the middle of the url - how?
This is a Django project and our project lead has come up with following URL-schema: <some-url>/avail?region_id=1&date=2021-01-01 ... get avail-data for given region and date <some-url>/cust?id=1/regs/ ... meaning we want the regions of customer with id 1 Now for all I know this is not really the way you normally would do it in Django, where you would define an URL as something like: <some-url>/cust/1/regs/ Furthermore I read that "query parameters are usually handled in the view" with request.query_params.get(). But if we go forward with this URLs-schema of having query parameters - even in the middle of the URL as in the 2nd case - what would be the best way of implementing it? How to set up urls.py? Another option would be to convince our lead of a better way - a more Django-ish way? How would we best define these URLs to adhere to Django conventions? -
`ValueError: %s has host bits set` while using InetAddressField in django model
I am using InetAddressField from django.netfields to store IP address in DB. I followed steps from this answer. I have following model: class MyModel(models.Model): // some fields ... ip_address = InetAddressField() objects = NetManager() I have two REST end points, one with MyModel.objects.exclude(ip_address__net_contained=subnet_mask) and another with MyModel.objects.filter(ip_address__net_contained=subnet_mask) where subnet_mask is input from UI. Now the thing is all bits for host need to be zero in subnet mask. In, 10.0.0.2/24, its 2. So it gives error as follows: ERROR [2023-06-15 20:49:41,326] [django.request] [log] [Process:2090] [Thread:139874097665792] Internal Server Error: /my_module/my_rest_endpoint Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/myapp/my_module/views.py", line 484, in my_rest_endpoint .exclude(ip_address__net_contained=subnet_mask) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 899, in exclude return self._filter_or_exclude(True, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 908, in _filter_or_exclude clone.query.add_q(~Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.6/site-packages/netfields/lookups.py", … -
Django migration issues when changing model field
we have a Model with a field such as from core import snippets from modelcluster.fields import ParentalKey, ParentalManyToManyField tags = ParentalManyToManyField( snippets.Tag, blank=True, ) we have changed the snippets import from from readiness import snippets to from core import snippets where snippets is just the same but moved to the core app getting migration errors tags was declared with a lazy reference to 'readiness.tag', but app 'readiness' isn't installed. -
Having issues running py, python3, python etc. Environment Variables correct as far as I can tell
I have used Django in the past but just got this new computer and was running though the Django tutorial a refresher. Having issues running the python manage.py runserver command. I get "Python was not foun; run....." error. I've tried py, python, python3. I have made sure my path varibles are set correctly. Not really sure what to try next. The only thing that is different on this PC than other computers Ive used is my username has been set as (username.computername) not really sure but it has messed with some code I use to get the user for file directories. I added a path variable with my full path instead of the %USERPROFILE% incase this was effecting something. Path Varibles Image of CMD I have also looked at the "Manage App Execution Aliases" and python is clicked to on. Thanks in advance for any help here is what I'm getting from CMD: `C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>py --version Python 3.11.4 C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python --version Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python3 --version Python was not found; run without arguments to install from the Microsoft Store, or disable … -
Nginx ERR_SSL_PROTOCOL_ERROR
Need help setting up Ngin. I need to set up https for my service This is the service configuration events {} http { server { listen 80; listen \[::\]:443 ssl; server_name example.com localhost; # SSL-сертификаты ssl_certificate /etc/nginx/certs/example.crt; ssl_certificate_key /etc/nginx/certs/example.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; keepalive_timeout 70; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_trusted_certificate /etc/nginx/certs/ca.crt; resolver 8.8.8.8; location / { proxy_pass http://example_app:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } This is the docker-compose.yml configuration version: '3' networks: imggen_network: driver: bridge services: nginx: container_name: nginx image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/certs:/etc/nginx/certs:ro depends_on: - example_app networks: - imggen_network The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR -
Getting Docker-Compose file working on ubuntu
I have a django project running correctly with docker compose on my mac, but I want to get the docker-compose working on my linux ubuntu machine. When I run the docker-compose file on my mac everything works fine; however, I run into an issue on ubuntu where it says that port 5432 is in use. This is because: "On your Mac, you can run PostgreSQL on the host machine and use the same port (5432) without conflict because Docker for Mac uses a feature called "host networking" by default. With host networking, containers share the network stack with the host machine, allowing them to access services running on the host directly. In the case of your Docker Compose file, when you run it on your Mac with PostgreSQL running on the host on port 5432, the container can still access the PostgreSQL service on the host because it shares the network stack. The container's PostgreSQL service listens on the same port inside the container (5432) as the host's PostgreSQL service. So, when your Django application inside the container tries to connect to the database at localhost:5432, it effectively connects to the PostgreSQL service running on the host." So I modify … -
how to shrink my celery-worker docker image?
I am running Django application on ECS and I am trying to optimize the size of Docker containers. Below are my Dockerfiles that I am using to build django-app, celery-worker and celery-beat services on ECS. CMD are inserted in ECS task definition. The problem I have is that the size of celery worker container exceeds 1 GB and with enabled autoscalig it takes around 5 minutes to create new task in ECS service, to build and deploy the container. It is not a problen when deploying whole application but it is probmematic when I want to autoscale my app and I need to wait 5 minutes for new task so celery can run another tasks. Concurrency is set up to 3 and I cannot put higher number because my tasks are heavy and last around an hour (each). How can I optimize the size of celery Dockerfile and the way in is being built and deployed on ECS? Dockerfile for Django: FROM python:3.9-slim ENV DockerHOME=/home/app/web ENV GitHubToken=ghp_*** RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY . $DockerHOME RUN apt-get update && apt-get install -y git RUN pip install git+https://github.com/ByteInternet/pip-install-privates.git@master#egg=pip-install-privates # … -
My Home page doesn't work in Django and react app
I am working on a project with Django and React and I have already deployed it in Render but my Home page doesn't work. The screen is all white. The others pages work correctly. This is my urls.py in core: urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('auth/', include('djoser.social.urls')), path('api/blog/', include('apps.blog.urls')), path('api/category/', include('apps.category.urls')), path('api/contacts/', include('apps.contacts.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] And this is my Home route in React: <Route path="/" element={<Home />} /> I have tried everything including Chat GPT but I can't find the error. When I was working on debug mode the Home page worked correctly. -
Permission denied for urls paths Django + Apache + mod_wsgi
I have configured a Dajgno application to be hosted in an Apache server using mod_wsgi. I have successfuly opened the home page, but haven't been able to open others urls paths. For instance, if I try to access /pop/, it returns 403 forbidden error. Here are my code: urls.py from django.contrib import admin from django.urls import path, include from dashboard import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.NewView.as_view()), path('pop', views.PopView.as_view()), ] urlpatterns += staticfiles_urlpatterns() wsgi.py import os import sys from django.core.wsgi import get_wsgi_application path = '/home/andremou/DashboardUnicamp/unicamp/unicamp' if path not in sys.path: sys.path.append(path) #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unicamp.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "unicamp.settings" application = get_wsgi_application() .conf file <VirtualHost *:443> ServerAdmin [CENSORED] DocumentRoot [CENSORED] #ServerName [CENSORED] ServerName [CENSORED] #ServerAlias [CENSORED] ServerAlias [CENSORED] RewriteEngine On RewriteCond [CENSORED] RewriteCond [CENSORED] RewriteRule [CENSORED] Alias /dashboardteste/ /home/andremou/DashboardUnicamp/unicamp/unicamp/ # Executar o Django como usuario apache SuexecUserGroup apache apache #Header set X-Frame-Options SAMEORIGIN <Directory /home/andremou/DashboardUnicamp/unicamp/unicamp> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> # Certificados TLS/SSL SSLEngine on SSLCertificateFile /etc/httpd/conf.d/ssl/moodle.pem SSLCertificateKeyFile /etc/httpd/conf.d/ssl/moodle.key SSLCertificateChainFile /etc/httpd/conf.d/ssl/moodle_chain.crt WSGIScriptAlias /dashboardteste /home/andremou/DashboardUnicamp/unicamp/unicamp/wsgi.py WSGIDaemonProcess unicamp python-home=/home/andremou/DashboardUnicamp/my_env python-path=/home/andremou/DashboardUnicamp/unicamp WSGIProcessGroup unicamp WSGIApplicationGroup %{GLOBAL} </VirtualHost> The structure of my files: home |-andremou |-DashboardUnicamp |-my_env |-unicamp ||-dashboard | |-migrations | |-static | |-templates … -
django dynamic URL routing
so i have been trying to use single template to display multiple content for different pages in django. i have an main app called websiteappand main template as index.html if i click a link in main page it goes to another app called moviedetailthat contains a template called movie-detail. html from that template i want to display various content according to the link clicked in main page i have been trying so long i didn't find any answer what do i need to change and how i have tried int:pk and objects.get(id=pk) it doesn't work -
how can i bookmark songs in my django project with rest framework and js
I've been trying to put the favorites feature for days with django rest framework and javascript api fetch in my lyrics project but without success all the methods I'm trying don't work please help me I'm a beginner in javascript, even in api with django too. here is what I tried, where did I mow apiviews.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,permissions from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework import generics from rest_framework.response import Response from rest_framework import viewsets, status from rest_framework.decorators import action from .serializers import SongSerializer from .models import Song, User from .models import Song, Favorite class FavoritesongView(APIView): serializer_class = SongSerializer queryset = Song.objects.all() @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def favorite(self, request, id): song = self.get_object() user = request.user if user not in song.favorited_by.all(): song.favorited_by.add(user) song.save() return Response({'status': 'favorited'}) @favorite.mapping.delete def unfavorite(self, request, id=None): song = self.get_object() user = request.user if user in song.favorited_by.all(): song.favorited_by.remove(user) song.save() return Response({'status': 'unfavorited'}) api_urls from django.contrib import admin from django.urls import path from favorites.apiViews import FavoritesongView urlpatterns = [ path('songs/<int:id>/favorite/', FavoritesongView.as_view()) ] Js file function addToFavorites(songId) { fetch(`/api/songs/${songId}/favorite/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) .then(response … -
HTMX tags not activating when using locally-stored copy of source code in Django project
I have a Django project where I'm using HTMX to set up "cascading" SELECT widgets (i.e. the options listed in SELECT #2 are modified based on the user option from SELECT #1). I've confirmed that the HTMX tags in SELECT #1 are triggering as expected when I put this line in the HTML template header to pull in the HTMX code from their web site: <script src="https://unpkg.com/htmx.org@1.9.2" integrity="sha384-L6OqL9pRWyyFU3+/bjdSri+iIphTN/bvYyM37tICVyOJkWZLpP2vGn6VUEXgzg6h" crossorigin="anonymous"></script> Specifically, I can confirm the event is triggering because at this point the corresponding view for the target (create_itemid_2) is just a stub, and I see the printed message in my Powershell console. def create_itemid_2(request): print('HTMX event fired') context = {} return render(request,'create_itemid_2.html',context) So now I want to pull down the code, and use it locally in my Django project, so I'm not dependent on the external resource. The problem is, after I've done that, the event never triggers. I can even see the js file being successfully retrieved in my console (HTTP status 200, then 304 after that), but still the event never triggers. [14/Jun/2023 08:05:05] "GET /newitemid/ HTTP/1.1" 200 1652 [14/Jun/2023 08:05:05] "GET /static/htmx/htmx.min.js HTTP/1.1" 200 361101 [14/Jun/2023 08:09:50] "GET / HTTP/1.1" 200 515 [14/Jun/2023 08:09:52] "GET /newitemid/ HTTP/1.1" … -
How to optimize the filtering of queryset in ModelViewSet
I'd like to know if it's possible to optimize the following code (especially the part when event_wmode is passed as a parameter) class MessageViewSet(viewsets.ReadOnlyModelViewSet): permission_classes = (permissions.DjangoModelPermissions,) serializer_class = MessageSerializer filter_backends = [ DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter, ] filter_fields = ["device", "date", "variable", "sensor"] search_fields = [ "variable", "device__name", ] ordering_fields = "__all__" ordering = ["device", "-date"] def get_queryset(self): if self.request.user.is_superuser: return Message.objects.all() else: return Message.objects.filter(device__users=self.request.user) def list(self, request, *args, **kwargs): if not self.request.GET.get("event_wmode"): return super().list(request, *args, **kwargs) else: # remove duplicate wMode in result queryset = self.filter_queryset(self.get_queryset()) currentwMode = None excluded_pks = [] for item in reversed(queryset): if item.variable == "wMode": if item.message not in ["1", "4", "8", "9", "10"]: excluded_pks.append(item.pk) continue if currentwMode == None: currentwMode = item.message continue elif currentwMode == item.message: excluded_pks.append(item.pk) else: currentwMode = item.message queryset = queryset.exclude(pk__in=excluded_pks)[:100] # paginate the result page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) The purpose of this mode is to remove unnecessary wMode. What I want is to keep only the wMode when it changes, and only the values 1 4 8 9 and 10 (for variable=wMode only). Let's imagine I have this message sequence: [{ message: … -
django only show the highest value of m2m in template
Hej! I have a table view with multiple columns one of them contains a m2m field from the model. I dont want all values (if multiple values/entries are given for that m2m) only the highest. Example: 1890 bonbons 30 bonbons 300000 bonbons i only want to show the 300000 bonbons in that cell and not all 3 values. {% for candymarket in mall %} <td> {% for bon in candymarket.bonbon_color.all %} {{bon.value}} | {{bon.color}} {% endfor %} </td> {% endfor %} How can I filter inside the template? I still want to be able to get all values in a detail view. Is there something like {% if bon.value|length > 200 %} only with is max? Any help or link to a documentation is appreciated! :) class CandyMarket(models.Model): name = models.CharField( max_length = 500, unique = True ) bonbon= models.ManyToManyField( Bon, verbose_name = "BON", through = "BonForCandyMarket", blank = True, related_name = "bonbon_in_market" class BonForCandyMarket(models.Model): market= models.ForeignKey( Candymarket, on_delete = models.PROTECT, related_name = "bonbon_color" ) bon= models.ForeignKey( Bon, on_delete = models.PROTECT, related_name = "market_with_bonbon" ) value= models.PositiveSmallIntegerField( blank=True, null=True ) class Bon(models.Model): description_english = models.CharField( max_length = 500, unique = True ) -
Django admin url shows "table or view does not exist" while using oracledb
I am very beginner to django & oracle. Trying to connect oracledb from django using hr schema. Data is availabe to django model from database but it shows "table or view does not exist" when browsing admin url. I have the following tables on the database. DJANGO_MIGRATIONS DJANGO_CONTENT_TYPE AUTH_PERMISSION AUTH_GROUP AUTH_GROUP_PERMISSIONS AUTH_USER AUTH_USER_GROUPS AUTH_USER_USER_PERMISSIONS DJANGO_ADMIN_LOG Does django automatically migrate admin to the oracle database or I need to create them manually? -
Issues running Django Channels in Docker container
I am running Django application in Docker container. The command I use to start Django application is daphne -b 0.0.0.0 -p 8000 main.asgi:application. However, I get an error that ModuleNotFoundError: No module named 'main'. Here is my asgi.py file: import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings') django.setup() from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from modules.chat.urls import ws_urlpatterns as chat_ws_urlpatterns application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(URLRouter(chat_ws_urlpatterns)) }) What is wrong in my asgi.py configuration? -
i keep getting the error "Parameter "form" should contain a valid Django Form." when i try to create form from class in models
i need to add comment to class Course and when i try to make form from the class it show this error models.py class Course(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=7, decimal_places=2) period = models.DecimalField(max_digits=5, decimal_places=2) instructor = models.CharField(max_length=50) description = models.TextField(max_length=250) image = models.ImageField(upload_to='courses/') category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100, blank=True, null=True) user = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) created_at = models.DateField(auto_now_add=True) comment = models.ManyToManyField(Comment, related_name=("user_comment")) def __str__(self): return self.name forms.py class CommentForm(forms.ModelForm): class Meta: model = Course fields = ['comment'] views.py def comment_add(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): myform = form.save(commit=False) myform.user = request.user myform.save() return redirect('home:home') else: form = CommentForm cont = {'form': form} return render(request, 'desc.html', cont) desc.html <form method="post" class="pt-4"> {% csrf_token %} {% bootstrap_form form %} <button class="btn btn-info text-white w-100" type="submit">comment</button> </form> i tried to solve the error but i can't -
Save Django attachments from a form
Good morning, I would greatly appreciate your help, I am starting to use Django and I am making a web application that allows workers in a job to attach their documentation (files) through a form. The problem is that at the moment of pressing the submit of the form with the attached files, these are not saved, however, the name and other fields of the Charfield type are saved correctly. The only way to save the files is to attach them from the admin portal, but the idea is that each user enters from a url generated with their id that will be sent by email. Also, the files should be saved with the naming (DSR_”rut”-”name”-”filename (form label)”-0-”extension), but I still can't configure the naming of the file name instance. file, according to the label of the form. models.py: class Candidato(models.Model): nombre = models.CharField(max_length = 70, null=True, blank=True) rut = models.CharField(max_length = 10, primary_key=True) correo = models.EmailField(null=True, blank=True) centro_de_costo =models.CharField(null=True, blank=True, max_length =30, choices = cc) estado = models.IntegerField(null=True, blank=True) imagen = models.ImageField(upload_to=upload_directory_name, null=True, blank=True) certificado_antecedentes = models.FileField(upload_to=upload_directory_name, null=True, blank=True) hoja_de_vida_conductor = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_residencia = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_afp = models.FileField(upload_to=upload_directory_name, null=True, blank=True) certificado_afiliacion_salud = models.FileField(upload_to=upload_directory_name, null=True, blank=True) … -
Create new column in the existing table that has value as other column in sql using django ORM
I want to add new column in existing table that cannot be null and should have value as other column in the table. My attempt: In my django app models, I have added the new field and migrated using migrations: order_id = models.IntegerField(null=True) Ran the below sql query in database Update order_data_table SET order_id=id Again removed null=True from models so as to set it as non-nullable field and migrated Is there a better way to do? -
Search based application using Elasticsearch
I want to make search based application using python and elasticsearch. I want to create web application for this i will python but which framework i should use Django or Flask i don't know. -
Reliable django-river alternatives?
I like the workflow functionality that django-river provides, but its performance is inappropriate and occasionally it fails to find the next available choices. Do you know any fast and reliable django-river alternatives that would use Python code instead of database relations for workflow states? -
Converted PDF is downloadable on both mobile (375px) and lg devices (1024px) but it is not visible on mobile devices. It is not clickable on mobile
This is my views.py to convert html template to pdf from datetime import datetime from io import BytesIO import os from django.conf import settings from django.http import HttpResponse from frontend.views.task_shifts import valid_task_date from frontend.views.utils import * from django.contrib.auth import logout from django.shortcuts import redirect, render from django.contrib.auth import logout from xhtml2pdf import pisa from django.template.loader import get_template from django.contrib.auth.decorators import login_required def render_to_pdf(template_src, context_dict): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf_path = os.path.join( settings.BASE_DIR, 'pdf_files', 'Rating_report.pdf') pisa_status = pisa.CreatePDF(html, dest=result) if pisa_status.err: return HttpResponse('We had some error') with open(pdf_path, 'wb') as f: f.write(result.getvalue()) return pdf_path @login_required(login_url='login_user') def get_pdf(request): if request.user.is_authenticated == False or request.session.get('station_code') is None or request.session['station_code'] is None: logout(request) return redirect("login_user") if (request.method == 'POST'): date1 = request.POST.get('date') date = datetime.strptime(date1, '%Y-%m-%d').date() context = {'date': date } pdf_path = render_to_pdf('front/pdf/pdf.html', context) pdf_file = os.path.basename(pdf_path) with open(pdf_path, 'rb') as f: response = HttpResponse(f.read(), content_type='application/pdf') response['Content-Disposition'] = f'inline; filename="{pdf_file}"' return response else: messages = [] messages.append('Enter date to see pdf') return render(request, 'home.html', {'messages': messages}) and my html template is {% load custom %} {% load static %} {% block body %} <h1> pdf demo</h1> <p>for : {{date}}</p> {% endblock %} and the form to submit the … -
django.db.utils.DataBaseError: database disk image is malformed
I am getting the above error in my terminal. My db.sqlite3 file is explicitly re-assigned to plain text. I want to fix that thing. Please guide me regarding this issue. This error is with the database file. This is displaying me a warning in the db.sqlite3 file as "This file is explicitly re-assigned to plain text".