Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Safely Storing Passwords and Database Credentials in Django [closed]
Does anyone here have experience with Django? How can I safely store my passwords, database credentials, and other sensitive information in settings.py? I found it using cryptography but wanted to hear more ideas.. Someone Can help me? -
Adding laos language in Django
I have added the langauge laos in settings.py as follows LANGUAGES = [ ("en", _("English")), ("my", _("Burmese")), ("fr", _("French")), ("km", _("Khmer")), ("th", _("Thai")), ("vi", _("Vietnamese")), ("lo", _("Lao")), ] However, when I load my application I get the error. KeyError at / 'Unknown language code lo.' Seems like the current version of Django does not support the language. Is there a way I can manually add a none existing language in Django? Thank you in-advance. -
Why companies still prefer Django over Fast API for REST APIs developments
Can I get thoughts from working professionals in python domain over why companies still prefer Django over Fast API for REST APIs developments. In python world I see more opportunity of Django over Fast API. So wanted to know the reason about this preference. As in multiple blogs and Generative AI I got to know that Fast API outperforms Django. -
Pydantic/Django Ninja use only existing keys (even with None)
having an app in Django Ninja with schemas: class NumericalFilterSchema(Schema): gt: Optional[int] = None lt: Optional[int] = None gte: Optional[int] = None lte: Optional[int] = None exact: Optional[int] = None class Config(Schema.Config): extra = "forbid" class StringFilterSchema(Schema): contains: Optional[str] = None icontains: Optional[str] = None exact: Optional[str] = None class Config(Schema.Config): extra = "forbid" class InputsSchema(Schema): major_version: Optional[NumericalFilterSchema] = None app_name: Optional[StringFilterSchema] = None class Config(Schema.Config): extra = "forbid" class InputSchema(Schema): filters: InputsSchema class Config(Schema.Config): extra = "forbid" which I then use in the endpoint like this: @router_v1.post( "/apps", tags=["..."], auth=AuthBearer(), ) def dynamic_filter(request: HttpRequest, filters: InputsSchema): query = Q() # import ipdb # ipdb.set_trace() for key, value in filters.dict(exclude_none=True).items(): # key = translate_field(key) # just abstraction between endpoint keys to db keys if isinstance(value, dict): for k, v in value.items(): if v is not None: query &= Q(**{f"{key}__{k}": v}) else: query &= Q(**{key: value}) results = Apps.objects.filter(query) ... Problem: As you can see in the query building I am excluding all the None values which is fine in the most cases for example: { "major_version": { "exact": 3 }, "app_name": { "icontains": "google" } } this will return schema InputsSchema(major_version=NumericalFilterSchema(gt=None, lt=None, gte=None, lte=None, exact=3), app_name=StringFilterSchema(contains=None, icontains='google', exact=None)) which is … -
Method not allowed in fresh django-ninja-extra project
I cant make a post request in my project, now i created a fresh project, because i thought it was a configuration problem. But the Problem persists. The problem is that when i try to make a post request it always gives me a 405 status back. settings.py: # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'backend.apps.department', 'ninja_extra' ] 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', ] api.py: from ninja_extra import NinjaExtraAPI api = NinjaExtraAPI() api.auto_discover_controllers() department/api.py: from ninja_extra import api_controller, route from django.shortcuts import get_object_or_404 from ninja import Schema from datetime import datetime from .models import department from typing import List class DepartmentIn(Schema): name: str last_modified: datetime user_id: int class DepartmentOut(Schema): id: int name: str last_modified: datetime @api_controller('department/') class DepartmentController: @route.get("all/", response=List[DepartmentOut]) def get_departments(self): department_list = department.objects.all() return department_list @route.get("{department_id}/", response=DepartmentOut) def get_department(self, department_id: int): record = get_object_or_404(department, id=department_id) return record @route.post("create/") def create_department(self, payload: DepartmentIn): record = department.objects.create(**payload.dict()) return {"id": record.id} models.py: from django.db import models from django.conf import settings class department(models.Model): name = models.CharField(max_length=50) last_modified = models.DateTimeField(auto_now=True, auto_now_add=False) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) The Problem i get: Response body Method not allowed Response headers allow: GET content-length: 18 content-type: text/html; charset=utf-8 … -
In Django REST Framework, why does raising serializers.ValidationError return errors in different format in validate() and create() methods?
I am working on a DRF project and have a serializer like: class SomeSerializer(serializers.Serializer): number_field = serializers.IntegerField(required=False, min_value=25, max_value=100) In my settings.py, I have REST_FRAMEWORK = { other settings.... 'EXCEPTION_HANDLER': 'apps.utils.exceptions.custom_exception_handler', } In the custom exception handler, I handle ValidationError as follows: def custom_exception_handler(exc, context): # Call REST framework's default exception handler first response = exception_handler(exc, context) messages = None code = None detail = None if response is not None: # Map specific exceptions to custom error codes if isinstance(exc, ValidationError): code = "validation_error" detail = "One or more fields failed validation." messages = exc.detail status_code = status.HTTP_400_BAD_REQUEST # After checking for other errors here in between else: code = "unexpected_error" detail = response.data.get("detail", "An unexpected error occurred.") messages = response.data.get("messages", {"error": str(exc)}) """ In between the if and else, AuthenticationFailed, PermissionDenied, NotFound, are handled. Add an appropriate code and return in the format response.data = { "detail": detail, "code": code, "messages": messages } """ The custom exception handler is configured to return the error in the format shown below. But it only happens if I validate the min and max range inside the create() method (without min_value and max_value defined on the serializer field itself) { "detail": "One … -
When I dockerize django vue3 app django container does not work
I am learning docker and while I dockerize my django vue3 app I got error. Dockerfile: FROM python:3.11-slim RUN apt-get update && apt-get install -y \ libpq-dev gcc curl \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* WORKDIR /backend/project COPY requirements.txt /backend/ RUN pip install --no-cache-dir -r /backend/requirements.txt COPY . /backend/ RUN chown -R www-data:www-data /backend USER www-data ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] Docker-compose: version: '3.9' services: web: build: context: . dockerfile: dockerfile container_name: c_django command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend:/app ports: - 8000:8000 environment: ALLOWED_HOSTS: '*' DEBUG: 'True' SECRET_KEY: random_secret_key DATABASE_NAME: fitness DATABASE_USER: postgres DATABASE_PASSWORD: 123456 DATABASE_HOST: db DATABASE_PORT: 5432 REDIS_URL: redis://redis:6379/1 depends_on: - db - redis networks: - frontend_backend db: image: postgres:15 container_name: c_postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: 123456 POSTGRES_DB: fitness ports: - 5432:5432 volumes: - postgres_data:/var/lib/postgresql/data frontend: build: context: ../frontend container_name: c_frontend ports: - 8080:80 depends_on: - web networks: - frontend_backend nginx: image: nginx:latest container_name: c_nginx volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d - ./frontend/dist/:/usr/share/nginx/html ports: - 80:80 depends_on: - frontend networks: - frontend_backend redis: image: redis:8.0-M02-alpine container_name: c_redis ports: - 6379:6379 networks: - frontend_backend volumes: postgres_data: networks: frontend_backend: driver: bridge When I docker compose up I got this error for django … -
IIS does not pass on REMOTE_USER with HTTP Platform Handler
I have a Django server application that I am running with IIS on Windows Server (using HTTP Platform Handler). I would like to use Windows Authentication. I have enabled Windows Authentication in the server settings in IIS. If I understood the documentation correctly, I would expect that for each request, IIS would then send a REMOTE_USER object in the HTTP request to the Django server. However, this does not happen. REMOTE_USER is neither a server environment variable nor in request.META. In the IIS logs (The logs in C:\inetpub) I can see that it recognises my user, but IIS does not seem to forward that user information to the Django server. A line in the logs looks e.g. as follows: 2024-12-11 12:10:20 <SERVER IP> GET /<PATH> - <PORT> <DOMAIN>\<USERNAME> <CLIENT IP> <BROWSER DATA> ... So, IIS clearly does perform Windows Authentication, and it works, but that information somehow never makes it to the Django server. I have tried using Django's RemoteUserMiddleware, which does not change the behaviour. Is there some additional setting that I am missing? -
'{% load static %}' doesn't seem to get picked up by vs code
enter image description here The text is still white and there's no indicator as to if it's working or not. I don't know if this is because of a screw up in my part or an issue with VS code. I am unfamiliar with troubleshooting methods for this, please let me know if there are any. Thank you in advance for any help. -
what is the correct way to pass context to a playwright function when using python django as the basis for a webapp?
I've got a web app that I built first with Flask, then totally rebuilt with Django, to get advantage of the admin interface. It builds a flyer for a kids football match, using the context to overlay on a background image via css absolute position. Once the coach is happy with the image, a button calls a Generate function, which opens a browser with playwright and passes the session data to recreate the image and allow the coach to download it. When the coach is viewing the image the text fields are populated from the context. this all works fine. def image(request): ... some other bits ... for key in request.session.keys(): context[key] = request.session[key] return render(request, 'coaches/image.html', context) this is an example from the template that shows how the text is added from context. I'm using Django Template engine. {% for player in squad %} <td> <span class="playernumber">{{ player.number }}</span> <span class="playerfirstname">{{ player.first }}</span> <span class="playerlastname">{{ player.last }}</span> </td> {% if forloop.counter|divisibleby:2 %} </tr> <tr> {% endif %} {% endfor %} the same template code doesnt work when the playwright browser view is invoked. the view is fine, the template is fine, but calling the variables from context doesnt work. … -
How to list by most used foreign keys in django
I have 2 models: Post and Comment as you can see below class Post(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, ) date = models.DateTimeField(default=datetime.now) title = models.CharField(max_length=100,) body = models.CharField(max_length=1000) class Comment(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) post = models.ForeignKey(Post, on_delete=models.CASCADE, default=None, null=True, blank=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) date = models.DateTimeField(default=datetime.now) body = models.CharField(max_length=1000) I want to get the most commented posts last week so how would I list the Posts with most comments. Thanks! -
How to list product in fixed position?
Hello, I haven't been able to do this for a while. Can someone show me how how to did it? After searching for a product, is it possible for it to appear exactly in this format? this is model. class Product(BaseModel): owner = models.ForeignKey( 'account.Account', on_delete=models.CASCADE, blank=False, null=False, verbose_name=_("Owner"), ) title = models.CharField( max_length=150, help_text=_("User-friendly attribute name"), verbose_name=_("Name"), ) location = models.ForeignKey( 'tag_map.Location', on_delete=models.PROTECT, blank=True, null=True ) rank = models.IntegerField(blank=True, null=True) is_featured = models.BooleanField(default=False, db_index=True) class Tariff(BaseModel): name = models.CharField(max_length=100, verbose_name=_('Tariff Name')) duration_in_days = models.PositiveIntegerField(default=0, verbose_name='Duration in Days') duration_in_hours = models.PositiveIntegerField(default=0, verbose_name="Duration in Hours") price = models.DecimalField(default=0, max_digits=10, decimal_places=2) active = models.BooleanField(default=False) def __str__(self): return f"{self.name} ({self.duration_in_days} days, {self.duration_in_hours} hours) -- {self.price} uzs" def total_duration(self): return timedelta(days=self.duration_in_days, hours=self.duration_in_hours) class FeaturedProduct(BaseModel): product = models.OneToOneField( 'product.Product', on_delete=models.CASCADE, related_name='featureds', verbose_name=_("Product")) tariff = models.ForeignKey( 'product.Tariff', on_delete=models.PROTECT, blank=True, null=True, verbose_name="Tariff" ) start_time = models.DateTimeField(default=now, verbose_name="Start Time") end_time = models.DateTimeField(blank=True, null=True, verbose_name="End Time") def is_active(self): return now() <= self.end_time -
Custom Link on Column
I am working with django-tables2 to display some patient information on a page. I am creating the table like this: class PatientListView(tables.Table): name = tables.Column('Practice') patientid = tables.Column() firstname = tables.Column() lastname = tables.Column() dob = tables.Column() addressline1 = tables.Column() addressline2 = tables.Column() city = tables.Column() state = tables.Column() zipcode = tables.Column() class Meta: template_name = 'django_tables2/bootstrap.html' and then I am populating the table in my view with the result of an sql query like this: table = PatientListView(patients) I would like to ideally make each row of the table clickable so clicking anywhere on the table row would take me to a separate url defined by me. I would also settle for having a specific cell to click that would take me to a separate url. I have seen the linkify option, but from what I've read of the documentation it looks like linkify does redirects to django model pages, but I am not using models for this database as the database is created and managed by another application, and I am just reading and displaying that information. If django-tables2 is not the right solution for this issue I am open to hearing suggestions of other ways I can … -
get list of selected items from html form when we have two from in django app
hello i have two html from for selcting categories one for desktop view and other one for mobile view both of them have get method mt problem is in the mobile view when i select a category its work at start but when i want to select another one its not its html form for mobile view : <form action="{% url 'shop:category' %}" method="get"> {% for cat in categories %} <div class="d-flex align-items-center justify-content-between flex-wrap mb-3"> <div class="form-check"> <label for="category_{{ cat.id }}" class="form-check-label">{{ cat.name }} </label> <!-- Correctly use the same name and ensure it's an array to hold multiple values --> <input type="checkbox" name="categories" id="category_{{ cat.id }}" value="{{ cat.id }}" class="form-check-input" {% if cat.id|stringformat:"s" in selected_categories %}checked{% endif %}> </div> <div> <span class="fw-bold font-14">( {{ cat.product_numbers }} )</span> </div> </div> {% endfor %} <div class="filter-item text-center"> <button type="submit" class="btn-outline-site">اعمال فیلتر</button> </div> and this is for desktop view : <form action="{% url 'shop:category' %}"> {% for cat in categories %} <div class="d-flex align-items-center justify-content-between flex-wrap mb-3"> <div class="form-check"> <label for="colorCheck11" class="form-check-label">{{ cat.name }} </label> <label for="category_{{ cat.id }}"></label><input type="checkbox" name="categories" id="category_{{ cat.id }}" value="{{ cat.id }}" class="form-check-input"> </div> <div> <span class="fw-bold font-14">( {{ cat.product_numbers }} )</span> </div> </div> {% endfor … -
Django DRF - Accessing data from POST request forwarded through ngrok
I'm working on a Django REST framework (DRF) API that receives data forwarded from an external endpoint through ngrok. Here's the relevant view code: Python class MessageReceiver(generics.CreateAPIView): def post(self, request, org_id, channel_name): data = request.data if data: return Response( data={ "data": data }, status=status.HTTP_200_OK ) return Response(data={'message': 'No data received'}, status=status.HTTP_400_BAD_REQUEST) Use code with caution. My question is: since this is a POST request, I'm unable to access the original forwarded data directly. As I understand, POST requests require a payload to be sent along with the request. How can I effectively access and process the data within request.data in this scenario before I have to hit the endpoint again? -
Celery infinite retry pattern issue
I am using celery with AWS SQS for async tasks. @app.task( autoretry_for=(Exception,), max_retries=5, retry_backoff=True, retry_jitter=False, acks_late=True, ) @onfailure_reject(non_traced_exceptions=NON_TRACED_EXCEPTIONS) def send_order_update_event_task(order_id, data): ......... But the retry pattern is getting very much messed up when I use an integer value for the retry_backoff arg. No of tasks spawning up are getting out of control. logs: 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [53285c923f-79232a3856] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [1052f09663-c19b42589a] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [dd021828dd-4f6b8ae6f8] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [116bef9273-e4dbfb526b] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [913697ae7e-d4f65d45a5] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d99e889882-a76718b549] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d99e889882-30bac3e515] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR [1b810665-c0b1-4527-8cd9-c142f67d6605] [d7f01e5b4f-edfa22355f] tasks.order_request_task - [ send_order_update_event_task] Exception for order: 700711926: Order absent 700711926, retry_count: 10 2024-12-10 05:16:10 ERROR … -
Serializer raise exception to foreign data
I have complex selection logic for GET request, but serializer raise next exception. Got AttributeError when attempting to get a value for field crossroad_direction on serializer CrossroadDirectionRegulationSerializer. The serializer field might be named incorrectly and not match any attribute or key on the RelatedManager instance. Original exception text was: 'RelatedManager' object has no attribute 'crossroad_direction'. Direction has relationship One to One through models.ForeignKey(unique=True). Selection query create by use select_related('regulation') I added required serializers and models below. Serializers Crossroad class ReadonlyCrossroadFullDataSerializer(serializers.ModelSerializer): time_loads = CrossroadTimeLoadSerializer(many=True) sides = CrossroadSideFullDataSerializer(many=True) directions = CrossroadDirectionFullDataSerializer(many=True) class Meta: model = Crossroad fields = "__all__" CrossrodDirection class CrossroadDirectionFullDataSerializer(serializers.ModelSerializer): time_params = CrossroadDirectionTimeParamsSerializer(many=True) regulation = CrossroadDirectionRegulationSerializer(allow_null=True, default=None) class Meta: model = CrossroadDirection fields = "__all__" Regulation class CrossroadDirectionRegulationSerializer(serializers.ModelSerializer): class Meta: model = CrossroadDirectionRegulation fields = "__all__" Models CrossrodDirection class CrossroadDirection(models.Model): class Meta: constraints = ( models.UniqueConstraint( "input_point", "output_point", name="unique_crossroad_direction__input_output_points", ), ) crossroad = models.ForeignKey( Crossroad, on_delete=models.CASCADE, related_name="directions", ) input_point = models.ForeignKey( CrossroadPoint, on_delete=models.CASCADE, related_name="direction_input_point", ) output_point = models.ForeignKey( CrossroadPoint, on_delete=models.CASCADE, related_name="direction_output_point", ) probability = models.FloatField(default=1) Regulation class CrossroadDirectionRegulation(models.Model): crossroad_direction = models.ForeignKey( CrossroadDirection, on_delete=models.CASCADE, unique=True, related_name="regulation", ) cycle_duration = models.IntegerField(default=180) green_signal_phase = models.IntegerField(default=60) If I change Regulation serializer as below then crossroad serializer work successful - if there is regulation then … -
experiencing intermittent apache error AH01630
We have two different django apps running on a server (Centos7), using django manage.py runmodwsgi (python module mod_wsgi). Both apps are running fine, and have been for a few years. The odd thing we are running into is that every 10-12 days or so, we get a 403 Forbidden message in the browser. When checking the mod_wsgi apache error log (/tmp/mod_wsgi-localhost:8080:1999/error_log), there is nothing except the error below, which is triggered whenever the user unsuccessfully tries to access the app. AH01630: client denied by server configuration: /tmp/mod_wsgi-localhost:8080:1999/htdocs After receiving this error, I can see that the htdocs directory that is referenced in the error doesn't exist. Restarting the web server fixes the issue (and the htdocs directory reappears). Both apps experience this issue. Sometimes at the same time, sometimes not. Both apps otherwise run fine. We would really like to find a solution to this annoying issue. Googling this error just gives me advice on the httpd.conf file content, but I have not been able to find any help on this when the issue is intermittent the way I'm describing it here. I have plotted the date/times of the AH01630 errors, and find that this happens at an oddly regular … -
Django-tenant: Accessing tenant data in public domain
I was working on Django-tenant where I have tenant model called Appointment now I want to get the appointment of a specific tenant from the public domain but I'm having an issue when rendering it in the template class OrganizationAppointmentList(LoginRequiredMixin, TenantMixin, ListView): template_name = 'main/appointments/list_appointment.html' paginate_by = 10 def get_queryset(self): tenant_id = self.kwargs.get('pk') try: tenant = Organization.objects.get(id=tenant_id) self.schema_name = tenant.schema_name with schema_context(self.schema_name): queryset = Appointment.objects.all() return queryset except Organization.DoesNotExist: raise Http404("Tenant not found") except Exception as e: raise Http404(f"Error accessing tenant data: {e}") def paginate_queryset(self, queryset, page_size): with schema_context(self.schema_name): return super().paginate_queryset(queryset, page_size) def get_context_data(self, **kwargs): with schema_context(self.schema_name): context = super().get_context_data(**kwargs) tenant_id = self.kwargs.get('pk') context['tenant_id'] = tenant_id context['appointments'] = Appointment.objects.all() print(context['appointments']) return context In above code the print(context['appointments']) Is giving the exact data but while rendering it in template it shows LINE 1: ...app_appointment"."al_appointment_updated_at" FROM "appointme... and if I left the template empty the error does not show is it something that I'm missing?? I'm trying to get the specific tenant model data in public domain -
How can I programatically authenticate a user in Auth.js?
I have a Django application with authenticated (logged-in) users. I have another (Svelte) application using Auth.js (https://authjs.dev) for authentication, currently set up with github/facebook/linkedin. Now I want to send a user from the Django application to the Svelte application, and automagically (i) create the user in the Svelte application if they don't exist, and (ii) log them in to the Svelte application. I want the end-user experience to be like a regular redirect from one page to the other staying logged-in in both places. I'm stuck at the part where the user arrives in the Svelte application and I need to create a session. Does Auth.js have any way of doing this without going through a "provider"? -
PDF file cannot be opened, when generated with Django and WeasyPrint
I recently began trying generating PDF reports with Django and Weasyprint, but I cannot make it work somehow. I already have file upload, file download (even PDFs, but already generated ones that were uploaded), CSV generation and download, XLSX generation and download in my application, but I'm not able to return PDFs generated with WeasyPrint so far. I want my users to be able to create reports, and they'll be saved for further new download. So I created this basic model : from django.db import models class HelpdeskReport(models.Model): class Meta: app_label = "helpdesk" db_table = "helpdesk_report" verbose_name = "Helpdesk Report" verbose_name_plural = "Helpdesk Reports" default_permissions = ["view", "add", "delete"] permissions = [ ("download_helpdeskreport", "Can download Heldpesk Report"), ] def _report_path(instance, filename) -> str: return f"helpdesk/reports/{instance.id}" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, unique=True) file = models.FileField(upload_to=_report_path) Since I use service classes, I also did : import uuid from io import BytesIO from django.core.files import File from django.template.loader import render_to_string from weasyprint import HTML class HeldpeskReportService: def create_report(self) -> HelpdeskReport: report_name = f"helpdesk_report_{uuid.uuid4().hex}.pdf" html_source = render_to_string(template_name="reports/global_report.html") html_report = HTML(string=html_source) pdf_report = html_report.write_pdf() # print("check : ", pdf_report[:5]) # It gives proper content beginning (PDF header) pdf_bytes = BytesIO(pdf_report) pdf_file = … -
Forms not displaying properly when using django with tailwind and crispy forms
When using {{ form|crispy}} filter in the index.html file, the form input fields are not shown with borders as they should be when using Crispy Forms. I have followed the BugBytes YouTube video TailwindCSS and Django-Crispy-Forms - Template Pack for Django Forms! I am looking for help with getting the Crispy filter working with a Django form. Here is the html page Here is the html page I am using Django 5.1.4 with crispy-tailwind 1.03 and django-crispy-forms 2.3 using python 3.12.8 The output css files are being built correctly and referenced in the html. This is demonstrated by using tailwind styles in the (template) html files. I am using Pycharm as my IDE. I have created a Django based project with a virtual environment included in the project directory. Node.js has been installed. The following are command line instructions and excerpts are from relevant files (apologies for it being so long ...): Setup commands run from the .venv npm install -D tailwindcss npx tailwindcss init npx tailwindcss -i ./static/css/input.css -o ./static/css/style.css --watch The last command is used to create and update the tailwind stylesheet. package.json "devDependencies": { "tailwindcss": "^3.4.16" } tailwind.config.js (entire file) /** @type {import('tailwindcss').Config} */ module.exports = { … -
How to import stripe? [closed]
I am trying to import stripe library into my Django app but it says << stripe is not accessed >> I installed it correctly, I activated my virtual environment, I use python -m pip install stripe, I use pip install too. I use pip list command and it's in my list. There is no name conflict or anything else but still when I do << import stripe >> I have the problem I mentioned. virtual environment is activated : pip install stripe pip install stripe== version python -m pip install stripe pip list -
I'm developing a web application using django and ajax for checklist. I have total of 140 checklist
I'm developing a web application using django and ajax for checklist. I have total of 140 checklist each checklist have header(meta data about that particular checklist), body of the checklist, and signature footer where certain users can click the ticket box and close the checklist. These 140 checklist are of 28 different types with different structures. Now I stored that each checklist as json data and created different templates and views for each types. Is it good way or is there any other better way to do this.. I'm a new developer and I can't get satisfied with my approach to this solution like there is a better solution. As I'm a new developer. Even though I can get solution to my problems but there is a feeling that is not the best solution until I get the best solution I can't get satisfied with this approach -
Faster table of content generation in Django
I am trying to make a table of content for my queryset in Django like this: def get_toc(self): toc = {} qs = self.get_queryset() idx = set() for q in qs: idx.add(q.title[0]) idx = list(idx) idx.sort() for i in idx: toc[i] = [] for q in qs: if q.title[0] == i: toc[i].append(q) return toc But it has time complexity O(n^2). Is there a better way to do it?