Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Error In Swagger(drf_yasg library) For Nested Serializers in Django
I'm using drf_yasg library in django. Normally everything was working correctly. When I use the nested serializer, I get the following error in the swagger interface. **Error: ** Internal Server Error: /swagger/ Traceback (most recent call last): File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\views.py", line 94, in get schema = generator.get_schema(request, self.public) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 246, in get_schema paths, prefix = self.get_paths(endpoints, components, request, public) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 404, in get_paths operation = self.get_operation(view, path, prefix, method, components, request) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\generators.py", line 446, in get_operation operation = view_inspector.get_operation(operation_keys) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 32, in get_operation body = self.get_request_body_parameters(consumes) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 82, in get_request_body_parameters return self.get_request_form_parameters(serializer) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\view.py", line 134, in get_request_form_parameters return self.serializer_to_parameters(serializer, in_=openapi.IN_FORM) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\userx1\OneDrive\Desktop\projectx_backend\venv\Lib\site-packages\drf_yasg\inspectors\base.py", line 448, … -
Is Django Template legacy?
Django, as a backend framework, has the main purpose of returning JSON-format data to the frontend developer. So why do we need templates to render HTML with Django? We can use React for the frontend and Django for the backend to provide data via API. The problem is: is this technology a legacy? Does anyone or the company use templates to render the frontend using Django for now in a real project? Also, I am a noob in backend development, so can anybody tell me what backend developers work on exactly except create APIs and make databases? -
Django: cant relate my comment to a specific product
I dont know how to link comments to specific product(object). Maybe there is something to do with slugs. P.S. All the comments can be successfully uploaded to the database, but the problem is only with linking them with one product views.py class ProductDetail(DetailView): model = Product template_name = 'store/product-single.html' context_object_name = 'product' def get_context_data(self, **kwargs): context = super().get_context_data() products = Product.objects.all()[:4] context['products'] = products product = Product.objects.get(slug=self.kwargs['slug']) context['title'] = product.title context['comment_form'] = CommentForm() context['comments'] = Comment.objects.all() return context def save_comment(request): form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) # comment.product = Product.objects.filter() comment.save() return redirect('index') urls.py path('save_comment/', save_comment, name='save_comment') product-single.html <div class="container"> <form action="{% url 'save_comment' %}" method="POST"> {% csrf_token %} {{ comment_form.as_p }} <button type="submit" class="btn btn-primary btn-lg">Submit</button> </form> </div> models.py class Comment(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) user = models.CharField(default='', max_length=255) text = models.TextField(default='') forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['user', 'text'] widgets = { 'user': forms.TextInput(), 'text': forms.Textarea() } -
Django Websocket giving error when connecting in video call app
I am using Django websocket for making a real video chat app and I am beginner in Websocket. I/m trying that user first give the room name and then the username and then it will be connected to the meeting room. I've written it like below For Routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/(?P<room_name>\w+)/(?P<name>\w+)/$', consumers.ChatVideoConsumer.as_asgi()) ] For urls.py from django.urls import path from . import views urlpatterns = [ path('<str:room_name>/<str:name>/', views.index, name='index'), ] For Views.py from django.shortcuts import render # Create your views here. def index(request, *args, **kwargs): return render(request, "chat/room.html") For Room.js console.log("Hello World from room.js"); console.log(window.location.pathname); let wsStart = "ws://"; const loc = window.location; if(loc.protocol === "https:") { wsStart = "wss://"; } const endpoint = wsStart + loc.host + loc.pathname; console.log("Endpoint", endpoint); const websocket = new WebSocket(endpoint); websocket.onopen = (e) => { console.log("Open", e); }; // websocket.onmessage = (e) => { // console.log("Message", e); // }; websocket.onclose = (e) => { console.log("Close", e); }; For Consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatVideoConsumer(AsyncWebsocketConsumer): async def connect(self): print("connect") await self.accept() self.send(text_data=json.dumps({ "type" : "Message.Accept", "message" : "Hello Connect Established" })) async def disconnect(self, close_code): pass asgi.py import os from channels.routing import ProtocolTypeRouter, … -
How to Mock test for sending email post signup using celery in DRF
Post signup of an user in RegisterUserAPIView, i'm using a celery task to send email for verification. views.py class RegisterUserAPIView(generics.GenericAPIView): serializer_class = RegisterUserSerializer def post(self, request): serializer = self.serializer_class(data = request.data) if serializer.is_valid(): serializer.save() # Get the email from serializer and use it to send email for email verification. user_email = serializer.validated_data['email'] send_verification_email_task.delay(user_email = user_email) return Response(serializer.data, status = status.HTTP_201_CREATED) return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST) task.py def send_verification_email_task(user_email): ... response = send_verification_email(user_email=user_email) ... return "Successfully sent verification email to %s" % user_email email.py def send_verification_email(user_email): ... try: email_message = EmailMultiAlternatives( subject = email_subject, body = text_content, from_email = email_from, to = [email_to] ) email_message.attach_alternative(html_content, "text/html") email_message.send() response = { "status" : 200 } except Exception: response = { "status" : 400 } return response I tried the following test scenarios I called post request using the client api but that sends an email each time test cases are run. I tried the following mock test scenario but that still shows that my code lines are not covered. This is the test case i tried here. class EmailTestCase(TestCase): def test_send_verification_email_task_success(self): with patch('auth_service.views.send_verification_email_task.delay') as mock_task: user_email = 'testuser@example.com' # Mock the send method of the send_verification_email_task mock_task.return_value = 'Successfully sent verification email … -
Django QuerySet union() is not giving the desired output
I have written the following code views.py room_list = Room.objects.all() time_slot_list = TimeSlot.objects.none() for room in room_list: time_slots = TimeSlot.objects.filter(room=room) for time_slot in time_slots: time_slot_list.union(time_slot_list, time_slot) print(time_slot_list) models.py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(550), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class TimeSlot(models.Model): class Meta: ordering = ['available_from'] room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() When I am printing time_slot_list, I am getting empty QuerySet but I want it to contain the list of timeslots. Can someone please tell me what I am doing wrong? -
django login url with param
a third party authentication requires api must be called in the index view, for example my domain is zzd.com, then they only provide api to zzd.com, which means we cannot have route specified for a signin view, which unable to put all login stuff into zzd.com/login/ however, index view is designed to shows some other important info primarily rather than login QR, which only contains a login button, to use js to display the QR when click. here's the issue, I have followed declared in settings.py: my index view serves all stuff in one template, including trending info, and login qr code if user is not auth-ed. javascript looks like this: const url = new window.URL(window.location.href); let mode = url.searchParams.get('mode'); if(mode === 'login'){ showLoginQrCodeScanner(); } which login qr img would only show if index/?mode=login specified, otherwise would display trending info instead. and my settings.py: LOGIN_REDIRECT_URL = 'index' LOGIN_URL = 'index' the issue is that, I have some of my views @login_required, but, an anonymous user, would get redirected to the index/?next=particular/url, without the mode=login part, which does not show the qr primarily. is there a way to declare login url with the param, for a much better user experience? -
How to associate a django url with a bootstrap modal popup
I have a django view which create an form within a modal popup. When clicking to lithat triger the modal, nothing happen. I seems it is because I am not in the page. Because when I was in another page, I see the popup firing. Is it possible to add url cooresponding to the view in the modal button here is my navbar.html <div> <ul> <li> <a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#formModal" href="{% url 'create_campaign_naming_tool' %}">Modal</a> </li> </ul> </div> My form template: {% extends 'navbar.html' %} {% block content %} <div class="modal fade" id="formModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> </div> <div class="modal-body"> <form class="" action="#" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form}} <!-- Modal footer --> <div class="modal-footer"> <button type="submit" class="btn btn-success" name="button">Create</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </div> {% endblock %} -
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 …