Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
wsgi.url_scheme http in docker using nginx
I am using Apache on CentOS. On this server I have a Django project with docker. There are two containers in docker (nginx and python). In the Apache I have .conf that have proxy to nginx container that is exposed on port 803. SSL is set in the Apache conf as well. ProxyPreserveHost On RequestHeader set X-Forwarded-Proto "https" RequestHeader set X-Scheme "https" ProxyPass / http://127.0.0.1:803/ ProxyPassReverse / http://127.0.0.1:803/ On the docker I have app.conf for nginx that looks like this: upstream project { server project-python:5000; } server { listen 80; server_name _; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; client_max_body_size 64M; location / { gzip_static on; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_set_header X-Scheme "https"; proxy_set_header X-Forwarded-Proto "https"; proxy_set_header X-Forwarded-Protocol "ssl"; proxy_set_header X-Forwarded-Ssl=on; proxy_set_header Host $host; proxy_pass http://project; proxy_redirect off; } } In the Dockerfile Python is exposed on port 5000 and in the docker-compose.prod.yml file for production the python is started with gunicorn with this command: gunicorn tmssms.wsgi:application --preload --bind 0.0.0.0:5000 So I have two issues. In the Django when I dump request.META I got wsgi.url_scheme that is http. The second one is that I don't even understand how nginx is communicating with gunicorn because when I set app.conf to be just … -
get data from somewhere and use boolean field
i try to write a view for getting data from somewhere that is not my database,and if this data was true mine be true and if was false mine be false too!!1any one have any idea?for example take data from another web site that you can by something,if main website let you buy,my site button be green if was close my site button be red,by the way i use Django -
Docker container not running - Docker-compose
I am trying to run a django-react app in docker containers and trying to deploy it on digital ocean. Here is my docker-compose script version: "3.9" services: web: image: "${WEB_IMAGE}" container_name: website command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - 8000:8000 env_file: .env nginx: image: "${NGINX_IMAGE}" container_name: nginx volumes: - static_volume:/usr/src/app/staticfiles - media_volume:/usr/src/app/mediafiles ports: - 80:80 depends_on: - web tensorflow-servings: image: "${TENSORFLOW_IMAGE}" container_name: tensorflow_serving ports: - 8501:8501 depends_on: - web volumes: static_volume: media_volume: Here you see nginx and web are listed, but not web. I get 502 Bad Gateway - nginx/1.21.3 error -
Gettings errors during password validation in Django serializers?
my serializer class RegistrationSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ['username', 'password'] #overwrite validate method to add some complexity to the password def validate(self, data): #here data is a ordered dict if not data: return Response("please enter name and password") password = data.get('password', '') print(password) user = CustomUser(**data) print(self.instance) messages = {} my_password_validators = [UserAttributeSimilarityValidator, MinimumLengthValidator, CommonPasswordValidator, NumericPasswordValidator] try: password_validation.validate_password(password, password_validators=my_password_validators) # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: print("here") print(e) messages['password'] = list(e.messages) # If some error then return those error if messages: raise serializers.ValidationError(messages) return super(RegistrationSerializer, self).validate(data) my error object of type 'NoneType' has no len() Password is coming alright but it is giving no length attribute, also i want to know how the username to be given to this method so that it can check password similarity with the username -
API Integration in Python
I'm doing project on COVID live tracking website, so in my project when selected particular state, type(vaccinated, cases, tests) and from selected date range i.e., from date range to date range so according to date and type mentioned the website needs to give output in form of graph. For live data I've the following API links https://data.covid19india.org/csv/latest/states.csv http://data.covid19india.org/csv/latest/cowin_vaccine_data_statewise.csv I've never done this before so I'm just confused how to start and do the project. When I asked some of friends I came to know it can be done by API integration with Python. Can anyone please help me how to start and do project in efficient way (if some links or resources provided would be great). I know my question is silly but I'm helpless how to do project. Please help me -
How to show if there are duplicates in enumerate
I have a list of stats that I keep for every team in the NFL. Every week I have a function that goes through the whole league and using enumerate, ranks teams in each stat category and then saves to a db. My question is... if multiple teams have the same value how do I give them the same rank? For example if the Patriots and Giants each average 30points a game and thats the best in the league, how do I make them both rank 1 and the next team start at 3? Below I have how I currently rank the teams now I appreciate any help or tips you can offer. for team in TeamName.objects.filter(league__name='NFL'): for count, value in enumerate(NFLTeamStats.objects.all().values( 'name', 'avg_points').order_by( '-avg_points'), start=1): if value['name'] == team.pk: avg_points_rank = count -
Models not getting registered to admin in Django?
I was just starting to make a quiz app in django when i encountered this problem. The problem is that that my models are not getting registered in the admin page. I have tried a lot of methods but nothing seemed to work. Can someone help me with this? models.py from django.db import models # Create your models here. class Quiz(models.Model): name = models.CharField(max_length=300) description = models.TextField() class Questions(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) question = models.TextField() op1 = models.CharField(max_length=200) op2 = models.CharField(max_length=200) op3 = models.CharField(max_length=200) op4 = models.CharField(max_length=200) admin.py from django.contrib import admin from .models import Quiz, Questions # Register your models here. admin.site.register(Quiz) admin.site.register(Questions) -
Csrftoken is not defined
I'm using the following code as recommended by the documentation: function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $("#formTabla").submit(function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } url : "{% url 'submit' %}", type: "POST", processData: false, contentType: false, data: { "checkboxes": formData, "datos": todosDatos }, success: function (respuesta){ } }); }); I'm getting the error "Uncaught ReferenceError: csrftoken is not defined". I understand why this happens, but I have no idea how to solve it. How and where am I supposed to define crsftoken? -
Added functionality in views.py does not work online but working in localhost. I want to add contact page
It resulted FileNotFoundError [Errno 2] No such file or directory. When I accessed the contact page in the browser like this https://sample.one/orders/contact/ (sample.one is not the true domain name) Below is my code, could someone tell me how to solve this or possible cause of the problem. Thanks a lot. Below is the code. #settings.py import os from pathlib import Path from decouple import config SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ALLOWED_HOSTS = ['sample.one', 'www.sample.one'] ROOT_URLCONF = f'{config("PROJECT_NAME")}.urls' WSGI_APPLICATION = f'{config("PROJECT_NAME")}.wsgi.application' ASGI_APPLICATION = f'{config("PROJECT_NAME")}.routing.application' PREPEND_WWW = True # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Application definition INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'category', 'accounts', 'orders', 'django.contrib.humanize', 'currencies', 'django_filters', 'storages', ] 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', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'category.context_processors.menu_links', 'carts.context_processors.counter', 'currencies.context_processors.currencies', 'carts.context_processors.country_cur', ], }, }, ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } #tell that we are using custom user usermodels AUTH_USER_MODEL = 'accounts.Account' AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { … -
how to auto fill an IntegerField in django model based on a M2M relation?
I have a model named Post, and this model has a many to many relation with another model named LikeIps. class Post(models.Model): title = models.CharField(max_length=250) summary = models.TextField() content = RichTextField() likes = models.ManyToManyField(LikeIP, related_name="liked_posts", blank=True) like_count = models.IntegerField(editable=False) def __str__(self): return self.title I want to fill likes_count field automatically base on the number of object in likes query set something like this: like_count = obj.likes.count() how should I do that? -
Unable to render a different webpage while a loop is still running Django
I would like to achieve this flow: User's face is detected by webcam in homepage The app takes the attendance of the user, display a webpage with the attendance details The attendance details page will redirect back to the homepage after few seconds with the webcam still running As of now, my app is able to take the attendance of the user but will not render to the attendance details page even though I used return render(). It will remain at the homepage with the webcam still running. Is there a way I can solve this problem or am I getting something wrong? I have tried changing the request details manually like this but its not working. request.resolver_match = resolve('/takeAttendance/') request.path='/takeAttendance/' request.path_info='/takeAttendance/' The involved code as below: views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse , StreamingHttpResponse from datetime import datetime, date import cv2 import face_recognition import numpy as np import threading foundFace = False vs = cv2.videoCapture(0) lock = threading.Lock() frame = None def videoFeed(request): return StreamingHttpResponse(getFace(request),content_type="multipart/x-mixed-replace;boundary=frame") def getFace(request): global vs,outputFrame,lock,foundFace known_face_names,known_face_encodings = getFiles() # get the image files from my project directory face_location = [] face_encoding = [] while foundFace==False: check,frame = … -
getting value from another field of that table without inputting again , Django Rest Framework
I have found an issue in a project with Django REST Framework. Where in 'POST', I'll input only 1 image file but in 'GET', I will get the file path of that image file as well as I'll get another file path of resized version of that image. class BookCover(models.Model): id = models.UUIDField(primary_key=True, max_length=36, default=uuid.uuid4) original = models.ImageField() thumbnail = ResizedImageField() Here, we'll give input to the original image, not the thumbnail. but in the table, we'll get the resized version of that original image in the thumbnail field. How can we do this? Any help would be highly appreciated. -
Django filter deep related models
In my Django 3.2 app, my models have the following relations: OperationDraft -> ForeignKey(Structure) Structure -> ForeignKey(Customer) Customer -> OneToOne(AUTH_USER_MODEL) Now, when I create a new OperationDrat I have to limit the choice of the structure based on the user of its customer. If the user is not active then I cannot select the structure. To achieve that I overrided formfield_for_foreignkey to OperationDraftAdmin class: def formfield_for_foreignkey(self, db_field, request, **kwargs): """Override formfield_for_foreignkey.""" if db_field.name == "structure": # this doesn't work kwargs["queryset"] = Structure.objects.filter(customer__user__is_active=True) # this returns 0 results even if we have a customer with such user # kwargs["queryset"] = Structure.objects.filter(customer__user__username="user480") return super().formfield_for_foreignkey(db_field, request, **kwargs) The filter should be: kwargs["queryset"] = Structure.objects.filter(customer__user__is_active=True) But it returns all the structures, even those ones with a customer bound to an inactive user. I checked documentation and to me my query is correct but not working. What am I doing wrong? -
Template syntax error Could not parse the remainder: '("images/logo.png")' from 'static("images/logo.png")'. in django-jinja template?
<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" href="{{ static 'images/logo.png' }}" alt="Company Logo"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>Hello, world!</h1> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> --> </body> </html> when including the static files in the Django-jinja template it shows an error. If I removed that line It worked. But I want to load my static files in jinja template. -
init_fs_encoding: failed to get the Python codec of the filesystem encoding
I'm running Django website on apache. Here is the tail of my httpd.conf file. ServerName 127.0.0.1:8080 # Django Project LoadFile "c:/python39/python39.dll" LoadModule wsgi_module "c:/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" #WSGIPythonHome "c:/python39/" WSGIScriptAlias / "C:/pd_videowebapp/mysite/wsgi.py" WSGIPythonPath "C:/pd_videowebapp/" <Directory "C:/pd_videowebapp/mysite/"> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static "C:/pd_videowebapp/static/" <Directory "C:/pd_videowebapp/static/"> Require all granted </Directory> And here is the tail of the error.log file: The 'Apache2.4' service is restarting. Starting the 'Apache2.4' service The 'Apache2.4' service is running. pm_winnt:notice] [pid 4472:tid 420] AH00455: Apache/2.4.51 (Win64) mod_wsgi/4.9.0 Python/3.9 configured -- resuming normal operations [Wed Oct 13 08:31:28.026005 2021] [mpm_winnt:notice] [pid 4472:tid 420] AH00456: Apache Lounge VS16 Server built: Oct 7 2021 16:27:02 [Wed Oct 13 08:31:28.026005 2021] [core:notice] [pid 4472:tid 420] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Wed Oct 13 08:31:28.041641 2021] [mpm_winnt:notice] [pid 4472:tid 420] AH00418: Parent: Created child process 2676 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Python39' sys.base_exec_prefix = 'C:\\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Python39' sys.exec_prefix = 'C:\\Python39' sys.path = [ 'C:\\Python39\\python39.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get … -
How Do I Create a User Profile Update View/Form?
I trying to update the user profile but I can't get that what mistake I do here. #forms.py class AddStudentUserForm(forms.ModelForm): class Meta: model = User fields = ["username", "first_name", "last_name"] class AddStudentStaffForm(forms.ModelForm): class Meta: model = Staff fields = ["gender", "dob", "mob", "img"] #views.py def editProfile(request, user, id): if request.POST: staffform = AddStudentStaffForm(request.POST or None, request.FILES or None, instance=request.user.staff_profile) userform = AddStudentUserForm(data=request.POST, instance=request.user) if staffform.is_valid(): staffform.save() if userform.is_valid(): userform.save() return redirect(profile,user) return render(request, 'edit.html') #models.py class Staff(models.Model): Male = 'Male' Female = 'Female' Other = 'Other' GENDER_CHOICE = ( (Male, 'Male'), (Female, 'Female'), (Other, 'Other') ) id = models.AutoField(primary_key=True) admin = models.OneToOneField(User, related_name='staff_profile', on_delete=models.CASCADE) gender = models.CharField(max_length=10, choices=GENDER_CHOICE, default=Male) dob = models.DateField(auto_now_add=False, blank=True, null=True, default=None) mob = models.IntegerField(blank=True, null=True, default=None) img = models.ImageField(upload_to='staff/', blank="True", null="True") objects = models.Manager() @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Staff.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.staff_profile.save() def __str__(self): return self.gender I started to create a Student Management System project. But I faced some difficulties to develop it. I trying lot of to solve these problem but since I can't solve that. Here if I want to update the Staff model fields like gender, dob, mob it will updated successfully but when … -
Django Admin Page not found when including MEDIA_ROOT setting
this is my first question so please point me to the right direction in case I miss something of importance ☺️ So my problem is the following: I'm currently creating a website with Django, which is supposed to list a variety of projects from the database. Each project has a picture associated with it. The path to this picture is saved in the database (each picture is added as models.ImageField() to the projects model). In order to serve them, I added MEDIA_ROOT = os.path.join(BASE_DIR, 'main/media') to my settings.py and added the following snippet to my urlpatternsin urls.py: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now to the crux of it: Everything works fine, except I can't open my admin panel now. The media files are served as expected in the projects overview, but at soon as I try to open the /admin page, I get following error message: Page not found (404) “/Users/.../main/media/admin” does not exist Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: django.views.static.serve as soon as I remove + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) from my url patterns, the admin page works fine again, however the media files are not served anymore. Can someone show me what I've broken here? Thank you very much! -
Django: Override inherited field options
I am working with Django 3.2 and I would like to create an abstract class with 2 fields whose default values (or their blank attribute) could change in each of the child classes. # behaviors.py from django.db import models from colorfield.fields import ColorField class Representable(models.Model): color = ColorField(_("color in the app"), blank=True) icon = models.CharField(_("icon in the app"), max_length=50, blank=True) class Meta: abstract = True # models.py from django.db import models from .behaviors import Representable class Item(Representable, models.Model): name = models.CharField(_("name"), max_length=50, blank=False) # color couldn't be blank # icon couldn't be blank class Meta: verbose_name = _("item") verbose_name_plural = _("items") class Tag(Representable, models.Model): name = models.CharField(_("name"), max_length=200, blank=False, unique=True) # color default value shoud be #00AEC7 (but could be blank) # icon default value shoud be mdi-label (but could be blank) class Meta: verbose_name = _("tag") verbose_name_plural = _("tags") Any ideas? -
sort by using radio button is not working django
I have a web page as shown below, so when I click on any 1 of my radio button, my url will show what I have click but, my data table won't sort in ascending order according to what I have selected, how do I fix this issue and how do I make it so that when I use the search bar and filter the page, it will still be sort in ascending order? views.py @login_required() def ViewMCO(request): search_post = request.GET.get('q') if (search_post is not None) and search_post: allusername = Photo.objects.filter(Q(reception__icontains=search_post) | Q(partno__icontains=search_post) | Q( Customername__icontains=search_post) | Q(mcoNum__icontains=search_post) | Q(status__icontains=search_post) | Q(serialno__icontains=search_post)) if not allusername: allusername = Photo.objects.all().order_by("-Datetime") else: allusername = Photo.objects.all().order_by("-Datetime") # The newest submitted log data will appear at the top page = request.GET.get('page') paginator = Paginator(allusername, 6) try: allusername = paginator.page(page) except PageNotAnInteger: allusername = paginator.page(1) except EmptyPage: allusername = paginator.page(paginator.num_pages) context = {'allusername': allusername, 'query': search_post} return render(request, 'ViewMCO.html', context) ViewMCO.html {% extends "customerbase.html" %} {% block content %} <style> table { border-collapse:separate; border:solid black 1px; border-radius:6px; -moz-border-radius:6px; } td, th { border-left:solid black 1px; border-top:solid black 1px; } th { border-top: none; } td:first-child, th:first-child { border-left: none; } .pagination a { padding: 10px; } … -
Sign up for membership in Django City, create admin authentication process
Currently, it is set to return to the first screen of the program when membership registration is completed in Django. However, since anyone can sign up and view information within the program, I want to make it possible to access the program's first page only after the administrator approves it when someone completes membership registration. As a result of Googling, only email verification was found, so I had to ask a question. There seems to be no admin authentication process provided by Django. Are there any similar examples or methods? -
CSRF Token problem when I add dropzone to an existing form in Django
I'm working with a Django form using dropzone to upload images. But I don't want to add the dropzone to the entire form, just to a div of it. Here is the template: {% extends 'base.html' %} {% load static %} {% load i18n %} {% block content %} <h6>UPLOAD MULTIPLE IMAGES NOW</h6> <br> <div class="formdiv" style="width:100%"> <form enctype="multipart/form-data" action="upload/" methd="POST"> {% csrf_token %} <fieldset> <label for="yourname">Yourname <input type="text" value="name" /> </label> <div class="dropzone dz" id="my-dropzone"> <div class="dz-message" data-dz-message><span>{% trans "Drop here or click to upload" %}</span></div> <div class="fallback"> <input name="file" type="file" multiple /> </div> </div> </fieldset> </form> </div> {% endblock %} The problem is that when I try to upload any image I get a Forbidden error message with the following text: CSRF token missing or incorrect. Notice that if I remove the class="dropzone dz" id="my-dropzone" from the div and I put it inside the <form> tag instead, everything will work. The problem began exactly when I moved dropzone in a div because I didn't want it to apply to the whole form. Here is my dropzone configuration code: Dropzone.autoDiscover=false; const myDropzone = new Dropzone('#my-dropzone',{ url:'upload/', maxFiles:15, maxFilesize:5, // 5 mb max //parallelUploads:2, // if image is horizontal, then … -
Celery Optimization with ECS Fargate
I'm trying to understand the most efficient way to scale celery workers in AWS ECS Fargate. If I'm trying to do a large data-add (from files), I want the data to written to the database as fast as possible. From what I understand, my options to try to make these tasks complete quicker: • I can run the celery worker concurrently with the -c option • I can run multiple tasks in ECS service • I can run multiple celery services in ECS cluster • I can increase the CPU/Memory of the ECS task Which option/combination would be the quickest? Which option would be the cheapest? -
'PdfFileWriter' object has no attribute 'seek'
I was trying to add password protection with pdf files, encounters this error, following are my code def generate_pdf(request): queryset = Subscription.objects.all() html_string = render_to_string('super_admin/member_report_pdf.html', {'object_list': queryset}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'rb') inputpdf = PyPDF2.PdfFileReader(output) pages_no = inputpdf.numPages output = PyPDF2.PdfFileWriter() for i in range(pages_no): inputpdf = PyPDF2.PdfFileReader(output) output.addPage(inputpdf.getPage(i)) output.encrypt('pass') with open("member.pdf", "wb") as outputStream: response.write(outputStream) return response seeking help to sort out this error, thanks -
Django download file button takes in path
I am creating an app that allows users to convert their .ifc (3D model) files into other data forms (.xlsx, filtered .xlsx, json). I have managed to implement the upload part, but now I am not sure about the download. I would like to create a "download" button that takes in the users desired download path (maybe even file name). When I have the path I can start my conversion function with the last uploaded file. def model_form_download(request): if request.method == 'POST': download_path = ??? #How to take in the user defined upload path? last_model = Document.objects.latest("uploaded_at") last_model_name = last_model.document.name MODEL_DIR = Path(MEDIA_DIR) / last_model_name model = parser(MODEL_DIR) xlsx_name = Path(last_model_name).stem XLS_DIR = Path(download_path) / (xlsx_name + '.xlsx') model[1].to_excel(XLS_DIR) return render(request, 'core/model_form_download.html') return render(request, 'core/model_form_download.html') The extra question here is how to take in the user choice of prefered conversion format and use in this view function? -
Google Dev Tools
Hello I was wondering why Google Dev tools is loading the wrong CSS script when working on responsive design @media screen and (max-width:375px) { ... #name{ font-size: calc(.8rem + .1vw); } ... } @media screen and (max-width:480px) { ... #name{ font-size: calc(1rem + .1vw); } ... } when running the google dev tools it runs the second query rathenter image description hereer