Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Session Timeout on User side in Django
I am trying add a session timeout in my Django project by using Django's in-built session middleware. I have implemented session timeout on my project using the Views method I have come across for this purpose and it is working on my Admin side, but in my User side, the redirection that I given not working (i.e. I need to log out the user and get back to the signin page after session expires). My django version : 5.0.2 My python version: 3.12.2 Now it is taking the time and that page will expire but it will not redirect to the signin page. How can I solve this issue? What are some other approaches we can use for implementing Sessions on Admin & User sides both redirecting to the Signup page and persisting the last page worked on upon logging back in ?settings.pymiddilewareViews.pyurls.py -
Hi, i need help passing my cv2 yolov8s video feed to a django application i got for my project
Im new to neural network development i got pretrained YOLO8s model and trained it on my custom dataset, made a python class, using cv2 to display the results now i need help passing my cv2 yolov8s video feed to a django application i got for my project, how do i do that? ''' from ultralytics import YOLO from pathlib import Path import cv2, onnx, onnxoptimizer,numpy,onnxruntime import torch.onnx import torchvision.models as models from database.db import * from pprint import pprint as pt class Main_field: def __init__(self, model, size, source, conf_): self.model = self.load_model(model) self.size = size self.source = source self.conf_ = conf_ def __call__(self): self.process_video() def load_model(self, model): model.fuse() return model def process_video(self): cap = cv2.VideoCapture(self.source) while True: ret, frame = cap.read() if not ret: break results = self.model.predict(frame, conf=self.conf_, imgsz=self.size) masks_dict=[result.names for result in results][0] xyxys=[result.boxes.cpu().numpy().xyxy for result in results][0] #xyxy mask_ids=[result.boxes.cpu().numpy().cls.astype(int).tolist() for result in results][0] masks=[masks_dict[itr] for itr in mask_ids] db_output=[check_(local_list,str(itr)) for itr in mask_ids if itr] video_outp=cv2.imshow("_________", results[0].plot()) pt(mask_ids) if cv2.waitKey(1) & 0xFF == ord('q'): break def __del__(): cap.release() cv2.destroyAllWindows() def init_model(path: str) -> any: return YOLO(path) ''' looking for examples on how can i pass constant video feed to my web page -
Problem when trying to generate PDF files within Django with libreoffice
I have a Django application based on the 3.10.11-alpine3.16 image that runs in docker container. When I check during the build if a sample PDF is generated, this will succeed, and I see that when running with root it is okay. The problem is that when I try to issue the same command in the running container's terminal, I got an error and I don't know why. In my dockerfile I have the commands to isntall the libreoffice: RUN apk add --no-cache xmlsec xmlsec-dev libreoffice libreoffice-writer libreoffice-calc libreoffice-impress libreoffice-base ttf-dejavu unzip wget curl openjdk11-jre This commands runs perfectly during build in the name of the root user: RUN soffice --headless --convert-to pdf --outdir /vol/logs /vol/logs/word_sample_01.docx If I try to run the same command when I logged into the docker's terminal, so for example: /usr/bin/soffice --headless --convert-to pdf --outdir /vol/logs/t/ /vol/logs/word_sample_01.docx I get this error: "Unspecified Application Error" I assume it is related to some permissions, but I can't figure it out which one is missing... Any hints? -
After scheduling a new task, previously scheduled tasks are not getting executed by Celery Beat (Django)
I have a Django (4.2.2) app running with Python (3.10.12), Celery (5.4.0), Celery Beat (2.6.0), Django Celery Results (2.5.1), Redis and Postgres. Here is my celery configuration: CELERY_BROKER_URL = "redis://localhost:6379/3" from __future__ import absolute_import, unicode_literals from celery import Celery from django.conf import settings import os import django # Set the DJANGO_SETTINGS_MODULE before calling django.setup() os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auctopus.settings') django.setup() # Initialize Celery app = Celery('proj') app.conf.enable_utc = False app.conf.broker_connection_retry_on_startup = True app.conf.task_serializer = 'json' app.conf.accept_content = ['application/json'] app.conf.result_serializer = 'json' app.conf.timezone = 'Asia/Kolkata' app.conf.cache_backend = 'default' app.conf.database_engine_options = {'echo': True} app.conf.result_backend = 'django-db' app.conf.result_expires = 3600 app.conf.task_time_limit = 1000 app.conf.task_default_queue ='default' app.conf.worker_concurrency = 6 app.config_from_object(settings, namespace='CELERY') # Autodiscover tasks from installed apps app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_scheduler = 'django_celery_beat.schedulers:DatabaseScheduler' After Django application starts, it creates several schedulers automatically such as internet_status_check, system_resource_check, etc. using IntervalSchedule. At first, it runs smoothly, but as soon as I create any new scheduler be it an IntervalSchedule or CrontabSchedule, previously running schedulers stop execution. I get a message in celery beat terminal also saying DatabaseScheduler: Schedule changed. After this message it does not send any task for execution even if tasks are available for execution which can be seen from Django admin panel. I tried changing broker to … -
How to integrate different user types in djando UserModel?
I have a question regarding the user model in django. My project is to realize an area management system. The following entities have already been modeled: Building Area Area equipment (e.g. which furniture etc) SpaceUser (assignment between space and user) SpaceRequirement (request from a user) Users (those who were, are and will be on the space) Supervisor (user who is responsible for certain areas or buildings) TypeOfUse (e.g. office, laboratory, etc.) Organization (organizational affiliation to team/department etc) Landlord As a special case, the management of workshop spaces that are to be bookable at short notice is managed in the following entities: WorkshopSpace (space x in building y) WorkshopSpaceRequirement (request from a user) The attributes of the entities are: Supervisor firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) organisation = models.ForeignKey('Organization', verbose_name='Organization', on_delete=models.CASCADE) email = models.EmailField(verbose_name='Email') phone_number = models.CharField(max_length=20) Users: organisation = models.ForeignKey('Organization', verbose_name='Organization', on_delete=models.CASCADE) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) mgmt_level = models.CharField(max_length=10, choices=CATEGORY_CHOICES, default=E4, verbose_name='Level') cost_center = models.CharField(max_length=50, blank=True) number_employees = models.IntegerField(default=0, verbose_name='Number of employees') number_workstations = models.IntegerField(default=0, verbose_name='Number of workstations') superior = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) comment = models.TextField(blank=True) Unfortunately, I made the mistake of implementing the models without taking the django user model into account. I would now like … -
requirements.txt file packages version upgrade in django project
While I'm upgrading the packages in my django project and run locally it won't raise any error but when I am pushing the code to dev environment, it shows me internal server error I'm not sure is it because of the upgradation or is it because of the CI CD pipeline. I upgrade the django version from 3.2 to 4 2.3 and some other packages and all the thing are working fine in local but not in dev environment -
payments import from python_flutterwave not working.... python 3.12.4
This is the inport i have in my code from python_flutterwave import payment But i am getting an error: ImportError: cannot import name 'payment' from 'python_flutterwave' (C:\Users\HP\Downloads\Compressed\STechnologies-Suite\STech-Agent-Suite\env\Lib\site-packages\python_flutterwave_init_.py). How is this possible yet according to the docs, it should be working just fine. -
ValueError on autofield on my Django Project
I'm trying to make a music streaming website using Django. I have this error when i use the terminal command migrate: ValueError: Field 'song_id' expected a number but got ''. I don't understand where "song_id" take a value that is not a number. How can i fix it? this is my views.py: def myPlaylist(request, id): user = request.user if user.is_authenticated: # Extracting Playlists of the Authenticated User myPlaylists = list(Playlist.objects.filter(user=user)) if user.is_authenticated: if request.method == "POST": song_id = request.POST["music_id"] playlist = Playlist.objects.filter(playlist_id=id).first() if song_id in playlist.music_ids: playlist.music_ids.remove(song_id) playlist.plays -= 1 playlist.save() message = "Successfull" print(message) return HttpResponse(json.dumps({'message': message})) else: images = os.listdir("music_app/static/PlaylistImages") print(images) randomImagePath = random.choice(images) randomImagePath = "PlaylistImages/" + randomImagePath print(randomImagePath) currPlaylist = Playlist.objects.filter(playlist_id=id).first() music_ids = currPlaylist.music_ids playlistSongs = [] recommendedSingers = [] for music_id in music_ids: song = Song.objects.filter(song_id=music_id).first() random.shuffle(recommendedSingers) recommendedSingers = list(set(recommendedSingers))[:6] playlistSongs.append(song) return render(request, "myPlaylist.html", {'playlistInfo': currPlaylist, 'playlistSongs': playlistSongs, 'myPlaylists': myPlaylists, 'recommendedSingers': recommendedSingers, 'randomImagePath': randomImagePath}) def addSongToPlaylist(request): user = request.user if user.is_authenticated: try: data = request.POST['data'] ids = data.split("|") song_id = ids[0][2:] playlist_id = ids[1][2:] print(ids[0][2:], ids[1][2:]) currPlaylist = Playlist.objects.filter(playlist_id=playlist_id).first() if song_id not in currPlaylist.music_ids: currPlaylist.music_ids.append(song_id) currPlaylist.plays = len(currPlaylist.music_ids) currPlaylist.save() return HttpResponse("Successfull") except: return redirect("/") # return redirect("/") else: return redirect("/") def likesong(request): myPlaylists = [] … -
I continuously receive `Invalid HTTP_HOST header` error email
I am using Django==4.1.2. I deployed my site using Docker on an Ubuntu server, and I am continuously receiving 'Invalid HTTP_HOST header' emails. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www.google.com'. You may need to add 'www.google.com' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'ad608a31b0be:8000'. You may need to add 'ad608a31b0be' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'www'. You may need to add 'www' to ALLOWED_HOSTS. [Django] ERROR (EXTERNAL IP): Invalid HTTP_HOST header: 'api.ipify.org'. You may need to add 'api.ipify.org' to ALLOWED_HOSTS. Here is my Docker file code FROM python:3.9 as build-python RUN apt-get -y update \ && apt-get install -y gettext \ # Cleanup apt cache && apt-get clean \ && rm -rf /var/lib/apt/lists/* # Install Python dependencies COPY requirements.txt /app/ WORKDIR /app RUN pip install -r requirements.txt RUN pip install --upgrade pip ### Final image FROM python:3.9-slim RUN groupadd -r tgcl && useradd -r -g tgcl tgcl RUN mkdir -p /app/media /app/static \ && chown -R tgcl:tgcl /app/ COPY . /app WORKDIR /app EXPOSE 8000 CMD ["gunicorn", "--bind", ":8000", "--workers", "4", "tgcl.asgi:application"] Here is my Django Settings ALLOWED_HOSTS = ['app.thegoodcontractorslist.com', 'www.thegoodcontractorslist.com'] CORS_ALLOWED_ORIGINS = [ "http://localhost:4200", "http://localhost:3000", "http://dev.thegoodcontractorslist.com", ] CSRF_COOKIE_SECURE = True CSRF_COOKIE_HTTPONLY = … -
Updating a Foreign Key in Django Rest Framework
these are my models in DRF: class Course(models.Model): title = models.CharField(max_length=100, unique=True) class Prerequisite(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="course_prerequisite") title = models.CharField(max_length=75) and my serializers: class CourseSerializer(serializers.ModelSerializer): prerequisite = serializers.SerializerMethodField() class Meta: model = models.Course fields = "__all__" def get_prerequisite(self, obj): serializer = PrerequisiteSerializer(obj.course_prerequisite.all(), many=True) return serializer.data class PrerequisiteSerializer(serializers.ModelSerializer): class Meta: model = models.Prerequisite fields = "__all__" and my view to retrieve a course: def retrieve(self, request, pk=None): course = get_object_or_404(Course, slug=pk) serializer = serializers.CourseSerializer(instance=course) return Response(serializer.data, status=status.HTTP_200_OK) now my question is imagine i did send a request to my api to retrieve a course with pk of 18 like this: { "results": [ { "id": 18, 'title': 'learn python in 30 days' "prerequisite": [ { "id": 1, "title": "Introduction", "course": 18 }, ], } ] } and now i want update the prerequisite with id of 1 what code should i add to my update view in CourseViewSet, i know i can create another view for prerequisites, but i want to do it in this way exactly like when you add TabularInLine in Django`s default admin panel when you can update and change a foreignkey! -
Removing {{ choice.tag }} in Django Template Breaks JavaScript Update Function for Radio Button Selection
In my Django application, I have a form with radio buttons for selecting the number of meals per week. The form also includes checkboxes for meal preferences. I have initialized a preselected value for these fields in my form. I use JavaScript to dynamically update a summary section based on preselected selections when page loads. The radio buttons for meals_per_week are generated by Django and included in the HTML template. If I remove {{ choice.tag }}, the updateSummary function no longer receives the selected value for meals_per_week. How can I fix this issue while still removing {{ choice.tag }}? Here is the relevant part of my HTML template: {% for choice in form.meals_per_week %} <div class="flex-fill mx-1"> <div class="card mb-4 custom-card" data-input-id="{{ choice.id_for_label }}"> <div class="card-body text-center"> <input type="radio" class="hidden-input" id="{{ choice.id_for_label }}" name="{{ choice.name }}" value="{{ choice.choice_value }}" {% if choice.is_checked %}checked{% endif %}> {{ choice.tag }} <label class="form-check-label d-block" for="{{ choice.id_for_label }}"> {{ choice.choice_label }} </label> </div> </div> </div> {% endfor %} And here is my JavaScript function that updates the summary: async function updateSummary() { const mealsPerWeek = **parseInt(document.querySelector('input[name="meals_per_week"]:checked').value);** const mealPreferences = Array.from(document.querySelectorAll('input[name="meal_preference_type"]:checked')).map(el => el.value); let response = await fetch(`/get_price?meals_per_week=${mealsPerWeek}`); let data = await response.json(); const pricePerServing … -
Django,Docker caching previsouly setup email in he settings.py
I have changed my backend email when I run in docker compose it uses the previous email thus an error but when i run in manage.py runserver mode there is no error. I want when i run in docker mode for it to read the new email that i have setup -
Calculating amount when saving in django admin
I am trying to calculate the total amount of a sale before saving it in the Django admin site. Sales data model Inventory data model The SaleItem is a through table to keep track of the quantity of each item sold in the sale. How do I calculate the total price of each item sold? enter image description here I've tried declaring a method called save to calculate the price of the items sold when saving the entry in the django admin, however im getting errors for trying to perform an operation on deferred attribute. -
Django GET request a page with a button
I have a django view with html template with a form and a few buttons. When one of the buttons is pressed it sends a get request with a query param and depending on this param I render the page again but with different json paramethers. However I can't return the webpage with a second return. This is the important code of the view for the question. I also tried this without return, but it doesn't work either. I tried using JsonResponce, but no success: def card(request): cur_rk = 0 if request.method == 'GET': if request.GET.get('C', '') == '-1': q1 = "SELECT MAX(RK) AS L_RK FROM B_DATA;" with connection.cursor() as cursor: cursor.execute(q1) val = cursor.fetchall() cur_rk = val[0][0] return render(request, "card.html", get_db_data(cur_rk)) return render(request, "card.html", get_db_data(cur_rk)) Here is the html code if it might help you: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create new card</title> </head> <body> <div class = "enter_data"> <form action = "" method="POST">{% csrf_token %} <div class = "base"> <h2>Базови данни</h2> <input type="number" class="field" placeholder="Enter RK" value = {{RK}} name="RK"> <input type="text" class="field" placeholder="Enter RN" value = {{RN}} name="RN"> <input type="text" class="field" placeholder="Enter Marka" value = {{Marka}} name="Marka"> <input type="text" class="field" placeholder="Enter … -
Django: Problem rendering and downloading HTML in PDF format, styles and resources are not applied correctly
I am trying to generate a PDF with data previously entered in Django, the base of the PDF is with HTML, when creating the HTML it is rendered in order and as I want when viewing it with the ""Live Preview" extension in Visual Studio Code, but when transform it to PDF in my project, it is generated badly and messy (I'm sorry if I describe myself badly, it's the first time I use this platform D:)The idea is that it looks something like this: HTML, but when you download the PDF it looks like this: Bad PDF As a reference to make the PDF functionality I used this video: https://www.youtube.com/watch?v=J3MuH6xaDjI, this is HTML that I am using to generate the PDF: <!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cotización - SOLUPLAST</title> <style> body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; } .container { max-width: 800px; margin: 0 auto; background-color: #fff; padding: 20px; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } .header { display: flex; justify-content: left; align-items: flex-start; } .logo { order: -1; } .header img { position: absolute; max-width: 120px; } .header .info { margin-top: 90px; text-align: left; … -
How can I use Google Cloud Storage and Local folders together using Django?
I have a Django app with my images on Google Cloud Storage, but I want to use just one image on the local folders This is my code: Settings.py GS_CREDENTIALS = service_account.Credentials.from_service_account_info(credentials_dict) DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_PROJECT_ID = 'projectid' GS_BUCKET_NAME = 'bucketname' STATICFILES_STORAGE='storages.backends.gcloud.GoogleCloudStorage' HTML: <img src="{% static 'img/testimg.png' %}" alt=""> I want to search just for one image, how can I do this? I tried removing Staticfiles_storage line, then django searched all the images on the local folders, instead of just one -
How to create a custom UI for admin interface in Django
Okay, I probably couldn't explain the issue in the title very well but I am building a Django app which will have various contributors. These contributors will not have superuser privileges but only some read/write privileges. Right now, I have a custom AdminSite which can be accessed by the Contributors. Here's the code: admin.py class ContributorAdmin(AdminSite): def has_permission(self, request): return request.user.is_active urls.py urlpatterns = [ path('admin/', admin.site.urls), path('contributor/', contrib_admin_site.urls), path('login/', loginview, name='login'), path('logout/', logoutview, name='logout'), #other paths for the app ] This is working as intended and gives the contributors access to the admin interface with limited privileges. However, what I would like to do is create a custom Admin UI (not the built-in Django one) which will be used by the Contributors. As an example, I would like to have a contributor.html in my templates which provides Admin like interface to the contributors but the styling etc. is all customized. Also, I would like to have my login and logout views to redirect to this custom page only. Right now, the login page redirects to ContributorAdmin so my custom logout view becomes useless. Is it possible to do this? Thanks in advance! -
Can I use hash partitioning on a non-primary key column in a PostgreSQL table?
I am trying to replace an existing table with a partitioned version of that table. I want the schema of the new partitioned table to exactly match the existing non-partitioned table so that I can continue to manage the table through Django migrations. My first attempt at creating the new partitioned table looked something like this: CREATE TABLE partition_test ( row_index bigint, id character varying(128) PRIMARY KEY, vendor_id character varying(128) ) PARTITION BY HASH (vendor_id); Which results in the following error: ERROR: unique constraint on partitioned table must include all partitioning columns DETAIL: PRIMARY KEY constraint on table "product_api_partition_test" lacks column "vendor_id" which is part of the partition key. I am looking for a work around that will allow me to partition on vendor_id while keeping row_index as the primary key. I tried modifying the primary key as follows, however, Django requires a primary key and does not support composite primary keys. Therefore, both of these options would result in an inconsistency between the true schema and what Django believes is the schema. CREATE TABLE partition_test ( row_index bigint, id character varying(128), vendor_id character varying(128) PRIMARY KEY (row_index, vendor_id) ) PARTITION BY HASH (vendor_id); CREATE TABLE api_partition_test ( row_index bigint, … -
Django Pagination with Titles Instead of Numbers
I have a lecture view which I have paginated to 1 lecture per page. I have created a separate list of all the lectures which I want to use as a navigation side bar to the different lectures. I want that side bar to display the lecture titles as links and not numbers. <ul class=""> {% for pg in lecture_single.paginator.page_range %} {% for lecture_x in lecture_single %} <li> <a href="?page={{ pg }}" class="btn">{{ lecture.title }}</a> </li> {% endfor %} {% endfor %} </ul> I tried using a for loops which did work in creating the links but all the lectures where being presented with the same title as opposed to a specific title for a different page -
How to connect sql server to djangorestframework
So I am working on a project and I have already populated the database in mysql workbench 8.3 and I am building an api so I trying to link my database in sql to my django api and I did it but it looks like the connection in my terminal is a brand new one and it isn't showing my databases that are on workbench so I am tried to change permission and give the connection in my terminal all the permission of root but that didn't really do anything. -
Image not found in my Django Project (only in one of the 2 pages)
i'm trying to display an home image at top of the page but it doesn't work. I have the same image in an other page and it works. also if i hold mouse on image source link on the ide it says me that the path is correct. . : Here is the line code (path in the images): <p><img src="../media/images/home.png" width="30px" alt="home image">HOME</p> -
Is this django test project rejected because of code structure?
Hello Dear Python Community, I created a django test project. the client was rejected with these reasons. Client Feedback 1 The code related to the recipe was looking fine but the use register and login code is good. It seems those API's will not even work well. So, I think we should not move forward. Client Feedback 2 Code structure does not looks good. Authentication is not implemented correctly. So, we should not move forward. Here the test project information Build a Recipe Sharing Platform 1. Framework:- Use Django framework to build the REST APIs. 2. User Authentication:- Implement user authentication and authorization to allow users to sign up, log in, and manage their recipes securely. 3. CRUD Operations: Enable users to perform CRUD operations (Create, Read, Update, Delete) on recipes they own. 4. Recipe Details: Include fields such as title, description, ingredients, preparation steps, cooking time, and serving size for each recipe. 5. Recipe Categories: Allow users to categorize recipes into different categories (e.g., starter, main courses, desserts). 6. Search and Filter: Provide functionality to search and filter recipes based on various criteria (e.g., category, ingredients, cooking time). 7. Rating and Reviews: Allow users to rate and review recipes, … -
Django->IntegrityError when Creating a record with a foreign key assign to it model
So I am Following a course of Django API and at last of my project is to create API for a Little Lemon restaurant.I have downloaded the Same Project Source code and now implementing it on my side.Currently i am stuck on a issue for 2 days now i have tried chatgpt, stack-overflow but there are no concrete solution.so the problem is i can't insert a menu-item in the DB. Beacuse it is thorwing an error of IntegrityError at /api/menu-items NOT NULL constraint failed: LittleLemonAPI_menuitem.category_id **This error occurs when i try to insert a menu-item using the Insomia. But if i create the same item using the Super User it is created. This is my View.** class MenuItemListView(generics.ListCreateAPIView): queryset = MenuItem.objects.all() serializer_class = MenuItemSerializer def get_permissions(self): permission_classes = [IsAuthenticated] if self.request.method != 'GET': permission_classes = [IsAuthenticated, IsManager | IsAd This is my Model: class MenuItem(models.Model): title = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2) featured = models.BooleanField(db_index=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) class Meta: unique_together = [['title', 'category']] def __str__(self): return self.title This is my Serializer class MenuItemSerializer(serializers.ModelSerializer): def validate_category(self, value): try: Category.objects.get(pk=value) return value except Category.DoesNotExist: raise serializers.ValidationError('Invalid category ID.') class Meta: model = MenuItem fields = ['id', 'title', 'price', 'featured', 'category'] … -
Django problem with downloading file from my computer
I am new in Django and I need some assist. I want to download the file which path is in plik.localisation(it has been taken from loop). The problem is with the path. Could someone help me what I am doing wrong? My view.py is: def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="application/pdf") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 Urls path('download/(?P<path>)$', serve,{'document root': path}, name="download"), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Html <div class="com"> {{plik.localisation}} <a href="{% url download/path %}" class="button">downloadz</a> </div> I've tried to change that path but still have problem with it. -
Input Validation with one Text Input and ChooseField of Model Fields in Django
I want to implement a Basic Search function to my Django Project I have a dropdown field with all model Fields of my userdb model. forms.py class searchForm(forms.Modelform): field=forms.ModelChoiceField(queryset=[f.name for f in MyModel._meta.get_fields()],widget=forms.Select(attrs={'class':'form-select','data-live-search':'true'})) class Meta: model=userdb fields='__all__' input=forms.CharField() How can I validate if the input of the input charfield is correctly Formated depending on the selected field in field.