Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
docker-compose doesn't mount volumes correct for django container
Running Docker on Windows 10 with WSL 2 Ubuntu on it. I have the following Dockerfile: FROM ubuntu #base directory ENV HOME /root #subdirectory name for the REST project ENV PROJECT_NAME django_project #subdirectory name of the users app ENV APP_NAME users #set the working directory WORKDIR $HOME #install Python 3, the Django REST framework and the Cassandra Python driver RUN apt-get update RUN apt -y install python3-pip 2> /dev/null RUN pip3 install djangorestframework RUN pip3 install cassandra-driver #initialize the project (blank project) and creates a folder called $PROJECT_NAME #with manager.py on its root directory RUN django-admin startproject $PROJECT_NAME . #install an app in the project and create a folder named after it RUN python3 manage.py startapp $APP_NAME ENV CASSANDRA_SEEDS cas1 ENTRYPOINT ["python3","manage.py", "runserver", "0.0.0.0:8000"] I build a image with docker build -t django-img . and then I have the following .yaml: version: '3' services: django_c: container_name: django_c image: django-img environment: - CASSANDRA_SEEDS='cas1' ports: - '8000:8000' volumes: - /mnt/c/Users/claud/docker-env/django/django_project:/django_project When I run docker-compose up -d inside django-project folder (.yml and Dockerfile are there), I get the container running, but I can't see in the host any file from the container. If I run ls in the container, however, I see all … -
ERR_EMPTY_RESPONSE - Docker-Compose - Windows -Django
I just recently moved to windows 10 from linux and am now trying to run a dockerized django web-application but with no success. I am working with docker-compose and when I run docker-compose up, I can see the container running but the browser shows the following message: This page isn’t working 127.0.0.1 didn’t send any data. ERR_EMPTY_RESPONSE I receive the same response when using 0.0.0.0 This is my Dockerfile: # pull the official base image FROM python:3 RUN mkdir /app # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies COPY ./requirements.txt /app RUN pip install -r requirements.txt # add project ADD . /app and this is my docker-compose.yml version: "3" services: backend: build: context: . dockerfile: Dockerfile ports: - 8000:8000 volumes: - .:\app command: python manage.py runserver This is a windows specific issues it appears as when I run it on my linux machine, everything works fine. Previous questions on the topic indicated that it's a port mapping issue in Windows (e.g., https://stackoverflow.com/a/65721397/6713085) However, I have not been able to solve it. Do you have any suggestions? Thanks in advance for any help. -
How to query all model objects except the ones that already are in another model?
I am working on a Django application. I have 2 models relevant to the question: class Quiz(models.Model): """ Represents a Quiz for a `Module`. It will have a `name` """ name = models.CharField(max_length=200) user = models.ManyToManyField('cme.Bussines', related_name='quizes', through='UserQuiz', through_fields=('quiz', 'user')) def __str__(self) -> str: return f'{self.name}' class Trio(models.Model): """ Represents the content for a Module. Each `Trio` will have, as it's name says, 3 content fields, plus the `Module` it belongs to. It will have a `file`, a `video` (which will be a URL to a YT video), and a `quiz` (which will be key to `Quiz`) """ file = models.FileField(upload_to='legacy/classes/', max_length=254) quiz = models.ForeignKey(Quiz, on_delete=models.SET_NULL, related_name='trios', null=True, blank=True) video = models.URLField() module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='trios') user = models.ManyToManyField('cme.Bussines', related_name='trios', through='UserTrio', through_fields=('trio', 'user')) def __str__(self) -> str: return f'Trio {self.id} de {self.module}' I want to query all the Quizzes that are not in quiz field of Trio. Is there a way of doing this? -
'rest_framework_nested.routers' error in Docker only
I am trying to deploy a Django app through docker but am stumped at this problem. When I run my application locally, I have no problems but when I deploy to Docker I get this error: AttributeError: module 'rest_framework_nested.routers' has no attribute 'NestedDefaultRouter' The last lines of the stack trace looks like this: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/= /app/store/urls.py", line 13, in <module> modules_router = routers.NestedDefaultRouter(router, 'modules', lookup='module') AttributeError: module 'rest_framework_nested.routers' has no attribute 'NestedDefaultRouter' The file where the error emanates from looks like this: from django.urls import path, include from rest_framework.routers import DefaultRouter from rest_framework_nested import routers from . import views router = DefaultRouter() router.register('modules', views.ModuleViewSet, basename='modules') modules_router = routers.NestedDefaultRouter(router, 'modules', lookup='module') My Dockerfile looks as follows: FROM python:3.9.9-slim #Set up user RUN apt-get update RUN apt-get -y install sudo RUN addgroup app && adduser -system app -ingroup app USER app WORKDIR = /app #Environment settings` ENV PYTHONUNBUFFERED=1 #Install MySQL and dependencies RUN sudo apt-get -y install python3.9-dev RUN sudo … -
How to make 1:N orm? like comment
template.html view.py model.py result. I want to use filter orm in view.py. not like this. used 'if' in template.py and select all. How can I do this? And I tried use join sql. but It was not worked. -
how to customize the image filed returned by UpdateView
i use the UpdateView to update the products informations in my future webstore in my temblate . when i open my template i find a that it renders me the image link edit_product.html <form method="post"> <div class="form-group"> <label>Name</label> {{form.name}} </div> <div class="form-group"> <label>Description</label> {{form.description}} </div> <div class="form-group"> <label>Price</label> {{form.nominal_price}} </div> <div class="form-group"> <label>Image</label> <img src="{{form.instance.photo.url}}" width="200"/> </div> <div class="form-group"> {{form.photo}} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> output <form method="post"> <div class="form-group"> <label>Name</label> <input type="text" name="name" value="flawless legs" maxlength="255" required="" id="id_name"> </div> <div class="form-group"> <label>Description</label> <textarea name="description" cols="40" rows="10" required="" id="id_description">Epilateur de jambes pour femmes</textarea> </div> <div class="form-group"> <label>Price</label> <input type="number" name="nominal_price" value="199" min="0" required="" id="id_nominal_price"> </div> <div class="form-group"> <label>Image</label> <img src="/media/products/images/449165_ALTMORE2.jpeg" width="200"> </div> <div class="form-group"> Currently: <a href="/media/products/images/449165_ALTMORE2.jpeg">products/images/449165_ALTMORE2.jpeg</a><br> Change: <input type="file" name="photo" accept="image/*" id="id_photo"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> what should i do to remove this Currently: <a href="/media/products/images/449165_ALTMORE2.jpeg">products/images/449165_ALTMORE2.jpeg</a><br> -
Django form regrouping - How can I regroup a field form queryset like I would do in a template?
I have a Django form for a model called AvailabilityRequested that has a ManyToMany with another model called Event. class Event(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date = models.DateField(blank=True, null=True) ... class AvailabilityRequested(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) event = models.ManyToManyField(Event, blank=True) position = models.OneToOneField(JobPosition, blank=True, on_delete=models.CASCADE, related_name='availability_requested', null=True) class AvailabilityRequestedForm(forms.ModelForm): class Meta: model = AvailabilityRequested fields = ['event'] def __init__(self, *args, **kwargs): self.project = kwargs.pop('project') super(AvailabilityRequestedForm, self).__init__(*args, **kwargs) self.fields['event'].widget = CheckboxSelectMultiple() self.fields['event'].to_field_name = "event_name" #event.event_name.name self.fields['event'].queryset = self.project.jobproject_events.order_by('date') I built the form and it works fine, however I am trying to now render the events in the AvailabilityRequestedForm in a specific way inside my template and that's where the problem arise. Specifically, my goal is to basically display the events grouped by date like in the picture attached. I originally managed to do achieve my goal when I wasn't using forms but just passing to the template a queryset of dates as follow context['dates'] = project.jobproject_events.order_by('date') and then using the following template logic. {% regroup dates by date as event_by_date %} <thead> <tr> {% for date in event_by_date %} <th colspan="{{ date.list | length }}" scope="col" style="border-right: 1px solid black; text-align: center;"> {{ date.grouper }}</th> {% endfor %} </tr> … -
Django Model Property in Async Function Called from Sync View
I need to convert some of my Django views to work with async functions that query data sources. I'm experiencing big performance issues as those queries are executed one by one in series. However, the task is much harder than anticipated. I've indicated below where the problems start. I'm experiencing other problems as well, however, this is by far the one that I don't have a clue on what to do. I get the following error where indicated in the code below: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async model2 is a ForeignKey property pointing to another Model. Wrapping model1.model2 inside sync_to_async() does not work. Any idea how to make this work ? async def queryFunctionAsync(param1, param2, loop): model1 = await sync_to_async(Model1.objects.get)(pk=param1) model2 = model1.model2 # This is where the error is generated def exampleView(request): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) data = async_to_sync(queryFunctionAsync)(param1, param2, loop) loop.close() -
How can I separate categories in different pages in Python and Django?
I need help with my e-commerce website project. I will have 5 categories in the dropdown menu. I want to see different categories on different pages when I click on a category in a dropdown menu. Now I see all products on the home page and when I click on a category as BOOKS I see books on the home page but I don't want it. I want to use the home page for ads and when I click on a category, I want to see it on a different page. How can I separate them? My models: class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('products_by_category', args=[self.slug]) def __str__(self): return str(self.name) # Model: Product # Model: Cart class Add(models.Model): image = models.ImageField(upload_to='add', blank=True) image1 = models.ImageField(upload_to='add', blank=True) image2 = models.ImageField(upload_to='add', blank=True) class Meta: verbose_name = 'add' verbose_name_plural = 'adds' def __str__(self): return str(self.image) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) image1 = models.ImageField(upload_to='product', blank=True) image2 = models.ImageField(upload_to='product', blank=True) image3 = models.ImageField(upload_to='product', blank=True) … -
How to make a left join in django queryset
I have two models and I need to do a left join operation I tried some solutions, but wihout success yet Models class SmdRepairIn(models.Model): sum_ymd = models.DateField(blank=True, null=True) line_nm = models.CharField(max_length=20, blank=True, null=True) model_code = models.CharField(max_length=20, blank=True, null=True) class SmdRepairOut(models.Model): repair_in_id = models.CharField(max_length=20, blank=True, null=True) repairman_out = models.CharField(max_length=30, blank=True, null=True) SMDRepairIn.id == SmdRepairOut.repair_in_id I want to retrieve the correspondent query result: select A.*, B.repairman_out from SmdRepairIn as A left join (select repairman_out from SmdRepairOut) B on (A.id = B.repair_in_id ) How to do it in django queryset? The expected result should be: id, sum_ymd, line_nm, model_code, repairmain_out -
How can I get image table with main table?
view.py q = Q() q &= Q(user_idx = request.user.id) portfolio_list = UserPortfolio.objects.filter(q).order_by('-idx') q &= Q(portfolio_idx = portfolio_list.values('idx')) portfolio_img_list = UserPortfolioFile.objects.filter(q).order_by('-idx') model.py class UserPortfolio(models.Model): idx = models.AutoField(primary_key=True) user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) subject = models.CharField(max_length=255) client_name = models.CharField(max_length=255) client_service = models.CharField(max_length=255) client_category = models.CharField(max_length=255) start_date = models.DateTimeField() end_date = models.DateTimeField() content = models.TextField() write_date = models.DateTimeField(auto_now = True) update_date = models.DateTimeField(auto_now = True) is_file = models.CharField(max_length=1) class Meta: managed = False db_table = 'account_user_portfolio' def portfolio_upload_to(instance, filename): nowDate = datetime.now().strftime("%Y/%m/%d") return '/'.join([str(instance.portfolio_idx.user_idx), instance.folder , nowDate, filename]) class UserPortfolioFile(models.Model): idx = models.AutoField(primary_key=True) portfolio_idx = models.ForeignKey( UserPortfolio, db_column='portfolio_idx', on_delete=models.CASCADE ) folder = 'portfolio' file = models.ImageField(upload_to=portfolio_upload_to) class Meta: managed = False db_table = 'account_user_portfolio_file' I want to get image in my image table. ex)I want to get portfolio_idx 1 to list in template But I don't know how to get. Maybe I think that is almost done. right? If not please answer. -
REACT-DJANGO Post form to an API 400 error strict-origin-when-cross-origin
I'm having a problem where when I try to post a FORM to my API it gives me this error. Request URL: http://localhost:8000/api/ Request Method: POST Status Code: 400 Bad Request Remote Address: 127.0.0.1:8000 Referrer Policy: strict-origin-when-cross-origin I did follow a tutorial to create the API and I think that may be the problem I don't even know where to start looking! I don't know where I'm messing up at and it's really frustrating! This is my REACT Post form page import axios from "axios"; import { useState, useEffect } from "react"; import { useHistory } from "react-router"; import "./createpost.css"; const CreatePost = () => { const [username, setUsername] = useState(""); const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [image, setImage] = useState(null); const [category, setCategory] = useState(""); const history = useHistory(); const AddPost = async () => { let formField = new FormData(); formField.append("title", title); formField.append("description", description); formField.append("category", category); if (image !== null) { formField.append("image", image); } await axios({ method: "post", url: "http://localhost:8000/api/", data: formField, }).then((response) => { console.log(response.data); history.push("/"); }); }; useEffect(() => { if (localStorage.getItem("token") === null) { } else { fetch("http://127.0.0.1:8000/api/v1/users/auth/user/", { method: "GET", headers: { "Content-Type": "application/json", Authorization: `Token ${localStorage.getItem("token")}`, }, }) … -
ASGI is slower than WSGI in Django Rest Framework
When I switch from WSGI to ASGI, my server Response per second (RPS) drops by more than half. I think I misunderstood how ASGI should be implemented In the docker-compose file with WSGI services: web: container_name: djangoRestFramework command: gunicorn server.wsgi:application --bind 0.0.0.0:8000 -w 6 In the docker-compose file with ASGI services: web: container_name: djangoRestFramework command: gunicorn server.asgi:application --bind 0.0.0.0:8000 -w 6 -k uvicorn.workers.UvicornWorker The post request that I am testing against @api_view(('POST',)) def some_post_request(request): serializer = serializer_class(data=request.data) if serializer.is_valid(): address = serializer.validated_data['somedata'] result = some_function.delay(address) return JsonResponse({"task_id": result.id, "task_status": result.status}, status=status.HTTP_200_OK) Can someone please highlight what I did wrong? -
Create a zip file that contain a pdf file (static location) - Python django windows
The title says it all.. I have a django based application and already find a way to generate the Models database into pdf. And now, I am having a difficulties to create a zip of PDF file, that can be download by the user.. To be honest, I already try and look several threads and still confused how to do it. Could someone help me? Any positive comment will be appreciated -
How to remove arrows from Django integerField without maintaining the only number input feature?
forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() registration = forms.IntegerField(label='Registration Number') class Meta: model = User fields = ['username', 'email','registration','password1', 'password2'] How can I remove the up and down arrows from the registration field? P.S. I want to only allow the user to input numbers in this field. -
Error during template rendering, TaggableManager.get_extra_restriction() missing 1 required positional argument: 'related_alias'
TypeError views.py post_detail def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status='published', publish__year=year, publish__month = month, publish__day=day) comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() post_tags_ids = post.tags.values_list('id', flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4] return render(request, 'blog/post/detail.html', {'post': post,'comments': comments,'comment_form': comment_form,'similar_posts':similar_posts}) detail.html {% extends "blog/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} <p> <a href="{% url "blog:post_share" post.id %}"> Share this post </a> </p> <h2>Similar Post</h2> {% for post in similar_posts %} <p> <a href="{{ post.get_absolute_url }}"> {{post.title}} </a> </p> {% empty %} Therse is no similar post {% endfor %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{ forloop.counter }} by {{ comment.name }} {{ comment.created }} </p> {{ comment.body|linebreaks }} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form method="post"> {{ comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> … -
How to disable django-admin's change password, for users who signed up via LDAP server
We have an application where users can be uploaded via GUI. Other users of the application can come from a LDAP server. LDAP Server-backed users must not be able to change their django-admin password. The best, if they don't even have one. I know that there is a possibility to disable their password: user.set_unusable_password() Now the thing is that I must not disable the passwords for the GUI-uploaded users, only for those who came from a LDAP-server (because only LDAP-server backed users can access the application anyways). What is the best place and way to distinguish between the two? I've overridden create_user() in managers.py: class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user If I put user.set_unusable_password() into the method above, I would get the exact opposite (i.e. I would disable the pw for GUI-uploaded users, while left it intact for those who come from LDAP-server) What should I modify/override/add etc if … -
How display 2 model tables on 1 admin page
I have a general error model and "child models" I want to display all the tables of child models on the error page. Example: #models.py class Errors(models.Model): class Meta: verbose_name = "Errors" class Error1(models.Model): error1 = models.TextField(('Error1'), blank=True, null=True) class Error2(models.Model): error2 = models.TextField(('Error2'), blank=True, null=True) class Error3(models.Model): error3 = models.TextField(('Error3'), blank=True, null=True) #admin.py @admin.register(Errors) class ErrorsAdmin(admin.ModelAdmin): change_list_template = 'admin/errors/errors.html' ... -
Do using queryset.count() caches the queryset?
I'm making some filtering in my endpoint, and one of the filters are only applied if the filtered queryset has more than 30 items. yesterday_date = timezone.now() - timezone.timedelta(days=1) if query_dict.get("active"): active_query = cleaned_query.filter(created_at__gt=yesterday_date) if active_query.count() > 30: cleaned_query = active_query else: cleaned_query = cleaned_query[:30] My doubt is, will the .count() method already evaluates and caches the queryset or should I use len(queryset) to avoid another database hit in case it's bigger than 30? -
How to get value attribute in views
Hello is there a way to get 'value' attribute from HTML template into views.py and use it there?? HTML: <form class="card__delete" method="POST"> {% csrf_token %} <button value="{{item.id}}" class="card__delete__button" name="delete" type="submit">&#10008</button> </form> views.py class TodoView(UserPassesTestMixin, CreateView): model = Item template_name = 'home/todo.html' form_class = ItemCreationForm def test_func(self): return self.request.user.username in self.request.path def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['card'] = Card.objects.get(user=self.request.user, pk=self.kwargs.get('pk')) return context def post(self, request, pk, username): if 'delete' in self.request.POST: Item.objects.get(id=pk).delete() print('deleted') return redirect('home-page') -
Django REST Framework ViewSet Authentication Token issue
I have a small API in my Django project, I've been following tutorials for authentication tokens. I'm able to generate and store tokens, but whenever I do a cURL request to the API, with the token, it always returns unauthenticated, even though the token is correct. The endpoint worked before I applied the token authentication. Any help would be great, code is below: api/views.py from rest_framework import viewsets from .serializers import PlatformSerializer from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated from userplatforms.models import Platform class PlatformViewSet(viewsets.ModelViewSet): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = PlatformSerializer queryset = Platform.objects.all().order_by('user_id') api/urls.py from django.urls import path, include from rest_framework import routers from rest_framework.authtoken import views as auth_views from . import views router = routers.DefaultRouter() router.register(r'userplatforms', views.PlatformViewSet) urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('authtoken/', auth_views.obtain_auth_token, name='tokenauth') ] api/serializers.py from rest_framework import serializers from userplatforms.models import Platform class PlatformSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Platform fields = ('id', 'user_id', 'platform_reference', 'platform_variables') settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ) } INSTALLED_APPS = [ 'api.apps.ApiConfig', 'userplatforms.apps.UserplatformsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'rest_framework', 'rest_framework.authtoken' ] -
How to start a celery task again as soon as it's over?
An apply_async() within the task will probably work, it'll schedule the task again repeatedly. Is there a better way to write it? -
Ordering custom fields in django admin
I have a User model with the following fields: #models.py class User(models.Model): ... first_name = models.CharField(max_length=255) middle_name = models.CharField(max_length=255, null=True, blank=True, default="") last_name = models.CharField(max_length=255) ... I have written a custom field like bellow that can be ordered with first_name, middle_name and last_name: @admin.register(User) class UserAdmin(BaseUserAdmin): list_display = ("username", "email", "full_name", "is_staff", "date_joined") list_filter = ("is_staff", "is_active") @admin.display(ordering=("first_name", "middle_name", "last_name")) def full_name(self, user: User): return f"{user.first_name} {user.middle_name} {user.last_name}" But admin.display(ordering=...) doesn't work with multiple fields like above. How to make this custom field ordered by multiple fields? -
Django admin action to download multiple pdfs
I have been trying to make custom Django admin action that allows me to convert html page to pdf and then download that pdf, for each object separately if more than once is selected. and since there is only one request to be sent I know there will be only one response. So I tried to put these pdfs in a zip file and then download the zip.. but What I see at the end is corrupted zip file. No idea where is the problem CODE in admin.py def report_pdf(self, request, queryset): from django.template.loader import get_template from xhtml2pdf import pisa import tempfile import zipfile with tempfile.SpooledTemporaryFile() as tmp: with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED) as archive: for item in enumerate(queryset): context = {"transactions": item} template_path = "test-pdf.html" template = get_template(template_path) html = template.render(context) file = open('test.pdf', "w+b") pisaStatus = pisa.CreatePDF(html.encode('utf-8'), dest=file, encoding='utf-8') file.seek(0) pdf = file.read() print(pdf) file.close() fileNameInZip = f"{item.chp_reference}.zip" archive.writestr(fileNameInZip, pdf) tmp.seek(0) response = HttpResponse(tmp.read(), content_type='application/x-zip-compressed') response['Content-Disposition'] = 'attachment; filename="pdfs.zip"' return response -
error with Django using poetry env when I try to run tests
I have this error with Django using poetry env when I try to run tests only with this command: python manage.py test module = import_module('%s.management.commands.%s' % (app_name, name)) File "/home/moegts/.pyenv/versions/3.9.5/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 855, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/home/moegts/python/snacks_crud_project/.venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 6, in <module> from django.test.runner import get_max_test_processes File "/home/moegts/python/snacks_crud_project/.venv/lib/python3.9/site-packages/django/test/runner.py", line 2, in <module> import ctypes File "/home/moegts/.pyenv/versions/3.9.5/lib/python3.9/ctypes/__init__.py", line 8, in <module> from _ctypes import Union, Structure, Array ModuleNotFoundError: No module named '_ctypes' I did reinstall all the setup for the WSL & Ubuntu etc and that didn't solve the problem