Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problema al guardar los datos actualizados de una tabla de Django (Vinculada a MySQL) a través de un formulario HTML
estoy tratando de llevar a cabo la función de actualizar de mi CRUD, sin embargo cuando intento guardar los cambios me da un error indicando que el formulario fue invalido (Sin importar si se cambiaron o no los valores de los campos). Estoy utilizando Python con el framework Django junto a HTML y Bootstrap 5. El modelo que estoy implementando es este: #LIBRERIAS NECESARIAS PARA QUE TODO FUNCIONE CORRECTAMENTE from django.db import models from django import forms from django.contrib.auth.models import User #CREACIÓN DE LOS MODELOS class Arbol(models.Model): #Defino las opciones de estado ESTADO = [ ("AJOV","Árbol joven"), ("AADU","Árbol adulto"), ("AANC","Árbol anciano") ] #Defino las opciones de salud SALUD = [ ("ASAN","Árbol sano"), ("AHER","Árbol herido"), ("AENF","Árbol enfermo"), ("AMUE","Árbol muerto") ] #Campos que lleva la tabla en la base de datos id = models.AutoField(primary_key=True, verbose_name="Identificador") especie = models.CharField(max_length=100, null=True, verbose_name="Especie") # estado = forms.ChoiceField(choices=ESTADO, required=True, label="Estado") # salud = forms.ChoiceField(choices=SALUD, required=True, label="Salud") estado = models.CharField(max_length=20, choices=ESTADO, null=True, verbose_name="Estado") salud = models.CharField(max_length=20, choices=SALUD, null=True, verbose_name="Salud") edad = models.DecimalField(max_digits=10,decimal_places=2 ,null=True, verbose_name="Edad [Años]") altura = models.DecimalField(max_digits=10, decimal_places=2, null=True, verbose_name="Altura [Metros]") encargado = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Encargado") #INFORMACIÓN DEL OBJ PRESENTADA EN EL ADMINISTRADOR (TO STRING) def __str__(self): info = f"Especie: {self.especie} - Estado: {self.estado} - Salud: … -
typeError: fromisoformat: argument must be str,
I trie many solutions from the internet nothing worked.. thanks in advance Error typeError: fromisoformat: argument must be str view.py def notes(request): now = datetime.datetime.now() month = now.month year = now.year cal = HTMLCalendar() events = Note.objects.filter(date_month=month, date_year=year) notes = Note.objects.all() return render(request, 'notes/home.html',{ 'cal': cal, 'events': events, } -
Why am I getting the 'Welcome to nginx!' page when I launch my Django app with Docker and Nginx?
My tech stack: Django, Gunicorn, Postgres, Nginx, Docker (and Docker Hub). I'm currently trying to deploy my web app, and when I launch my website with Docker, I get "Welcome to nginx!" page as a starting page. Here's the code of the docker-compose file that I use to launch my images: version: '3' services: db: image: sh1nkey/outtask1:latest ports: - "5432:5432" django: image: sh1nkey/django_outtask1:lastest ports: - "8000:8000" nginx: image: sh1nkey/outtask1_nginx:latest ports: - "80:80" Here's the Dockerfile code: FROM python:3.10 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY ./requirements.txt . RUN pip install --upgrade pip && pip install --upgrade setuptools wheel RUN pip install -r requirements.txt COPY . . EXPOSE 8000 Here's docker-compose file code i use to build images (i know this code sucks, so i'll gladly accept critique): version: '3.9' services: db: image: postgres volumes: - type: volume source: pg_data target: /var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres ports: - "5432:5432" expose: - 5432 django: image: django-docker:0.0.1 build: . command: sh -c "gunicorn --bind 0.0.0.0:8000 outtask.wsgi" # sh -c "gunicorn --bind 0.0.0.0:8000 outtask.wsgi" volumes: - type: bind source: . target: /outtask - type: volume source: static_data target: /outtask/static ports: - "8000:8000" expose: - 8000 environment: - DJANGO_SETTINGS_MODULE=outtask.settings depends_on: - db nginx: … -
Custom classes and views
I have set up the following custom class and am trying to output its contents into a Django view, however I keep hitting various Attribute and Type errors. I wondered if someone could point me in the right direction, please? Custom class from pickle import OBJ from urllib.request import HTTPPasswordMgr from django.shortcuts import render from django.http import request class Bloodcancer(): def __init__(self, my_symptoms=None, my_causes=None, my_treatments=None): self.symptoms = my_symptoms self.causes = my_causes self.treatments = my_treatments class AcuteMyeloidLeukemia(Bloodcancer): def my_symptoms(): symptomatology = { tuple({'a': "pale appearance",'b': "weakness or feeling tired", 'c': "shortness of breath", 'd': "easy brusing or bleeding",'e': "petechiae which are flat, pinpoint spots under the skin caused by bleeding", 'f': "loss of weight", 'g': "loss of appetite", 'h': "fever", 'i': "frequent minor infection"} ) } print (symptomatology) def my_causes(self): causes = ['age', 'being male', 'genes', 'environment', 'other bone marrow diseases'] return render(request, 'Healthcare/Conditions/Blood/Causes.html', {{causes}}) def my_treatments(self): treatments = ['induction therapy', 'consolidation therapy', 'chemotherapy', 'allogenic stem cell transplantation', 'central nervous system treatment', 'treatment of older and frail patients with AML', 'Treatment of refractory or relapsed AML', 'Supportive treatment'] return render(request, 'Healthcare/Conditions/Blood/Treatments.html', {{treatments}}) views.py from django.shortcuts import render from django.http import HttpResponseBadRequest, request from django.urls import path from Healthcare.Conditions.Blood.blood import AcuteMyeloidLeukemia as … -
Return object instead of string for FK field in SerializerMutation in Graphene Django
I have two models ProjectType and Project as follows class ProjectType(Base): name = models.CharField(max_length=100, unique=True) class Meta: db_table = 'project_types' def __str__(self): return self.name class Project(Base): name = models.CharField(max_length=100, unique=True) project_type = models.ForeignKey(ProjectType, on_delete=models.DO_NOTHING, related_name='related_projects') class Meta: db_table = 'projects' def __str__(self): return self.code and I have Mutations for both using SerializerMutation from Grapehene Django class ProjectTypeMutation(SerializerMutation): class Meta: serializer_class = ProjectTypeSerializer model_operation = ['create', 'update'] class ProjectMutation(SerializerMutation): class Meta: serializer_class = ProjectSerializer model_operation = ['create', 'update'] class Mutation(graphene.ObjectType): cudProjectType = ProjectTypeMutation.Field() cudProject = ProjectMutation.Field() When I perform a create mutation for project, I have to also specify the project_type. The resulting response also has the project_type but as a String. Not an object. Is there any way to get project_type back as an object? Current Mutation ⬇️ mutation{ cudProject(input: {name: "Project1" project_type: "1"}) { id name project_type } } Current Output ⬇️ { "data": { "cudProject": { "id": 200, "name": "Project1", "project_type": "1" } } } I want project_type to be an object which I can use as follows: Expected Mutation Request ⬇️ (This brings an error currently) mutation{ cudProject(input: {name: "Project1" project_type: "1"}) { id name project_type{ id name } } Expected Output ⬇️ { "data": { "cudProject": … -
Django and tailwind page responsiveness issues
I am trying to integrate tailwind with Django using django-tailwind library everything works fine only the page mobile design does not work properly so when I am on desktop and a resize (downsize) the window it works but when I use inspect element to see how the page look on phone size it does not work i am using Django-tailwind version 2.2 this is the result on inspect element (it shows 2 blog per row but it has to show only one) : this is the result on window resize (works fine): -
Empty results in dynamical form in Django
My views.py: from django.shortcuts import render from django.shortcuts import HttpResponse from .models import * from .forms import TestForm from django import forms def TestView(request,id): test = Tests.objects.get(id=id) queshions = Queshions.objects.filter(test=test) form = TestForm(queshions=queshions) if request.method == 'POST': print(request.POST) form = TestForm(data=request.POST, queshions=queshions) print(form) print(form.is_valid()) else: context = {'queshions':queshions,'test': test,'form':form } return render(request,'testview.html',context) My forms.py: from django import forms class TestForm(forms.Form): def __init__(self, *args, **kwargs): queshions = kwargs.pop('queshions') super(TestForm, self).__init__(*args, **kwargs) for queshion in queshions: self.fields[queshion.id] = forms.CharField(label=queshion.text) POST request is correct, but form.is_valid returns False, and when i am printing form it writes "This field is required." like it is empty -
Email verification after the user edits the email - Django
So, I'm trying to make a blog website. I'm with the authentication, and I'm struggling a bit with the security part. I'm trying to make email verification security a thing in my auth security. I've done all the basic stuff like user registration, login & logout functions, view profile, and edit profile. I have done the email verification part in the user registration, but I am somehow struggling a lot when trying to add email verification after users change their email. What I want my code to do is when a user edits his/her email, the code has to save the user's new email address temporarily and not change the email to the new one just then. I, instead, want the code to send an email to the old one (as the old one still is the recovery email address ... Additionally, I want the code to display the old email when clicked), asking for verification if he/she were the one to request to change the email. If the link provided is clicked then the email should change automatically with a message saying so, but if not then after 24 hours, deactivate the link. Oh, and I just wanted to … -
Django error Health checks failed with these codes: [502]
I'm trying to deploy a Django app on AWS Elastic beanstalk. I'm not an experienced tech guy but learning about AWS. I followed all the deployment steps till 'eb status'. Under EC2 > Target groups on AWS dashboard, Health status details are : Health checks failed with these codes: [502] How to troubleshoot this error so as to make the app run on the address provided by the CNAME of 'eb status' command? Tried many solutions from various stackoverflow posts but nothing seems to work. -
how to create a cycle approval?
I have an application made from the backend in django and from the frontend in nextjs, I have this models.py, you have to help me with the PurchaseOrders, ApprovalCycle and Approvalcycle models these 3 together regulate an approval cycle, I need to create a signals to make the status you change from the default value it currently has, which is given by the StatiPurchaseOrder class and you become approved when on the front-end side I'm going to use the function connected to the button, but this part of the frontend now let's leave it aside, let's focus on the backend, on the logic. Could you help me to write a signal that creates this approval? this is my signals @receiver(post_save, sender=ApprovazioniCiclo) def check_approvazione_ciclo(sender, instance, **kwargs): ciclo_approvazione = instance.purchase_order.ciclo_approvazione if ciclo_approvazione.check_approvazione(instance.purchase_order): # Il ciclo di approvazione è stato completato, quindi impostiamo lo stato del PurchaseOrder come 'Approvato' instance.purchase_order.stato = StatiPurchaseOrder.APPROVATO instance.purchase_order.save() -
django: How to defer TextField and localized variants of field from queryset including related models
When making the query to the model which has related models with large text fields, django loads all data in SQL query. How to defer automaticaly textfields, from main model and related in queryset? how to exclude from query fields like description, description_??, text, text_?? SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ... product.description, product.description_uk, product.description_ru, product.description_en, product.text, product.text_uk, product.text_ru, product.text_en, ... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, ... product_manufacturer.description, product_manufacturer.description_uk, product_manufacturer.description_ru, product_manufacturer.description_en, ... product_manufacturer.text, product_manufacturer.text_uk, product_manufacturer.text_ru, product_manufacturer.text_en, ... FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC SELECT DISTINCT store_item.id, store_item.store_id, ..... store_item.product_id, store_item.price_in, store_item.price_out, store_item.count, product.id, product.name, product.name_uk, product.name_ru, product.name_en, product.manufacturer_id, ..... product_manufacturer.id, product_manufacturer.action_id, product_manufacturer.name, product_manufacturer.slug, product_manufacturer.code, FROM store_item INNER JOIN product ON store_item.product_id = product.id LEFT OUTER JOIN product_manufacturer ON product.manufacturer_id = product_manufacturer.id ORDER BY product_manufacturer.name ASC, product.name ASC -
how i can convert a docx to pdf using python on a heroku app?
I have a Django app running on Heroku, and I'm trying different ways to convert a DOCX file to PDF. Are there any methods available for accomplishing this? I would greatly appreciate some assistance. i've tried install libreoffice with buildpacks, but logs return "FileNotFoundError: [Errno 2] No such file or directory: 'libreoffice'" -
How to handle user local timezone conversion for datetimes in Django forms/views/templates?
I'm having a problem with timezones in Django. I'm not sure how to go about storing datetime as UTC, but also displaying and accepting datetimes from the user as their local timezone. I'm planning to include a timezone setting option for the user that would be stored in the database and could be used to decide which timezone to accept input and display output as, but I'd like to know if there is way to automate the conversion for both directions that could be easily implemented without needing to manually add a piece of conversion logic (or the to every existing form/view/template/etc. to display the correct time. Something like how a Mixin works for views that can be easily applied to handle the conversion. -
Django with docker-compose : OperationalError: FATAL: database "" does not exist
I am currently on a project based around react in the frontend, django in the backend, postgresql for the database and nginx for the reverse proxy. Everything is linked up with a Docker-compose file. My previous question asked in this forum was about linking the database to the django backend. Altough it was resolved, I have another problem now : when I try to create a superuser account in the container, the container responds me with this error : django.db.utils.OperationalError: FATAL: database "" does not exist One of my first try to solve it was to check if the database is correctly created. Unfortunately I do not why but neither the database nor the role is created. Docker-compose.yaml file : version: '3.8' services: nginx: container_name: app_server_conf build: context: ./ dockerfile: ./Dockerfile ports: - "80:80" depends_on: - backend environment: - PUBLIC_URL=127.0.0.1 networks: app_network: volumes: - staticfiles:/staticfiles backend: container_name: backend ports: - "8000:8000" build: context: backend dockerfile: ./Dockerfile command: "make run" env_file: - .env depends_on: - database networks: - app_network volumes: - staticfiles:/app/staticfiles/ database: container_name: database build: context: ./postgres/ dockerfile: ./Dockerfile command: ['postgres', "-c", 'log_statement=all'] ports: - "5432:5432" restart: always volumes: - postgres_data/:/var/lib/postgresql/data environment: - POSTGRES_DB= - POSTGRES_USER= - POSTGRES_PASSWORD= networks: - … -
Django: 'list' object has no attribute '__dict__'
I try to implement modelformset_factory but got an error on form_valid(). 'list' object has no attribute 'dict' Neverthless all formset are correctly registered in database what is wrong with return super().form_valid(formset)? TraitementFormSet = modelformset_factory( Traitement, form=TraitementForm, fields=('arv_num','arv_reg','arv_reg_pre','arv_deb_dat','arv_fin_dat','arv_enc','arv_rai_eff','arv_rai_vir','arv_rai_gro','arv_rai_per','arv_rai_inc','arv_rai_aut','arv_rai_aut_pre'), extra=1 ) @method_decorator(login_required, name="dispatch") class TraitementFormSetCreate(SuccessMessageMixin, CreateView): model = Traitement form_class = TraitementForm template_name = "ecrf/traitements_form.html" success_message = "Fiche Traitement créée." success_url = reverse_lazy('ecrf:inclusion_list') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = TraitementFormSet(queryset=Traitement.objects.filter(pat=self.kwargs['pk'])) context['action'] = 'create' context['patient'] = Patient.objects.get(ide=self.kwargs['pk']) context['model_name'] = self.model._meta.model_name context['is_locked'] = self.object.ver if self.object else None return context def post(self, request, *args, **kwargs): formset = TraitementFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, formset): print('valid',type(formset)) patient = Patient.objects.get(ide=self.kwargs["pk"]) traitements = formset.save(commit=False) for traitement in traitements: traitement.pat = patient traitement.arv_sai_log = self.request.user.username traitement.save() return super().form_valid(formset) def form_invalid(self, formset): print('invalid',formset.errors) context = self.get_context_data(formset=formset) return self.render_to_response(context) -
Getting 401 error instead of being redirected to login page with ms_identity_web.login_required decorator in Django app
I have a django app which uses the ms_identity_web repository (https://github.com/Azure-Samples/ms-identity-python-samples-common) to authenticate against an Azure Active Directory. Authentication works fine, but when i directly (not logged in) browse to a page that requires the user to be logged in (using the provided @ms_identity_web.login_required decorator) I get a 401 error instead of being redirected to my login page (as i'm used to with the Django @login_required decorator and LOGIN_URL setting's variable). As I cannot find much documentation on this topic I resolved to writing a custom middleware (which sounds like it shouldn't be neccesary, but again; i couldn't find an option like MS_LOGIN_URL that should/is included in the repo). Where I'm stuck is that I need to find out whether the requested page/path requires login or not (basically if it has the decorator or not). The best solution would be one that's included in the library of course, but other solutions are welcome. I followed the tutorial on: https://learn.microsoft.com/en-us/training/modules/msid-django-web-app-sign-in/2-register-web-app-in-azure-active-directory-tenant In my settings.py I added: from ms_identity_web.configuration import AADConfig from ms_identity_web import IdentityWebPython AAD_CONFIG = AADConfig.parse_json(file_path='aad.config.json') MS_IDENTITY_WEB = IdentityWebPython(AAD_CONFIG) ERROR_TEMPLATE = 'auth/{}.html` I have a view with the decorator: ms_identity_web = settings.MS_IDENTITY_WEB @ms_identity_web.login_required def view_data(request): context = { 'data': 'test' } … -
How to show clusters in a map?
I'm building a Flutter map and I want show clusters that are storred in a Django server database. I want to do a similar view as this but instead of showing all the users location, I want to show the surface that these users are occupying (the surface of a cluster). PS: I'm using a package named flutter_map to display the map. -
Save to db only if changing fields
Is there a better way of doing the following in Django: obj = Thing.objects.get(name=name) if obj.a != a or obj.b != b: obj.a = a obj.b = b obj.save() So I wish to save if ether a or b has become invalid and I can’t make any change to the save implementation. And I’d like to stick to using the model instance rather than solving this using a query set. -
Database not updating between tests in Django
I'm trying to run a create test followed by an update, however on the second test I'm unable to find the object created in the first test. I've realised that this is because the object is not added to the DB until after both tests have run. Does anyone know why this is? And how I can run a create test, followed by an update test that uses the object created in the create test? from unittest import TestCase class QuantsTests(TestCase): def setUp(self): self.factory = RequestFactory() def test_create_object(self): object = Object() object.name = "123456789" object.save() def test_update_object(self): Object.objects.filter(name="123456789") Error: object.models.Model.DoesNotExist: Object matching query does not exist. -
Getting 'Invalid request method' error when trying to pass Scrapy data to Django using Python APIs
I have a problem, I created a scrapy project and a django project with an application, I registered the application, set the urls, set the views, and also wrote the spider, but when I go to the localhost stand, I get an error this is my piece of a spider with pandas, I only put the end here because the spider is ok , it saves the data to a json file on the disk, I want to send it to DJANGO code is scrapy data_dict = df.to_dict(orient='records') data = {'data': data_dict} print(df) yield scrapy.Request( url='http://127.0.0.1:8000/receive_data/', method='POST', body=json.dumps(data), headers={'Content-Type': 'application/json'}, callback=self.handle_response, cb_kwargs={'df': df} ) df.to_json('data.json', orient='records', lines=True) def handle_response(self, response, df): if response.status == 200: self.log('Data successfully sent.') else: self.log(f'Data sending failed. Response status: {response.status}') df.to_json('data.json', orient='records', lines=True) my views in Django @csrf_exempt def receive_data(request): if request.method == 'POST': data = json.loads(request.body) toy = modul toy.xx = data.get('xxx') toy.xx = data.get('xxx') toy.xx= data.get('xx') toy.xx = data.get('xx') toy.xx = data.get('xx') if toy.xxx is not None and toy.xxx is not None and toy.xx is not None and toy.xxx is not None and toy.xx is not None: toy.save() response_data = { 'message': 'Data received and saved successfully.', } else: response_data = { 'error': … -
django-oscar / django-oscar-api: huge number of queries to render the ProductSerializer
I am using django-oscar with my own Product class, and a serializer for Django REST Framework. I am finding that adding some properties which are stored as attributes results in a huge number of queries. For example as soon as I add "legacy_title" (which is an attribute I've added) to the serializer's fields, the number of queries made to render this result goes up from 3 to 70. I have 21 products in my databases. from oscarapi.serializers.product import ProductSerializer as CoreProductSerializer class ProductSerializer(CoreProductSerializer): class Meta(CoreProductSerializer.Meta): fields = ( "url", "id", "description", "slug", "upc", "title", "structure", "legacy_title", ) My Product class: from oscar.apps.catalogue.abstract_models import AbstractProduct def attribute_error_as_none(callable_): try: return callable_() except AttributeError: return None class Product(AbstractProduct): @property def legacy_title(self) -> str: return attribute_error_as_none(lambda: self.attr.legacy_title) or self.title I'm using django-oscar-api's built-in ProductList view. If I add a few more fields which are backed by attributes, then the query count keeps going up, to 84 queries for these 21 products. Then add things like children, recommendations, and images, and it takes 240 queries to render this result! How can I get the query count under control? The endpoint to fetch all products is by far the slowest API endpoint in my entire backend … -
how can i make like and unlike button more smooth Using django and javascript in python framework django?
“Like” and “Unlike” buttons with icons Users should be able to click a button or link on any post to toggle whether or not they “like” that post. Using JavaScript asynchronously let the server know to update the like count (as via a call to fetch) and then update the post’s like count displayed on the page, without requiring a reload of the entire page. problem is I cannot toggle between the like and unliked icons when I am in the unlike icon when I like one post liked count goes to all posts. look like my code is beginner code In html file inside Django templates {% if post.id in postLiked %} <button class="btn btn-primary fa fa-thumbs-down" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% else %} <button class="btn btn-primary fa fa-thumbs-up" id="{{ post.id }}" onclick="likeOrUnlike('{{ post.id }}', '{{ postLiked }}')"></button> {% endif %} <div class="container"> <div class="row justify-content-center"> <h3 class="col-4">Like: {{ likes.count }}</h3> </div> </div> In models.py class LikeOrUnlike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likeByUser') post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postLiked') def __str__(self): return f'{self.user} liked this {self.post}' In urls.py path("", views.index, name="index"), path('like/<int:post_id>', views.like,name='like'), path('unlike/<int:post_id>', views.unlike,name='unlike') In views.py def index(request): likes = LikeOrUnlike.objects.all() postLiked = [] try: … -
How can I set the permission policy for a custom Image model in Wagtail?
In a Django/Wagtail project, I use a CustomImage model inheriting from Wagtail's AbstractImage/Image model. When I want to set Image permissions for a new group of users, it doesn't work though, because the function set_permission_policy() from the source file permissions.py takes the original (Wagtail) Image model as an argument auth_model while it should take my CustomImage model (as the users have permissions regarding the CustomImage model): def set_permission_policy(): """Sets the permission policy for the current image model.""" global permission_policy permission_policy = CollectionOwnershipPermissionPolicy( get_image_model(), auth_model=Image, owner_field_name="uploaded_by_user" ) When I experimentally changed the value of auth_model in the source code to my CustomImage model, everything started working, but I need a solution which will be based on modifying my code and not the source Wagtail code. Everytime Wagtail checks permission policy (e.g. in views), it imports directly the wagtail.images.permissions. How to change it in my code so that the permission policy can be set for my CustomImage model and not for the original Wagtail's Image model? -
What can I do to troubleshoot Django's failure to connect to Postgres in Docker-Compose on Ubuntu server?
I am trying to deploy my django app on Ubuntu server. It is actually working on localhost with windows machine. Dockerfile # pull official base image FROM python:3.11.2-slim-buster # set working directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # updated # install system dependencies RUN apt-get update \ && apt-get -y install gcc postgresql \ && apt-get clean # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt # new # copy entrypoint.sh RUN apt-get update && apt-get install -y netcat COPY ./entrypoint.sh /usr/src/app/entrypoint.sh RUN chmod +x /usr/src/app/entrypoint.sh # add app COPY . . # new # run entrypoint.sh ENTRYPOINT ["/usr/src/app/entrypoint.sh"] docker-compose version: '3.8' services: qutqaruv: build: ./app command: gunicorn qutqaruv_core.wsgi --bind 0.0.0.0:8001 volumes: - ./app/:/usr/src/app/ - static_volume:/static ports: - "8001:8001" env_file: - ./app/.env.dev depends_on: - qutqaruv-db nginx: image: nginx:1.22.1 ports: - "82:8081" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - static_volume:/static depends_on: - qutqaruv qutqaruv-db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=qutqaruv - POSTGRES_PASSWORD=qutqaruv - POSTGRES_DB=qutqaruv_dev volumes: postgres_data: static_volume: entrypoint #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do echo $SQL_HOST $SQL_PORT sleep 0.1 echo "Got lost in this process" … -
openpyxl multiple headers and content
I'm using openpyxl for the first time in my django project. I got the task to make a two-part excel, that should be looking approximately like this: So basically i want to shaw all users of a certain organisation. This is what I have so far: def export_organisation(self, org_id): organization = Organization.objects.get(pk=org_id) wb = Workbook() ws = wb.active ws.title = "OKR" headers = [ ['Organisation Name', 'Signup Date', 'Language'], ['First Name', 'Last Name', 'Email'] ] line = 1 # Start from the first row for header_row in headers: ws.append(header_row) # Format bold the cells in the first row ft_bold = Font(bold = True) for cell in ws[ws.max_row]: cell.font = ft_bold line = ws.max_row+1 ws['A' + str(line)] = organization.name ws['B' + str(line)] = organization.signup_date.strftime("%d/%m/%Y") ws['C' + str(line)] = organization.language for user in organization.users.all(): ws['D' + str(line)] = user.first_name ws['E' + str(line)] = user.last_name ws['F' + str(line)] = user.email line+=1 # Filename with team name and date wb.save('{}.xlsx'.format(org_id)) But this gives me following output: Is there a way to make it look like the first image? If yes, what did I miss?