Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Integrating tailwindcss with django
am trying to integrate tailwindcss with django. django seems to have located my tailwindcss and even the default font for tailwindcss is implemented, but none of the tailwind classes seems to work in my project. What could be the reason why? I tried passing classes mx-auto, font-semibold into my div as seen in this image but both the classes failed to respond as seen in this image. And when i tried to add another css property (background-color:blue) in the tailwind output file, that property works. So the question is, how comes other css properties work but tailwind classes won work for me? -
ValueError: The given username must be set (Django)
I am Trying to Implement a User Authentication in Django, But i everytime i try to run the server i am getting this error "ValueError: The given username must be set " The error message highlights the necessity of setting a specific username. Despite dedicated attempts, a satisfactory resolution to this predicament remains elusive. Regrettably, exhaustive troubleshooting and investigation have yet to yield a viable solution. Here is Code: Signup.html <html> <head> <title>Signup</title> <style> body { background-color: #222; color: #fff; font-family: Arial, sans-serif; } .container { max-width: 400px; margin: 0 auto; padding: 20px; box-sizing: border-box; background-color: #333; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); } h1 { text-align: center; margin-bottom: 30px; } input[type="text"], input[type="email"], input[type="password"] { width: 100%; padding: 10px; margin-bottom: 20px; background-color: #444; border: none; border-radius: 4px; color: #fff; } input[type="submit"] { width: 100%; padding: 10px; background-color: #f44336; border: none; border-radius: 4px; color: #fff; cursor: pointer; } input[type="submit"]:hover { background-color: #e53935; } ::placeholder { color: #888; } </style> </head> <body> <form method="post" action="home/"> {% csrf_token %} <input type="text" name="username" placeholder="Username" required/> <input type="email" name="email" placeholder="Email" required/> <input type="password" name="password" placeholder="Password" required/> <input type="password" name="confirm_password" placeholder="Confirm Password" required/> <input type="submit" name="submit" value="Sign Up"/> </form> </body> </html> views.py … -
drf custom authentication backend gets executed on the path that doesn't need authentication
I am new to django and I am trying to add permissions from DRF to my project. Ever since I have set DEFAULT_AUTHENTICATION_CLASSES for REST_FRAMEWORK in django settings.py, all the requests are going to the authenticate method of my DEFAULT_AUTHENTICATION_CLASSES irrespective of what permission I set to my view. Later it is coming to my view. So here is the settings I have added: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'authentication.customauth.CustomAuthBackend', ] } And here is my authentication.customauth.CustomAuthBackend: class CustomAuthBackend(BaseAuthentication): def authenticate(self, request): user = AuthUtils.get_user_from_token(request) if user is None: raise AuthenticationFailed('User not found') request.user = user return user, None @staticmethod def authenticate_with_password(request): email = request.data.get('email') role = "CONSUMER" if request.data.get('role') is None else request.data.get('role') password = request.data.get('password') user = User.objects.filter(email=email, role=role).first() if password is not None and user is not None and user.check_password(password): return user The views that actually should be called without authentication have @permission_classes([AllowAny]) permission. Say this login view: @api_view(['POST']) @permission_classes([AllowAny]) def login(request): user = request.user if user and user.is_active: serializer = UserSerializer(user) tokens_map = AuthUtils.generate_token(request=request, user=user) return Response({'success': True, 'user': serializer.data, 'tokens': tokens_map}) return Response(data={'success': False, 'message': 'User not found'}, status=status.HTTP_404_NOT_FOUND) With my understanding I think if permission class is rest_framework.permissions.AllowAny no authenticate method should not be … -
automatic calculated integer fields in django models
I have model like this class Product(models.Model): name = models.CharField(max_length=150) stock = models.IntegerField() cogs = models.IntegerField() def __str__(self): return f"{self.name}" class Transaction(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE) product = models.ManyToManyField(Product) purchase_date = models.DateField(auto_now_add=True) quantity = models.IntegerField() total = models.IntegerField(blank=True) def save(self, *args, **kwargs): self.total = self.quantity * self.product.cogs super().save(self, *args, **kwargs) def __str__(self): return f"{self.customer}" my question is How to make Product attribute in this case stock will be dynamically calculated when there is transaction input. Every input in transaction will deduct product.stock which is product.stock - transaction.quantity I try to automatically calculate product.stock when there is input in transaction -
Should I make redirect-urls creating API service with Django Rest Framework?
I am new to web-development and creating APIs, so I have some misunderstandings. I am creating online-shop API, and already have registration system with email confirmation. So the logic is: When user sends post request to registration endpoint he recieves an url that consists of token and his ID, at the same time his account is created, but is_active status equals False. When he requests the page with the url, his is_active=True. So, according to business-logic of my web-app, when user requests the page with the given url to confirm email, he is supposed to automatically login and be redirected to his personal profile endpoint. My question is: should I make redirections in DRF using redirect and reverse functions, or it is a task for fronted developers? Sorry if question seems to be silly, I am just learning. Thanks in advance Just want to clarify my mind, if it is ok to make redirects in backend development, or it is supposed to be done by frontend developers. -
ModuleNotFoundError: No module named 'django_keycloak.decorators'
I am trying to integrate Keycloak with django, therefore, I am using django_keycloak to work it out. However, when I run the migration the following exception is being thrown: ModuleNotFoundError: No module named 'django_keycloak.decorators' -
Dynamic qrcode just like whatsapp web qrcode
How can I generate a QR code that updates periodically (every 10 seconds) in a Django web app, similar to how it is done in WhatsApp Web? Are there any packages or code snippets available for this purpose? -
Filtering With DRF
I'm currently trying to add filter to a menu API but it doesn't seem to work This is what I tried in my views.py: @api_view() def menu_items(request): if request.method == "GET": items = MenuItem.objects.select_related('category').all() category_name = request.query_params.get('category') to_price = request.query_params.get('to_price') search = request.query_params.get('search') if category_name: items = items.filter(category__title=category_name) if to_price is not None: items = items.filter(price__lte=to_price) # lte means price is less then or equal to the value to_price if search:. items = items.filter(title__icontains=search) # If the characters are present anywhere in the title. This is case insensitive. serialized_item = MenuItemSerializer(items, many=True) return Response(serialized_item.data) if request.method == 'POST': serialized_item = MenuItemSerializer(data=request.data) serialized_item.is_valid(raise_exception=True) serialized_item.save() # Saves the validated data to the database return Response(serialized_item.data, status.HTTP_201_CREATED) Whenever I go to the endpoint with the filter value set up, I get an empty list instead of a list of filtered menu items: empty list when filtered This is what it looks like without filtering: menu items list unfiltered Am I doing something wrong? I am following a tutorial and it works on the tutorial but not on mine. -
Django API: Error - Failed to load resource: the server responded with a status of 401 (Unauthorized) and HTTP 405 Method Not Allowed
I'm currently working on a Django project and encountered some issues with the login functionality. I have a React component called LoginPage.js which sends a POST request to the Django API for the farmer and customer login. However, I'm receiving the following errors: In the browser console, I see the error message "Failed to load resource: the server responded with a status of 401 (Unauthorized)". When I try to access the URL GET /api/farmer/login/, I receive the error "HTTP 405 Method Not Allowed". API endpoint view shows error: HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } React browser console error: "POST http://127.0.0.1:8000/api/farmer/login/ 401 (Unauthorized)" I have provided the relevant code snippets below for reference: LoginPage.js: import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import axios from 'axios'; import './css/LoginPage.css'; const LoginPage = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [errors, setErrors] = useState([]); const handleRedirect = (userType) => { if (userType === 'farmer') { window.location.href = 'http://127.0.0.1:8000/api/product/create/'; } else if (userType === 'customer') { window.location.href = 'http://127.0.0.1:8000/api/product/list/'; } }; const handleSubmit = (event, userType) => { event.preventDefault(); … -
Improve Django filter preformance for all fields searching special ManyToMany
I am trying to use django-filter to create a search for all fields. Here is my code: from django.db.models import Q, CharField, TextField, ForeignKey, IntegerField, Func, Value def get_all_fields_q_object(model, search_value, exclude_fields=None, prefix=None): q_object = Q() exclude_fields = exclude_fields or [] for field in model._meta.get_fields(): if field.name in exclude_fields: continue lookup_field_name = f"{prefix}__{field.name}" if prefix else field.name if isinstance(field, (CharField, TextField)): q_object |= Q(**{f"{lookup_field_name}__icontains": search_value}) elif isinstance(field, ForeignKey): related_model = field.related_model related_q_object = get_all_fields_q_object(related_model, search_value, exclude_fields=exclude_fields, prefix=lookup_field_name) q_object |= related_q_object elif isinstance(field, IntegerField): try: int_value = int(search_value) q_object |= Q(**{lookup_field_name: int_value}) except ValueError: pass elif isinstance(field, ArrayField): q_object |= Q(**{f'{lookup_field_name}__icontains': search_value}) # # Add more field types as needed... return q_object It works for integer, char, foreignkey and array at this moment. But now the model also added ManytoMany fields. I would like to show result based on string icontains. So I handled them like foreignkeyfields: ... elif isinstance(field, ManyToManyField): related_model = field.related_model related_q_object = get_all_fields_q_object(related_model, search_value, exclude_fields=exclude_fields, prefix=lookup_field_name) q_object |= related_q_object Although it works, but the result returns way too slow. Things are: I assume manytomany fields take time to loop the search I think about two ways : 1. convert manytomany fields object to a string only use PKname … -
Django REST PATCH request field is required problem
I have a Student model. And I want to update some specific fields. But when I go to update one or two fields but the other field value is as it is then which fields are not changing those fields show this error** "This field is required.". ** Here is my model. class Student(models.Model): teacher=models.ForeignKey(Teacher, on_delete=models.CASCADE) name=models.CharField(max_length=20) level=models.CharField(max_length=20) And here are my views class StudentUpdateDelete(APIView): def patch(self, request, id): student=Student.objects.filter(pk=id).first() serializer=StudentSerializer(student, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Avobe model has 3 fields but I want to change only the name field using patch methods. here is postman request image -
Task schedule using Django and Celery that fetches data from legacy database i.e. Oracle and dump to another database i.e. SQLite
Suppose I have a model in Django that represents a database table named UnfilledReturn with the following columns; category_id and form_code configured in the SQLite in Django app. All these columns are fetched from other table in legacy database which is in Oracle(the connection is through VPN) named TRetCategory. I create a task that is capable of fetching data from TRetCategory and then dump it to the UnfilledReturn in Django using redis, and celery. The following are codes in the Django project:- #settings.py 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'oracle': { 'ENGINE': 'django.db.backends.oracle', 'NAME': config('DB_NAME'), 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), } } # Celery beat configurations CELERY_BROKER_URL = "redis://127.0.0.1:6379/0" CELERY_RESULT_BACKEND = "redis://127.0.0.1:6379/0" CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' from datetime import timedelta CELERY_BEAT_SCHEDULE = { 'load_task': { 'task': 'main.tasks.load_unfilled_returns', 'schedule': timedelta(minutes=2), }, } #models.py class UnfilledReturn(models.Model): CATEGORY_ID = models.IntegerField() FORM_CODE = models.CharField(max_length=50) #celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') app = Celery('core') app.config_from_object('django.conf:settings',namespace='CELERY') app.autodiscover_tasks() #tasks.py @shared_task def load_unfilled_returns(): oracle_conn = connections['oracle'] with oracle_conn.cursor() as cursor: cursor.execute("SELECT CATEGORY_ID,FORM_CODE FROM ITAX.T_RET_CATEGORY") rows = cursor.fetchall() sqlite_conn = connections['default'] with sqlite_conn.cursor() as cursor: for row in rows: CATEGORY_ID, FORM_CODE … -
I have installed and configured django-allauth-2fa. How to create a button for user to apply 2fa?
all. I have installed and configured django-allauth-2fa following this documentation: https://django-allauth-2fa.readthedocs.io/en/latest/installation/. Can anyone tell me what to do next to apply to 2fa to the users? Thank you very much in advance. Alex I have installed and configured django-allauth-2fa following this documentation: https://django-allauth-2fa.readthedocs.io/en/latest/installation/. How to create a button for user to apply 2fa? -
Integration Testing In Django Involving Reverse Lambda Call
I need to test a django application which involves AWS lambda talking back to the django server. Mock testing does not help catching the bug, so I need the original lambda function to be part of the test. The Django TestCase creates a temporary database for testing apart from the production database, which is good. However, when lambda function calls back to the server, it is outside of the context of the TestCase and therefore it refers to the production database instead of the test database and the test fails to complete. Is there any way to override the django settings globally to use the test database during the integration test? I tried to override the settings of the TestCase, but it does not apply globally, rather it is just for the TestCase. -
How to override a class in django.contrib.admin?
I don't want to modify the source code of Django directly, since any updates will remove my modifications. So, how to override the ChangeList class in django.contrib.admin.views.main, and tell django to use it instead of the original one? Thanks -
Sum of values in Django views
I intend to make a query to get a value and then add that value to 1 in the django views, but when I try to do that, I always get an error def atualizar(request, contador): lista = factura.objects.filter(contador__contador=contador) conta1 = factura.objects.filter(contador__contador=contador).order_by('-contar')[:1] conta=conta1.values('contar') # this is value cont=cliente.objects.filter(contador=contador).first() if request.POST: data1=request.POST['data1'] factura_nr=request.POST['factura_nr'] data2=request.POST['data2'] consumo=request.POST['consumo'] dados = factura( contador=cont, contar= conta +1, # to incremet here consumo=consumo, data1=data1, data2=data2, factura_nr=factura_nr ) dados.save() return render(request, 'tabela.html', {'lista': lista,'cont':cont ,'conta':conta})[enter image description here](https://i.stack.imgur.com/BdaMk.png) -
Add multiple routers with different router class to the same endpoints in FastAPI
I have a /users route in my app which is initialized with a default router like this : (Note that responses and dependencies have been removed from the snippet to protect proprietary code) api_router = APIRouter( responses={}, route_class=LocalizationRoute, dependencies=[], ) Localization Route is being used directly from fastapi-localizationpackage for translation purpose. Now I want to add another router to the same route for the purpose of logging . This router is based on the following router class def log_info(req_body, res_body): print(req_body) print(res_body) class LoggingRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_route_handler() async def custom_route_handler(request: Request) -> Response: req_body = await request.body() response = await original_route_handler(request) if isinstance(response, StreamingResponse): res_body = b'' async for item in response.body_iterator: res_body += item task = BackgroundTask(log_info, req_body, res_body) return Response(content=res_body, status_code=response.status_code, headers=dict(response.headers), media_type=response.media_type, background=task) else: res_body = response.body response.background = BackgroundTask(log_info, req_body, res_body) return response return custom_route_handler I tried doing this by using includerouter clause like this : api_router.include_router(APIRouter(router_class= LoggingRoute)) But this is not working. I can see the router class is still set to Localization Route and the routerclass argument in include_router statement is ignored. So I was wondering do fast api not support adding multiple routers with different router class to the … -
mysql : The term 'mysql' is not recognized as the name of a cmdlet Of Code with Mosh's Ultimate Django Series
If you had been following The Ultimate Django Series by code with mosh and you got to the video : 4.Setting Up the Database -> 9- Using MySQL in Django and you get the following error in the console on windows : mysql : The term 'mysql' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. -
can't access certain file types in media file in django local server
when i try to acess a file with pdf or mp4 that exsit in the media folder using dirict link to the file `http://127.0.0.1:7500/media/1.pdf` the broswer just load forever with no errors but if i try to acess a jpg file in the same folder it works fine http://127.0.0.1:7500/media/1.jpg this will work and show the image i trid some sloutions like add this to the settings but same problem ALLOWED_FILE_TYPES = ['*'] . this is my confgration of the media folder in the settings MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIAFILES_DIRS = [os.path.join(BASE_DIR, 'mediafiles')] and i this is from the urls if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) i also trid several browsers all gave me the same problem. i tried to run it on another pc that is using linux it works fine on the other pc but not on mine i'm using Windows DJANGO VERSION 4.2.2 -
Tailwind CSS classes not rendering on Nginx server but working on Gunicorn
I am facing an issue with my Django web application where the Tailwind CSS classes are not rendering when accessing the site through the Nginx server. Strangely, the Tailwind CSS classes are applied correctly when running the application using Gunicorn. I have carefully checked my static file configuration and confirmed that Nginx is properly serving other static files, such as images and JavaScript files. However, the Tailwind CSS classes seem to be the only ones not functioning as expected. Here is my current Nginx server block configuration: server { listen 80; server_name localhost; access_log /Users/curtwheeler/Documents/Django/Business/cookiecutters/base/base/var/log/nginx/access.log; error_log /Users/curtwheeler/Documents/Django/Business/cookiecutters/base/base/var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /static { root /Users/curtrosenblad/Documents/Django/Business/cookiecutters/base/base/base; } location /media { root /Users/curtrosenblad/Documents/Django/Business/cookiecutters/base/base/base; } } I have already checked the file permissions and ownership of the static files, and they appear to be set correctly. Additionally, during the collectstatic process, the Tailwind CSS files are being correctly copied to the static files directory. I suspect that there might be a misconfiguration or missing directive in my Nginx server block that is causing the issue. I would appreciate any guidance or suggestions on how to properly configure Nginx … -
'cross-env' is not recognized as an internal or external command, operable program or batch file
I'm working on a team in a django project with tailwind following by this set up tutorial https://django-tailwind.readthedocs.io/en/latest/installation.html. everything works find but when i'm starting tailwind py manage.py tailwind start. theme@3.5.0 start npm run dev theme@3.5.0 dev cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w 'cross-env' is not recognized as an internal or external command, operable program or batch file. here is package.json { "name": "theme", "version": "3.5.0", "description": "", "scripts": { "start": "npm run dev", "build": "npm run build:clean && npm run build:tailwind", "build:clean": "rimraf ../static/css/dist", "build:tailwind": "cross-env NODE_ENV=production tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css --minify", "dev": "cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w", "tailwindcss": "node ./node_modules/tailwindcss/lib/cli.js" }, "keywords": [], "author": "", "license": "MIT", "devDependencies": { "@tailwindcss/aspect-ratio": "^0.4.2", "@tailwindcss/forms": "^0.5.3", "@tailwindcss/line-clamp": "^0.4.2", "@tailwindcss/typography": "^0.5.2", "cross-env": "^7.0.3", "postcss": "^8.4.14", "postcss-import": "^15.1.0", "postcss-nested": "^6.0.0", "postcss-simple-vars": "^7.0.1", "rimraf": "^4.1.2", "tailwindcss": "^3.2.7" } } do i need to install cross-env? should i install it using npm or pip? in my venv or locally? -
Can you deploy sqlite db to pythonanywhere? if so how do you configure it for deployment?
Deploying sqlite database to python anywhere -
Why is my attempt to clone this django repository failing?
I am trying to clone a django repository, but I keep running into problems. I am trying to do this through a virtualenv. When I run python3 manage.py runserver I am met with the following error: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\mukes\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\django\urls\resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", … -
Securing Endpoint in Django including Generic Relationship
In a simplified version i have 3 classes in the first app (named: appBasic): class ClassA(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) class ClassB(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() specific_B = GenericForeignKey('content_type', 'object_id') in another app (appSpec) class ClassBSpec(models.Model): class_b = GenericRelation(ClassB, related_name='class_b') class_a = ForeignKey(ClassA, on_delete=models.CASCADE) using these classes i build the endpoints using NestedRouters form the rest_framework_nested to get to: /appSpec/class_b_spec/ /appSpec/class_b_spec/<pk>/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/ /appSpec/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ my goal is to protect these endpoints and allow post,get,put,patch request only for instances, which belong (via class_a) to the current user. To secure the first two endpoints i add the following method in the ClassBSpecSerializer: def validate_class_a(self, class_a): user_id = self.context['user_id'] if classs_a.user.id != user_id: raise serializers.ValidationError('No class_a with given ID found for this user') return class_a However, i cannot do the same for the other two endpoints, /appB/class_b_spec/<class_b_spec_pk>/class_b/ /appB/class_b_spec/<class_b_spec_pk>/class_b/<pk>/ because here i am dealing with a generic relation-ship What i have implemented for now is to override the ViewSet for ClassB in the second app (appSpec) such as: from appBasic.views import classBViewSet as BasicClassBViewSet class ClassBViewSet(BasicClassBViewSet): class_b_spec_queryset = ClassBSpec.objects.filter(classA__user_id=self.request.user.id) class_b_spec = get_object_or_404(class_b_spec_querset=self.kwargs['class_b_spec_pk'] return class_b_spec.class_b.all() like that i can ensure that i get a 404 error when i am at this endpoint: /appB/class_b_spec/<class_b_spec_pk>/class_b/ … -
Having a list of autocomplete options in Django form CharField
I have a Django form with two CharFields. I want users to be able to type but I want autocomplete suggestions based on the values in the database. Here is an example of what I want pulled from another website. This is what I am currently doing. albums = Album.objects.values_list('artist', flat=True).distinct() artists = Album.objects.values_list('name', flat=True).distinct() class MakeGuess(forms.Form): artist = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Artist'})) album = forms.CharField(max_length=100, label='', widget=forms.TextInput(attrs={'placeholder': 'Album'})) The goal is to have the autocomplete dropdown for the artist field be the artists list and same for the albums. I tried to use a forms.TypedChoice field with choices=artists but it did not do what I thought it would.