Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF Serializer field's queryset not updating
I have a Django models: class Author(Model): name = CharField(max_length=256) class Library(Model): address = CharField(max_length=256) books = ManyToManyField(Book) class Book(Model): name = CharField(max_length=256) created_by = ForeignKey(Author, on_delete=CASCADE) I want Author to create new Libraries with Books by sending array with IDs, but limit book choices to only the ones created by author making request. I want this serializer to reject all books if author is not given. I have a serializer: class LibrarySerializer(ModelSerializer): books = PrimaryKeyRelatedField(many=True, queryset=Book.objects.none()) class Meta: model = Library fields = ("books", "address") def __init__(self, *args, **kwargs) self.author = kwargs.pop("author", None) super().__init__(*args, **kwargs) if self.author: self.fields["books"].queryset = Book.objects.filter(created_by=self.author) Now I run: author = Author(name="John") author.save() book = Book(created_by=author, name="book_one") book.save() serializer = LibrarySerializer(data={"books": [book.id], "address": "address_one"}, author=author) But when I validate the serializer by calling serializer.is_valid() there is an errors saying that given book does not exist. Do you know why it is rejected or how can I investigate that? -
while i am trying to access the files from postman and find patterns accordingly i am not getting the file from the pdf_file field
can anyone tell me how to get the file and extract data from it from postman class ReadPDFView(APIView): def post(self, request): data = request.data.get('pdf_file') # Assuming you want to extract text from the first page with pdfplumber.open(data) as pdfs : first_page_text=pdfs.pages[0] first_page_text= extract_text(pdfs) print(first_page_text) return Response(first_page_text) i tried this to get the result -
Is there a way to bind with DN using django-python3-ldap
Because there are some AD migrations coming up in our organization, I want to find the user using a specific field and binding with the corresponding DN rather than the sAMAccountName or userPrincipalName in our Django environment. When reading the django-python3-ldap docs I couldn't find if the package supports this. Is this true? Should I try to use another package that does supports this? -
condition for the uniqueness of the input data
I need names and surnames of the employees to not match. and so that an error occurs after trying to save changes if the same person is specified 2 times. What's wrong? class JrtnPerson(models.Model): rtn = models.ForeignKey(Drtn, verbose_name='Подразделение Ростехнадзора', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Имя и Отчество') surname = models.CharField(max_length=200, verbose_name='Фамилия') tel_mob = PhoneNumberField(verbose_name="Номер телефона мобильный", blank=True, null=True) tel_rab = PhoneNumberField(verbose_name="Номер телефона рабочий", blank=True, null=True) email = models.EmailField(max_length=100, verbose_name="Электронная почта", blank=True, null=True) # def str(self): # return '%s %s' % (self.surname, self.name) def save(self, *args, **kwargs): if not self.JrtnPerson.objects.filter(surname=self.surname, name=self.name).exists(): super(surname,name,self).save(*args, **kwargs) -
CSRF Missing Error in DRF + React + SimpleJWT
I have my backend deployed at http://11.11.11.11/api/ for APIs devloped with DRF. Django Admin panel is running at http://11.11.11.11/admin/ and my react frontend is running at http://11.11.11.11/. I am using SimpleJWT for the Authentication. When I login to the react frontend without logging out from the django admin panel It gives me the error CSRF token is missing (Error 403). However If i logout from the admin panel (which deletes the sessionID saved in cookies) I am able to login from my react frontend and here I am not sending any CSRF token or anything. Why this is happening? Why cant I login simultaneously in frontend and the backend? I tried creating an endpoint where frontend can get the CSRF token and pass it to the login api in X-CSRFToken header in order to get the access token and refresh token.. I didnt work. -
What can I do to optimize speed?
There are 5400 rows of data in the database and it takes too long to calculate them. In order to increase the calculation speed, I saved all possible combinations according to the filters in the database and I want to calculate on them. This function I wrote does not work fast enough and responds very late. I give random numbers with the random library but there will be real calculations. Example: score and history How can I make this calculation faster? Django==1.11 Python==3.5 from random import randint def ees_calculate(request): if request.user.is_superuser: if request.is_ajax() and request.method == 'POST': survey=request.POST['survey'] language=request.POST['language'] organization=request.POST['organization'] year=request.POST['year'] answer=request.POST['answer'] table=request.POST['table'] filters = { 'organization_filter': organization, 'survey_filter': survey, 'language_filter': language, 'year_filter': year, 'answer_filter': answer, 'table_filter': table } ees_combinations = models.Combination.objects.filter(**filters).values('id', 'demographic', 'gender', 'division', 'tenure', 'career_type_level') for combination in ees_combinations: dev0 = 0 avg_history = 0 answer_count = 0 answer_history_count = 0 combination_filter = { 'age_group': combination['demographic'], 'gender': combination['gender'], 'division': combination['division'], 'tenure': combination['tenure'], 'career_type': combination['career_type_level'], 'organization_filter': organization, 'survey_filter': survey, } filtered_answers = models.Answer.objects.filter(year_filter=year, **combination_filter).values('score') filtered_answer_history = models.Answer.objects.filter(year_filter__lt=year, **combination_filter).values('score') answer_count = len(filtered_answers) answer_history_count = len(filtered_answer_history) if answer_count > 0: avg_score = int(sum(answer['score'] for answer in filtered_answers ) / answer_count) if answer_history_count > 0: avg_history = int(sum(answer['score'] for answer in filtered_answer_history … -
In Django I can't see the user registration form on the home page
I'm new to Django, i would like to display the register.html registration form on the home page (index.html) and NOT on http://127.0.0.1:8000/register or similar. On the home page I want to see the various input textboxes. What am I doing wrong? How can I solve it? In the index.html page I don't use anything to call the form (register.html). Maybe I'm doing this wrong? App1/templates/registrazione/register.html {% extends "index.html" %} {% block content %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form.as_p }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} App1/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user App1/urls.py from django.urls import path from . import views urlpatterns=[ path('', views.index, name='index'), App1/views.py from .forms import NewUserForm from django.contrib import messages from django.contrib.auth.decorators import login_required def index(request): """View function for home page of site.""" return render(request, 'index.html') def register_request(request): if request.method == "POST": form = … -
Same records being added on unique constraints
I have added a unique together (badge_id, speech_id, badge_type) however I can still add data with same information, Attaching my schema as well I can explain one thing. unique constrain was applied and those column relation was DO_NOTHING and then in next migrations I updated it to CASCADE not sure if that is causing this misleading behavior of adding same rows. I double check if my django migrations were successful by extracting schema info from mysql, attached image. -
Django CORS cannot set cookie in HTTP
Premise I wanna use Django sessionid feature to identify which user was sending request. Therefore I need the user to login first and expect the user will bring the sessionid in their request header cookie then. What's wrong now login/ response header shows: This attempt to set a cookie via a Set-Cookie header was blocked because it had the "Secure" attribute but was not received over a secure connection. I'd like to find a way NOT to use https since it's just not quite a big project so I don't want to make too much effort on configuring https environments. Not sure if I set CORS or use sessionid feature correctly either. Related environment and codes I have a Django backend server in my local network Django 4.2.7 django-cors-headers 4.3.0 ip: http://192.168.10.200:8000 and my frontend dev environment (vue2.x) is on my own laptop ip: http://192.168.10.101:8888 my setting.py is like below # settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True SESSION_COOKIE_SAMESITE = "None" SESSION_COOKIE_SECURE = False SECURE_SSL_REDIRECT = False SESSION_COOKIE_HTTPONLY = True CORS_ALLOWED_ORIGINS = ["http://localhost", "http://127.0.0.1", "http://192.168.10.101"] views.py this … -
Challenges with Celery: Managing Long-Running Tasks and Communication Loss in Solo Mode
Good day to all. I've encountered an intriguing issue. I've developed a microservice using Celery that communicates with the main application through REDIS, where the main application also uses Celery. The problem is that I had to run the microservice worker in solo mode because certain functionalities don't operate properly in the regular mode (it's quite complex to explain what and why). Due to the solo mode and the extended task execution time, there is a loss of communication between the workers, causing tasks to re-enter the queue. This occurs because Celery assumes something has gone wrong when the worker doesn't respond for an extended period (tasks take up to 5 hours to complete). Increasing the task execution waiting time isn't feasible, as tasks re-enter the queue due to connection disruption. To avoid tasks re-entering the queue, the heartbeat was disabled. Despite my efforts, tasks still repetitively re-enter the queue even if the process is ongoing My Settings: app.conf.broker_connection_timeout = 10 app.conf.broker_connection_retry = 10 app.conf.result_extended = True app.conf.task_acks_late = True app.conf.task_track_started = True app.conf.task_publish_retry = False app.conf.broker_transport_options = {"visibility_timeout": 86400} app.conf.worker_max_memory_per_child = 10000 app.autodiscover_tasks() The following solutions to the problem were tried, but they did not help Running the microservice … -
crispy form height does not change
I have this problem with my {{ form|crispy }} it works just fine for one of my view but for the other one the fields are too thin and whatever I so the width does change but the height which I want to increase does not what should I do? if I need to post another part of code please let me know it looks like this Thanks in advance views.py from django.forms.models import BaseModelForm from django.http import HttpResponse from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from .forms import PostForm from .models import post from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from users.models import Profile from django.views.generic import UpdateView from django.views import View from django.contrib.auth import get_user_model @login_required() def new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): form.instance.author = request.user form.save() messages.success(request, f'Post created!') return redirect("/") else: form = PostForm() return render(request, "posts/new.html", {"form": form }) class PostUpdateView(LoginRequiredMixin, UpdateView): model = post fields = ['title','body'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) forms.py from django import forms from django.forms import ModelForm, Textarea from .models import post class PostForm(ModelForm): class Meta: model = post fields = '__all__' exclude = ('author',) widgets = { … -
How to check the details are correct or not without rendering the page in django?
I have created a registration form using django framework and in the phone number content how can I check the number is only equal to 10 digits without rendering the page, because when i render the page if the phone number condition is wrong whole input's will be deleted and return the page how can i handle that without deleting the data?? i have explained as above -
Prettier - How to format HTML files as expected, in a Django project
I have difficulties in formatting HTML files as expected. Here are some of them: (1) Expectation (before being saved): After being saved and formatted (not as expected): (2) Expectation (before being saved): After being saved and formatted (not as expected) : (3) Expectation (before being saved): After being saved and formatted (not as expected): My .prettierrc is as follow: { "singleQuote": true, "printWidth": 80, "useTabs": true, "overrides": [ { "files": ["**/*.html"], "options": { "printWidth": 150 } } ] } I feel like the expected ones make the file more readable. Am I missing some configurations in .prettierrc? Thank you -
Django 4.1 Static Files
I recently migrated from Django 3.8 to 4.1 without much issue, but since then, when I have DEBUG=True in my development environment, changes to Static Files are not reflected when refreshing the page, I instead have to reboot my dev environment. All other changes, including template changes and view changes are working as expected, just not static file changes. To fix the template changes issue I updated my templates variable from: { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] to: default_loaders = [ "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ] cached_loaders = [("django.template.loaders.cached.Loader", default_loaders)] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': default_loaders if DEBUG else cached_loaders, }, }, ] Which worked perfectly, however still, changes to my static files are not being served. I have tried disabling my browser cache with no luck. I am using Docker to run the dev environment with Docker Compose. Let me know if you need any other information, wasn't 100% sure what to provide as I have no idea what may be causing it. -
displaying image from sqlite in django
I have a model that has a field of Image profile_picture = models.ImageField(upload_to='clothes_images', null=True, blank=True). I have a function that returns the image URL def image_url(self): if self.profile_picture: return self.profile_picture.url return None but when I display in my template using this code <img src="{{cloth.image_url}}"> I get this error Not Found: /media/clothes_images/1_fSqDIIb.png my image name is 1.png but it changes when I store that and not find that. I want to display each image that stores in my local system. -
Django Schema Reverse Related Objects
I have the following two Django models: class Participant(models.Model): name = models.TextField() sport = models.TextField() bookmaker = models.ForeignKey(Bookmaker, on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ("name", "bookmaker", "sport") def __str__(self) -> str: return f"{self.name} ({self.sport}) | {self.bookmaker.name}" class BookmakerParticipant(models.Model): sharp_participant = models.OneToOneField( Participant, on_delete=models.CASCADE, primary_key=True, related_name="sharp_participant_match" ) soft_participants = models.ManyToManyField( Participant, related_name="soft_participant_matches" ) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) In my schema definition I'd like to access all the BookmakerParticipant objects where the Participant is in soft_participants from the Participants perspective. Thus, I created the following schema: class UnmatchedParticipantSchema(ModelSchema): bookmaker: BookmakerSchema soft_participant_matches: BookmakerParticipantSchema class Meta: model = Participant fields = [ "name", "sport", "bookmaker", "soft_participant_matches" ] However, this creates the following error in Django ninja.errors.ConfigError: DjangoField(s) {'soft_participant_matches'} are not in model <class 'core.models.Participant'>. How do I resolve this? -
Why i'm getting 403 error while creating a docker image?
Dockerfile: FROM python:3.19-alpine WORKDIR /app ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV PATH="/PY/BIN:$PATH" RUN pip install --upgrade pip COPY ./req.txt /app/req.txt COPY . /app RUN pip install -r req.txt docker-compose.yml: version: '3.8' services: django: container_name: django_celery_project build: context: ./ dockerfile: Dockerfile command: sh -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000" volumes: - .:/app ports: - "8000:8000" environment: - ALLOWED_HOSTS=localhost,127.0.0.1 - DEBUG=True - SECRET_KEY=*********** command : docker-compose up -d --build result : => [django internal] load .dockerignore 0.0s => => transferring context: 87B 0.0s => [django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 270B 0.0s => ERROR [django internal] load metadata for docker.io/library/python:3.19-alpine 10.7s => [django auth] library/python:pull token for registry-1.docker.io 0.0s error : failed to solve: python:3.19-alpine: failed to authorize: failed to fetch oauth token: unexpected status from POST request to https://auth.docker.io/token: 403 Forbidden My IP address without a VPN is: 93.115.225.147 My IP address with VPN is: 213.142.149.230 -
Serving static files with presigned URLs
I have a Django application hosted in AWS Lightstail and its static and media files hosted in a S3 bucket. The client is asking me to serve ALL the files (static and media) through AWS's presigned URLs. To my knowledge, presigned URLs are more suitable for media or single files rather than all the website's static files, since every time someone access the website, a new URL is generated for each static file, causing loading delays and misusage of the URLs' expiration time. I suggested to set up CloudFront instead. My question: Is the client's request reasonable? And if so, is there a way to serve these static files in a way that the presigned URLs are not created with every new access to the website? -
Display Image related to a Foreign Key
I have scoured the Internet, ChatGPT, StackOverflow, etc, and cannot find out how to make an image from my AWS S3 bucket (from a foreign key) appear in my template. The images work perfectly fine when they aren't connected via a foreign key and I am showing just students and their images. views.py #@login_required @user_passes_test(lambda u: u.groups.filter(name='teacher').exists()) def hallpasses(request): students = HallPass.objects.filter(dateissued__date = todaysdate2.date ) allstudents = Student.objects.all() context={'students':students, 'todaysdate2':todaysdate2, 'allstudents':allstudents, } return render(request, 'pass.html',context) models.py #HallPass model class HallPass(models.Model): DESTINATIONS=( ('Activities Office', 'Activities Office'), ('Alumni Office', 'Alumni Office'), ('Cafeteria', 'Cafeteria'), ('Chelsea Center', 'Chelsea Center'), ('Counseling Center', 'Counseling Center'), ('Cr. Counselor', 'Cr. Counselor'), ('Library', 'Library'), ('Nurse', 'Nurse'), ('Office 124', 'Office 124'), ('Office 157', 'Office 157'), ('Office 210', 'Office 210'), ('Office 308', 'Office 308'), ('Other', 'Other'), ('Locker', 'Locker'), ('Main Office', 'Main Office'), ('Teachers Room', 'Teachers Room'), ('Restroom', 'Restroom'), ('Water', 'Water'), ('WGHS Academy', 'WGHS Academy'), ('Art Department','Art Department'), ('Business Department','Business Department'), ('English Department','English Department'), ('FACS Department','FACS Department'), ('Industrial Tech Department','Industrial Tech Department'), ('Math Department','Math Department'), ('Music Department','Music Department'), ('Makerspace','Makerspace'), ('PE Department','PE Department'), ('Science Department','Science Department'), ('Social Studies Department','Social Studies Department'), ('SSD Department','SSD Department'), ('Theater Arts Department','Theater Arts Department'), ('World Languages','World Languages'), ) student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name="images") dateissued = models.DateTimeField(null=False,blank=False) teacherissuing = … -
How to fix importerror or Pythonanywhere deployment with Python upgrade?
I am using Python 3.8 on my mac and developing an app for more then two years. I am hosting this app on PythonAnywhere because I'm using Sqlite3. Now PA sent me an email that I need to upgrade the system image from Python 3.8 to 3.10. I never done this before so I'm registered a free account and deployed the exactly same app to test the process. I made a new project, virtualenv and installed Python 3.10 and Django 5.0 (tried 3.1 too - this is the version on my Mac). I did all the setting ans setted the wsgi too like many times before in other projects. When I installed all the apps and try to run the site I get this very long error traceback: 2023-12-20 18:37:37,746: Error running WSGI application 2023-12-20 18:37:38,100: ImportError: cannot import name 'SuccessURLAllowedHostsMixin' from 'django.contrib.auth.views' (/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/contrib/auth/views.py) 2023-12-20 18:37:38,100: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/wsgi.py", line 124, in __call__ 2023-12-20 18:37:38,100: response = self.get_response(request) 2023-12-20 18:37:38,101: 2023-12-20 18:37:38,101: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/base.py", line 140, in get_response 2023-12-20 18:37:38,101: response = self._middleware_chain(request) 2023-12-20 18:37:38,101: 2023-12-20 18:37:38,101: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 57, in inner 2023-12-20 18:37:38,102: response = response_for_exception(request, exc) 2023-12-20 18:37:38,102: 2023-12-20 18:37:38,102: File "/home/ruszakmikloseu/.virtualenvs/mpa-virtualenv/lib/python3.10/site-packages/django/core/handlers/exception.py", line 140, in response_for_exception 2023-12-20 18:37:38,102: … -
React Django app not updating component after change
I was working on a react js app with django backend. I made some changes to my search page component but my browser is still rendering the old search page. Here is the code for my search page import React, { useState, useEffect } from "react"; import TextField from "@material-ui/core/TextField"; import Button from "@material-ui/core/Button"; import axios from 'axios'; const SearchPage = () => { const [searchTerm, setSearchTerm] = useState(''); const [searchResults, setSearchResults] = useState(null); const [recentSearches, setRecentSearches] = useState([]); useEffect(() => { const storedSearches = localStorage.getItem('recentSearches'); if (storedSearches) { const parsedSearches = JSON.parse(storedSearches); console.log("Loaded searches:", parsedSearches); setRecentSearches(parsedSearches); } else { console.log("No recent searches found in localStorage"); } }, []); const handleSearch = async () => { try { const response = await axios.get('/backend/search', { headers: { 'Cache-Control': 'no-cache', }, params: { searchTerm: searchTerm, start: 0, }, }); setSearchResults(response.data); if (searchTerm.trim() !== '') { const updatedSearches = [searchTerm, ...recentSearches.filter(search => search !== searchTerm).slice(0, 4)]; setRecentSearches(updatedSearches); localStorage.setItem('recentSearches', JSON.stringify(updatedSearches)); } } catch (error) { console.error('Error fetching data: ', error); } }; return ( <div> <div style={{ margin: "20px" }}> <TextField label="Enter search term" variant="standard" fullWidth onChange={(e) => setSearchTerm(e.target.value)} /> </div> <div style={{ margin: "20px" }}> <h3>Recent Searches:</h3> <ul> {recentSearches.map((search, index) => ( <li … -
I'm unable to create superuser in Django
I'm unable to create a user profile in terminal after I have created Django environment by typing py manage.py createsuperuser it's unfortunately showing *** exe: can't open file 'C:\User\USER\manage.py'[Errno 2] No such file or directly *** I don't know what to do, I'm just keep trying and trying if it would work, I'm just keeping rolling a dice with no face that why I'm here, I'm expecting a best solution that will relieve the tie that tight my neck -
On media screen, swiping over the home-slider doesn't move
While checking mobile screen, found out that I have to swipe on top of the navbar to swipe through the homepage from top to bottom. If I swipe over the home-slider, it doesn't do anything since on media screen the home-slider is in full height and I am using a pre made template for python django project <section class="home-slider js-fullheight owl-carousel bg-white"> <div class="slider-item js-fullheight"> <div class="overlay"></div> <div class="container"> <div class="row d-md-flex no-gutters slider-text js-fullheight align-items-center justify-content-end" data-scrollax-parent="true"> <div class="one-third order-md-last"> <img class="js-fullheight" src="/static/images/coverpic1.jpeg" alt="background"> <h3 class="vr">Builders & Developers</h3> </div> <div class="one-forth d-flex js-fullheight align-items-center ftco-animate" data-scrollax=" properties: { translateY: '70%' }"> <div class="text"> <h1 class="mb-4" style="font-family: 'Lobster Two', sans-serif;">We don't just build,<br> we build legacies</h1> <p style="width: 50%; text-align: justify; font-family: 'Afacad', sans-serif;">At Maskn, we transcend construction, building legacies that stand as timeless testaments to our commitment to excellence.</p> <p><a href="/project" class="btn btn-primary px-4 py-3 mt-3">View our works</a></p> </div> </div> </div> </div> </div> This is my code for the home slider I tried to reduce the height of the slider, but it reduces the aesthetic of the page. -
Django & DRF: trying to find a way to reuse code for user registration for web and REST api
I have a working Django based web experience that has a CustomUser (AbstractUser) model to remove username and require email as default. I implemented a "register" function within views.py that set is_email_verified to FALSE (which is only set to TRUE by the email verification component). Now, I am creating REST services that could be used by a mobile app. I find the logic for the register function within api/views.py to be very similar to the register function within the views.py supporting the web experience. While I can extract the common code into a common function (and call it from both web and api register functions), is it a bad practice to instead update the web register function as follows (and call it from the POST function within the api/views): web views.py: @api_view(['POST']) @permission_classes([AllowAny]) @csrf_exempt def register(request): if request.method == 'POST': if request.content_type == 'application/json': # registration via API call data = json.loads(request.body) user_form = UserRegistrationForm(data) else: # registration via web user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.is_email_verified = False new_user.save() Profile.objects.create(user=new_user) send_email_verification_email(request, new_user) if request.content_type == 'application/json': # API response with token token, created = Token.objects.get_or_create(user=new_user) if created: return Response({'message': _('User registered successfully'), \ 'token': token.key, 'created': … -
django_filters and drf_yasg is not compatible
I am developing a project where I am using django_filters and there are some views where I have filters and apparently I have problems because of that. This is the message "UserWarning: <class 'apps.tenant_apps.orders.api.views.TotalProductsByOrderStateAPIView'> is not compatible with schema generation" and comes from django filters. I am following the documentation to the letter but I see no support for this warning. What should I do? django_filters docs: https://django-filter.readthedocs.io/en/stable/index.html drf_yasg docs: https://drf-yasg.readthedocs.io/en/stable/ class ProductByCategoriesListView(TenantListApiViewMixin): # 2. Listar productos por categoría o categorías # http://example.localhost:8000/api/products/list/category/?categories=Electr%C3%B3nica,Ropa%20y%20Accesorios,Ropa,Calzado,Muebles%20y%20Decoraci%C3%B3n serializer_class = ProductByCategorySerializer def get_queryset(self): categories = self.request.query_params.get('categories', '').split(',') queryset = [] for category in categories: # Utiliza Q objects para construir las condiciones OR q_objects = Q() q_objects |= Q( channelproduct_product__productcategory_channelproduct__channel_category__category__icontains=category) q_objects |= Q( channelproduct_product__productcategory_channelproduct__integration_category__category__icontains=category) # Filtra ProductModel con las condiciones OR products = ProductModel.objects.filter( q_objects).distinct().values_list('name', flat=True) if products: queryset.append({ 'category': category, 'products': list(products) }) return queryset @swagger_auto_schema(tags=['Product']) def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I expected this view to be placed in the Products tag but it sent me a warning. enter image description here