Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I output only the last form submission in for a form. Using React and javascript here. Thank you
Currently, I have a form on a page. I wish to display the latest form submission below the form, but it will display all the form submissions till date. I am wondering how to approach this issue. I have no idea how to approach this issue. I tried several methods, such as using data filter, or using an if else statement to see if the input value is same as the latest logged value. However, I have no idea what to pass in as the argument and I keep getting errors.. Hope I can receive tips on how to tackle this issue. Thank you so much. This is the frontend render of the website This is an example of the backend database. Please let me know if you guys require any extra information. Thank you so much! -
CSRF Token issue in Django app deployed in Railway, "CSRF verification failed. Request aborted."
The error I get is "CSRF verification failed. Request aborted." Error Image The site works fine and there are no issues on localhost I tried adding this base domain in my settings.py but I am still getting the same error: enter image description here I also tried this fix, and reloaded the requirements.txt but to no avail: enter image description here Any help would be appreciated. -
How to change link in Django admin backend "Webseite anzeigen"
I am developing a Django app and using both the admin backend and the developed website, which I refer to as the frontend, for the user. In the admin backend, there is a button "Webseite anzeigen" (Django German version) located at the top right corner. The code for this button is provided by Django. This button leads to the website or the frontend. I want to modify this button but I am not sure where to find it. For example, I want to increase the font size and change the color. -
Django app sending jwt token and refresh token to browser cookie but why my frontend app couldn't verify it?
I am using jwt authentication on my Django app. When user login to my website my server sends jwt token and refresh token to the browser cookie but I am getting "User is not authenticated." error and not getting any profile data for my user_profile/ api endpoint. Even I can see jwt token and refresh token also avaiable on the browser cookie after user login and aslo {withCredentials:true} in my axois post. here is my login code: @api_view(['POST']) def user_login(request): if request.method == 'POST': ...others code refresh = RefreshToken.for_user(user) response = Response({'message': 'Login successful.'}, status=status.HTTP_200_OK) response.set_cookie('jwt_token', str(refresh.access_token)) response.set_cookie('refresh_token', str(refresh)) return response else: return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED) here is my api for get user profile @api_view(['GET']) def get_user_profile(request): if request.user.is_anonymous: return Response({'error': 'User is not authenticated.'}, status=status.HTTP_401_UNAUTHORIZED) user = request.user profile = Profile.objects.get(user=user) data = { 'username': user.username, } return Response(data, status=status.HTTP_200_OK) my settings.py REST_FRAMEWORK = { 'DEFAULT_SCHEMA_CLASS': 'drf_spectacular.openapi.AutoSchema', 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), } my frontend code: axios.get(`${CustomDomain}/user_profile/`,{withCredentials:true}) .then((res) => { console.log(res); }) .catch((error) => { console.error(error); }); }) ; -
How to show items in dropdown based on alphabet search from Model in Django?
Just like Stackoverflow Tags auto-complete dropdown, I have a model of name Tags which contains 68311 name of Tags and key which contains the first alphabet it starts with. **Note ** : There are few words which starts with dot (.) for example, (.post) in that case, we will consider the second alphabet. class Tags(models.Model): name = models.CharField(max_length=255) key = models.CharField(max_length=1, null=True, default='') def __str__(self): return self.name def save(self, *args, **kwargs): if not self.key: if self.name.startswith('.'): self.key = self.name[1].upper() else: self.key = self.name[0].upper() super().save(*args, **kwargs) class Meta: indexes = [ models.Index(fields=['name']) Following is the view I am using to search the possible words starts with the user specified alphabet. def tag_search(request): search_term = request.GET.get('search', '') print("search_term", search_term) if search_term.startswith('.'): search_term = search_term[1].upper() else: search_term = search_term[0].upper() tags = Tags.objects.filter(name__istartswith=search_term).values_list('name', flat=True) return JsonResponse({'tags': list(tags)}) When I try to input any character from frontend on the auto=-complete dropdown, It executes tag_search only once and provide the words which contains first character that the user provider. What I required is when the user delete the first character and delete and type another one, then it should not show the result of previous written character. For example, I refreshed the page, and in auto-complete … -
Why date from data base dont show on home.html Python Django
The problem is that date from database that i have created doesnt show on my html page and i dont understand what is the problem maybe i connected something wrong models.py from django.db import models class table_1(models.Model): datetime = models.DateField() machine_1 = models.IntegerField() machine_2 = models.IntegerField() dryer = models.IntegerField() machine_1_time = models.TimeField() machine_2_time = models.TimeField() dryer_time = models.TimeField() def __int__(self): return self.title settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'data', 'USER': 'postgres', 'PASSWORD': '1221', 'HOST': 'localhost', 'PORT': '5432', } } home.html <h2>1{{ tablet.machine_1_time }}</h2> {{ mytable.machine_1 }} {% for item in tablet %} <h3>{{ item.datetime }}</h3> <!-- Выведите другие поля модели --> {% endfor %} views.py from django.shortcuts import render from .models import table_1 def home(request): tablet = table_1.objects.all() return render(request, 'table/home.html', {' tablet': tablet}) When i runserver there is no data shown at all machine_data.sql create table machine_dara ( datetime DATE, machine_1 INT, machine_2 INT, dryer INT, machine_1_time INT, machine_2_time INT, dryer_time INT ); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2022-12-31', 55, 77, 35, 84, 91, 63); insert into machine_dara (datetime, machine_1, machine_2, dryer, machine_1_time, machine_2_time, dryer_time) values ('2023-01-14', 67, 69, 79, 80, 50, 64); insert into machine_dara (datetime, machine_1, machine_2, dryer, … -
Django chunked upload
I have a Django app in which the user can upload a tdms file. When I deploy it, this does not work for large files, which is why I want to implement chunked upload through the django-chunked-upload library. I gave it a go, but I really need help. I get this feedback in my terminal: "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {'resumableChunkNumber': ['5'], 'resumableChunkSize': ['1048576'], 'resumableCurrentChunkSize': ['1339055'], 'resumableTotalSize': ['5533359'], 'resumableType': [''], 'resumableIdentifier': ['5533359-VibrationLog_2023-05 -05-084134tdms'], 'resumableFilename': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableRelativePath': ['Vibration Log_2023-05-05 - 084134.tdms'], 'resumableTotalChunks': ['5']}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload/?resumableChunkNumber=5&resumableChunkSize=1048576&resumableCurrentChunkSize=1339055&resumableTotalSize=5533359&resumableType=&resumableIdentifier=5533359-VibrationLog_2023-05-05 -084134tdms&resumableFilename=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableRelativePath=Vibration%20Log_2023-05-05%20-%20084134.tdms&resumableTotalChunks=5 HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 <QueryDict: {}> [19/Jun/2023 14:50:44] "POST /tdms/api/chunked_upload_complete/ HTTP/1.1" 302 0 [19/Jun/2023 14:50:44] "GET /tdms/list_vibration_logs/ HTTP/1.1" 200 7346 which seems okay, but the file does not get saved anywhere. This is my models.py: from django.db import models from nptdms import TdmsFile import json import pytdms from chunked_upload.models import ChunkedUpload # Create your models here. class VibrationLogChunkedUpload(ChunkedUpload): name = models.CharField(max_length=100, blank=True, null=True) notes = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) data = models.JSONField(blank=True, null=True) sample_frequency = models.FloatField(blank=True, null=True, default=8533.33) tdms_file = models.FileField(upload_to='tdms') … -
Custom submit button's name isn't added to request.POST when I add the record in Django admin
Let's say I have model Record with the approved flag class Record(models.Model): approved = models.BooleanField(default=False) I want to add Save and approve button in Record's admin near the Save button. For that I added new imput tag in the submit_line.html: {% extends 'admin/submit_line.html' %} {% load i18n admin_urls %} {% block submit-row %} {{ block.super }} {% if show_save %} <input type="submit" value="Save & approve" name="_save_and_approve"/> {% endif %} {% endblock %} Now I see this button and _save_and_approve appears in the request.POST when I edit the created record, but this name doesn't exist in the request.POST when I try to add a new one. So, the custom button works only when I edit the record. What I'm doing wrong? I use Django 4.1 P.S. Things I've tried so far: tried overriding the change_form.html with adding change_form_template to admin.Model class tried using both templates: change_form.html and submit_line.html tried adding add_form_template to admin.Model class with relation to change_form.html checked all relateed topics -
Displaying images from an EPUB file along with text using ITEM_DOCUMENT in Python
I'm currently working on a Python project where I need to extract text and images from EPUB files and display them together. I'm using the ITEM_DOCUMENT method from the epublib library to extract the text successfully. However, I'm facing difficulties in extracting and displaying images alongside the text. Here's a simplified version of my code: class PDFtoBookCreateView(CreateView): template_name = 'pdf_viewer.html' model = EBook def get_context_data(self, **kwargs): context={} book = epub.read_epub("H:/Hexcoder/sellzzy/new2_developer02/tshirtbundle/static/epub/9781408855713.epub") epub.EpubBook.get_template = new_get_template epubObj= book.get_items_of_type(ebooklib.ITEM_DOCUMENT) epubObjList= list(epubObj) context['finalTextList'] = [xhtml_to_html(i.content) for i in epubObjList] return context I'm able to retrieve the text content using the ITEM_DOCUMENT method, but I'm unsure how to extract and incorporate the images into the display. I've tried exploring the EPub library's documentation, but I couldn't find specific guidance on this matter. Could someone please provide guidance on how I can extract images from the EPUB file using Python, and integrate them into my display alongside the extracted text? Any example code or pointers to relevant resources would be greatly appreciated. Thank you! -
How can I Mock OpenSearch Client in Django unit test
I'm trying to mock OpenSearch client for writing unit tests for those methods using OpenSearch operations i.e. index, delete, etc. I have tried openmock library's decorator but in git workflow test it couldn't connect to OpenSearch client. -
giving user's ip address and display it in admin.py of a django project
how can i give ip address of users and display it in admin.py of django project? I created view of it but i don't know how to display it in admin panel this is my view function : `def get_ip_address(request): user_ip_address = request.META.get('HTTP_X_FORWARDED_FOR') if user_ip_address: ip = user_ip_address.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def show_ip_address(request): user_ip = get_ip_address(request) return render(request, "output.html", {"user_ip":user_ip})` ...................................................................................................... -
Django App for azure authentication python 3.7
I have a Django web app that runs on Python 3.7 and I want to integrate user authentication with Azure Active Directory in my web app. There is a Django app "django-azure-auth" & "django-azure-auth 1.1.0" but it requires Python >=3.8. Can anyone please suggest to me a Django app that supports Python 3.7? -
how to connect an existing mongdb database which has collection and fields to a website in django frame work
Is there a solution or approach to reuse an existing MongoDB database for a website instead of creating a new one, given that both have the same structure? I want to avoid the hassle of setting up a new database and ensure efficient utilization of resources. The objective is to leverage the existing MongoDB database, which already has the desired structure, for my website. By reusing the database, I can avoid duplicating efforts and maintain consistency in data management. I'm seeking guidance on the logic or code required to accomplish this task. Ideally, I would like to establish a connection to the existing MongoDB database, ensuring that the website can interact with it seamlessly. I want to perform CRUD operations, such as retrieving data, updating records, and executing queries, based on the needs of my website. Furthermore, I need to adapt the retrieved data from the database to suit the requirements of my website. This may involve transforming the data into a format compatible with web pages or other components of the website. Ultimately, I aim to integrate the existing MongoDB database with my website, allowing it to serve as the backend data storage solution. By reusing the database, I … -
How can I create mock a manytomany field for django pytest?
I am trying to create mock data for test in django. I have team model like this: class Team(TimeStampedModel): id: int created: datetime name = models.CharField(max_length=100) members = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="teams", through="Membership" ) And here is the part of test file: class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=admin1, created=datetime.datetime.now(), ) ] This case, I get error: def __set__(self, instance, value): > raise TypeError( "Direct assignment to the %s is prohibited. Use %s.set() instead." % self._get_set_deprecation_msg_params(), ) E TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use members.set() instead. So, I tried class TestTeamListViews: def test_team_list( self, client: Client, mocker, site_admin_user: User, team_with_members: Team ): admin1 = team_with_members.members.get(email="admin1@example.com") mock_teams = [ Team( id=1, name="Test Team", members=Team.members.set(admin1), created=datetime.datetime.now(), ) ] Then, I get error: AttributeError: 'ManyToManyDescriptor' object has no attribute 'set' I googled a lot, but there is no solutions I could found other than using add instead of set. Using add gives same error. Please help me. -
How do i make custom api calls in Ant design's filters/Search in a table columns?
I have a React application where I'm implementing a filter feature for the columns of my table. The goal is to make the search in the back and get an updated datasource that fit the search criteria or filter criteria. However, I'm facing an issue where the API requests continue endlessly, even after implementing a timeout mechanism. here is one of the columns : { title: "Project visibility", dataIndex: "projectVisibility", filters: filterLists.projectVisibilityFilters, onFilter: (value) => { console.log("onfilter method", value); dispatch(setColumnSearchValues("projectVisibility", "filter", value)); if (timeoutId > 500) { clearTimeout(timeoutId); } else { console.log("how many times i am in the else !!"); timeoutId = setTimeout( dispatch( RequestSearchColumns( advancedSearchForm, quickFiltersForm, columnsFiltersForm, currentPage, pageSize ) ), 500 ); } console.log("time taken to reach the back !!", timeoutId); }, onFilterDropdownOpenChange: (visible) => { if (visible) { setTimeout(() => searchInput.current?.select(), 500); } }, render: (value, row, index) => { isUnavailableValue(value); switch (value) { case "Confidential": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="red" text={value} /> </div> ); case "Visible": return ( <div className="custom-width-column w-120"> <div className="blur-layer"></div> <Badge color="#52C41A" text={value} /> </div> ); default: if (isUnavailableValue(value)) { return unavailableValue(value); } else { return ( <div className={ row.isConfidential ? "blur-content custom-width-column w-120" : "custom-width-column w-120" }> <div … -
How to not escape a character in a Django ORM?
I use Django, ORM. I don't want the character '%' to be escaped. name='' author='' annotation = 'harry%magic%school' criterion_name = Q(name__contains=cleaned_data['name']) criterion_author = Q(name__contains=cleaned_data['author']) criterion_annotation = Q(name__contains=cleaned_data['annotation']) Book.objects.filter(criterion_name, criterion_author, criterion_annotation) I get '%harry\%magic\%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry\%magic\%school%' I want to get '%harry%magic%school%': select name, author, annotation from books where name LIKE '%%' AND author LIKE '%%' AND annotation LIKE '%harry%magic%school%' How to fix it? -
I am unable to Add to Cart as Anonymous User using session key
I am developing a ecommerce website using Python Django framework. Code is proper and actively working when user login but not working as a guest. I am unable to Add to Cart as Anonymous User using session key. models.py class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) product_qty = models.IntegerField(null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True) session_key = models.CharField(max_length=140, null=True) cart.py from django.http import JsonResponse from django.shortcuts import render, redirect from django.contrib import messages from buyjoi.models import Product, Cart from django.contrib.auth.decorators import login_required def addtocart(request): if request.method == 'POST': if request.user.is_authenticated: prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(user=request.user.id, product_id=prod_id)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( user=request.user, product_id=prod_id, product_qty=prod_qty) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) else: request.session['product_id'] prod_id = int(request.POST.get('product_id')) product_check = Product.objects.get(id=prod_id) if (product_check): if (Cart.objects.filter(product_id=prod_id, session_key=request.session.session_key)): return JsonResponse({'status': "Product Already in Cart"}) else: prod_qty = int(request.POST.get('product_qty')) if product_check.quantity >= prod_qty: Cart.objects.create( product_id=prod_id, product_qty=prod_qty, session_key=request.session.session_key) return JsonResponse({'status': "Product added successfully"}) else: return JsonResponse({'status': "Only " + str(product_check.quantity) + " quantity available"}) else: return JsonResponse({'status': "No such product found"}) return redirect("/") def … -
Django and Docker: ModuleNotFoundError: No module named 'widget_tweaks'
I'm trying to use django-widget-tweaks in my web application (using Django and Docker), but it is not being recognized as an installed package. My DockerFile: # Pull base image FROM python:3.10.2-slim-bullseye # Set environment variables ENV PIP_DISABLE_PIP_VERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt RUN pip3 install django-widget-tweaks # Copy project COPY . . My settings.py: INSTALLED_APPS = [ 'users.apps.UsersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'openai', ] INSTALLED_APPS += [ 'widget_tweaks', ] The error: Exception in thread django-main-thread: project-web-1 | Traceback (most recent call last): ... project-web-1 | ModuleNotFoundError: No module named 'widget_tweaks' -
Docker in Github actions
I am building a Django application in Docker. In one of my tests, I am calling a function that uses celery[redis] for background task. Currently, I want to make a CI (github actions) that checks linting and tests my app whenever pushed to certain repositories. I am getting this error whenever I try run this workflow: Error -3 connecting to redis:6379. Temporary failure in name resolution. ` name: Django CI on: push: branches: [ "main", "master"] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: max-parallel: 4 matrix: python-version: [3.9] steps: - uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install -r requirements.txt - name: Lint with flake8 run: | pip install flake8 flake8 - name: Build and run docker run: docker-compose up --build -d - name: Coverage report env: STRIPE_API_KEY: ${{ secrets.STRIPE_API_KEY }} EMAIL_HOST_USER: ${{ secrets.EMAIL_HOST_USER }} EMAIL_HOST_PASSWORD: ${{ secrets.EMAIL_HOST_PASSWORD }} run: | coverage run manage.py test coverage report - name: Stop containers if: always() run: docker-compose down ` But if I try to pass docker-compose run --rm [service] sh -c "coverage run manage.py test" instead of coverage run manage.py test everything … -
Django Upload File API Endpoint
so I have a view in my Django website that is supposed to accepted uploaded backup files and save a backup record to the database. It's meant to accept http post requests with a file and user credentials so that I can associate backup uploads to each user. I also created a different script entirely to test if this works and it's been fine when I upload small files but keeps failing when I try and upload large files (e.g. 100mb +). I'm not sure if there's a better way to do this or if I'm making a mistake somewhere. views.py: @csrf_exempt def upload(request): if request.method == 'POST': try: file = request.FILES['file'] # check file type before saving. only allow .zip files if not file.name.endswith('.zip'): return HttpResponse("Invalid file type. Only .zip files are allowed.", status=415) # get the user credentials from the request username = request.POST.get('username') password = request.POST.get('password') # authenticate the user user = authenticate(request, username=username, password=password) if user is None: return HttpResponse("Invalid credentials", status=401) saveDir = os.path.join('backups/', user.username) savePath = os.path.join(saveDir, file.name) storage_left = user.profile.max_storage - user.profile.used_storage backup = Backup(user=user, file=file) backup.file.name = savePath backup.save() if backup.filesize > storage_left: response_str = f"Could not upload file {backup.basename}. " \ … -
What are the appropriate configurations for the WSGIDaemonProcess if memory is not being released?
I have a Django application which is hosted using Apache and a WSGI Daemon Process. It fetches large amounts of data from a database, and I have an issue where it won't release the RAM after completing the request if the request was large and/or many requests come in at the same time. I've tried debugging this without touching the server configuration (since I don't have editing privileges on the server and need to request the change), but my last hope is changing the options on the WSGI Daemon process to mitigate the problem. It is currently set to processes=2 threads=5, nothing else is configured. I have read through the documentation of the different configuration options, but I am unsure what an appropriate configuration for my use case would be. The site doesn't see a lot of traffic (probably only used once or twice a day), but when it IS being used, it will have to handle large amounts of data and 100-500 requests in relatively short sucession. So I don't want to set the maximum-requests too low, but since the site doesn't see traffic regularly, the RAM might never be released if the limit isn't reached. Would a restart-intervall … -
__isnull not working in Django ORM in test method
In my test setup: def setUp(self): self.myitem_1 = mommy.make(MyModel, my_field=None) ... In the test: result = MyModel.objects.my_field__isnull().all() self.assertEqual(result.count(), 1) I was expecting is null to work for None, but doesn't count the value. Test fails as 0 != 1 What am I missing? -
Making a that enables 'GET' without token but not posts without tokens
I recently started working with Django backend development, so I'm still struggling with some features. This time, I've encountered a problem that has been quite challenging, and I couldn't find any helpful answers on the web. I'm creating a view that supports both 'GET' and 'POST' requests. The issue I'm facing is that while I need a Bearer token for the 'POST' request, I don't want to require a token for the 'GET' request. Initially, I considered creating a separate view just for the 'GET' request, but that seemed redundant. Then, I came across the 'IsAuthenticatedOrReadOnly' permission class in the Django Rest Framework documentation. I thought this would solve my problem, but even after implementing this verification, the 'GET' endpoint still asks for a token. Could someone please provide me with some insights? Here's my view: from rest_framework.views import Request, Response, status, APIView from .serializers import MovieSerializer from rest_framework_simplejwt.authentication import JWTAuthentication from rest_framework.permissions import IsAuthenticatedOrReadOnly from movies.models import Movie class MovieView(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticatedOrReadOnly] def post(self, request: Request) -> Response: serializer = MovieSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(user = request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) def get(self, request: Request) -> Response: movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ...and … -
Django generic List View with multiple query search
Hello I'm working with class based views in Django and I want to create a search form for users to find their own favourite products in my app with multiple filters and excludes but I couldn't do it. my code is here if anyone can modify it to make it right please help me out : models.py from django.db.models import models from django.core.validators import RegexValidators class Product(models.Model): num=RegexValidators(r'^[0-9a-zA-Z]*$') title = models.CharField(max_length=100) embed_id = models.CharField(max_length=15, validators=[num]) description = models.TextField(null=True, blank=True) forms.py from django import forms class ProductSearchForm(forms.Form): title = forms.CharField(required=False) embed_id = forms.CharField(required=False) description = forms.CharField(required=False) views.py from django.views.generic import ListView from .models import Product from .forms import ProductSearchForm class ProductListView(ListView): model = Product form_class = ProductSearchForm template_name = 'pages/product/list_products.html' def get_queryset(self): queryset = super().get_queryset() form = self.form_class(self.request.GET) if form.is_valid(): title = form.cleaned_data.get('title') embed_id = form.cleaned_data.get('embed_id') description = form.cleaned_data.get('description') if title: queryset = queryset.filter(title__icontains=title) if embed_id: queryset = queryset.filter(embed_id__icontains=embed_id) if description: queryset = queryset.filter(description__icontains=description) return queryset def get_context_data(self, [**kwargs): context = super().get_context_data(self, **kwargs): context['form'] = self.form_class(self.request.GET) return context I know how to handle this in Function based views, but I want to create its generic.listview. -
Why isn't it recommended to use bare HTTP status codes in a response?
According to the documentation for Django REST Framework, "using bare status codes in your responses isn't recommended". They recommend instead using the objects from the status module (e.g. status.HTTP_404_NOT_FOUND). My question is, where does this recommendation come from? I wasn't able to find any kind of 'official' source for this recommendation.