Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix the timezone in django while filtering datas from database
views.py: def index(request): if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date, '%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) global roles roles = Scrapper.objects.all() # for i in roles: # print(i.description) global find_description # find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) find_description = Scrapper.objects.all().filter(created_at=f_date,updated_at=t_date) print(find_description) models.py from django.db import models from django.db import connections from django.utils import timezone # Create your models here. class Scrapper(models.Model): id = models.IntegerField(primary_key=True) full_name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.TextField(max_length=100) created_at = models.DateTimeField(default=True) updated_at = models.DateTimeField(default=True) class Meta: db_table = "test_table_1" When I pass the data as filter to the database to get value there occurs error RuntimeWarning: DateTimeField Scrapper.created_at received a naive datetime (2022-11-09 00:00:00) while time zone support is active. My f_date= "2022-11-09 00:00:00" . Is there any solution for removing error -
Django celery results does not store task results
The problem speaks for itself - django-celery-results does not store any task results. I did everything as it was described in 'getting started' section in documentation, but still no results. I'm using django 4.1.2 and django-celery-results 2.4.0 Here is related variables from settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.redis.RedisCache', 'LOCATION': 'redis://redis:6379', } } CELERY_BROKER_URL = os.environ.get("CELERY_BROKER", "redis://redis:6379") CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND", "django-db") CELERY_CACHE_BACKEND = "django-cache" CELERY_RESULT_EXTENDED = True I also tried database cache - nothing changed. How can I get this to work? -
django - Createview add error message when none of checkboxes is checked
I'm struggling with adding error message when none of checkboxes is selected in my template. Now in my CreateView I've got following code to get value of checkboxes: def form_valid(self,form): box1=form.cleaned_data['box1'] box2=form.cleaned_data['box2'] How to produce an error when user doesn't click any of them? -
Cache form data against page refresh
I have certain forms in my Django project and I want to get a different data with a button on this form with a pop-up window and save it to the database. But here, how can I make the previously entered data come back when the page is reloaded so that my background data is not lost? Thanks in advance to everyone who helps. -
How to get the values from the table based on dates from datetime field django
views.py from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligo_app.models import Scrapper from django.utils import timezone import datetime import pytz find_description = "" def index(request): if request.method == "POST": from_date = request.POST.get("from_date") print(from_date) to_date = request.POST.get("to_date") print(to_date) roles = Scrapper.objects.all() # for i in roles: # print(i.description) global find_description find_description = Scrapper.objects.all().filter(created_at=from_date,updated_at=to_date) print(find_description) return render(request, "home.html", {"scrappers": find_description}) models.py from django.db import models from django.db import connections # Create your models here. class Scrapper(models.Model): id = models.IntegerField(primary_key=True) full_name = models.CharField(max_length=100) slug = models.CharField(max_length=100) description = models.TextField(max_length=100) created_at = models.DateTimeField(default=True) updated_at = models.DateTimeField(default=True) class Meta: db_table = "test_table_1" From my form I will post data where my from_date = "2022-11-09" and to_date = "2022-11-09". But my table column has time with date. Is there any solution to get the data based on only date I post. But my table should not make any alter. -
celery periodic task with view function
I have created periodic tasks to send mails only once as per the given time as below using post save signals class MailTask(models.Model): name = models.CharField(max_length=100, blank=True) subject = models.CharField(max_length=100) message = models.TextField() from_email = models.EmailField() recipient = models.EmailField() sent = models.BooleanField(default=False) time_to_send = models.DateTimeField() def create_periodic_task(sender, instance, created, **kwargs): if created: time_to_send = instance.time_to_send clocked_schedule, created = ClockedSchedule.objects.get_or_create( clocked_time=time_to_send ) periodic_task = PeriodicTask.objects.create( clocked=clocked_schedule, name=instance.name, task='core.tasks.send_mail_func', one_off=True, ) post_save.connect(create_periodic_task, sender=MailTask) the function to be called is as below @shared_task def send_mail_func(): mail_task = MailTask.objects.last() send_mail( mail_task.subject, mail_task.message, mail_task.from_email, [mail_task.recipient], fail_silently=False, ) This will run only the last instance of the email task, how I can loop through all the instance and send mail, or how I can connect the periodic task id the corresponding mail function -
PostgresSQL connection refused on docker container in same server
I have postgresSQL database running docker on server when i spin up another container for django app and trying to connect postgress getting connection error. any idea? django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 6545 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (::1), port 6545 failed: Cannot assign requested address Is the server running on that host and accepting TCP/IP connections? -
How to call AsyncWebsocketConsumer functions from different files in Django
this is consumers.py class ChatConsumer(AsyncWebsocketConsumer): async def receive(self, text_data): pass this is my view.py class CreateChatMessageView(APIView): ... message_obj = ChatMessage.objects.create(chat_room=chat_room_obj, sender_id=sender_id, receiver_id=receiver_id, message_text=message_text, message_attachment=message_attachment) # here I want to call the 'receive' function from 'ChatConsumer(AsyncWebsocketConsumer):' message_obj.save() ... I want to call the receive function from ChatConsumer(AsyncWebsocketConsumer):. How can I have done? -
FILTERING AN ARRAY IRREGARDLESS OF THE ARRANGEMNT (Python)
Am trying to save this data from a callback url but the arrangement keeps changing, how do I fetch the data without use of index {"Body":{ "stkCallback":{ "MerchantRequestID":"106225-49293961-1", "CheckoutRequestID":"ws_CO_041120220958559137xxxxx768", "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ {"Name":"Amount","Value":1.00}, {"Name":"MpesaReceiptNumber","Value":"QK438EQIOX"}, {"Name":"TransactionDate","Value":20221104095914}, {"Name":"PhoneNumber","Value":2547xxxxx178} ] } } } } This is what I have done merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"] print(merchant_requestID) checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"] print(checkout_requestID) result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"] print(result_code) result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"] print(result_desc) amount = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][0]["Value"] print(amount) mpesa_receipt_number = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][1]["Value"] print(mpesa_receipt_number) transaction_date = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][2]["Value"] print(transaction_date) phone_number = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"][3]["Value"] print(phone_number) balance = '' Some transaction will have balance other will not have and that is where the error comes in because of fetching the data using index. Advice on how to save the data, more so the Item list without use of index. -
Calculate %-deviation with values from a pandas Dataframe
I am fairly new to python and I have the following dataframe setting_id subject_id seconds result_id owner_id average duration_id 0 7 1 0 1680.5 2.0 24.000 1.0 1 7 1 3600 1690.5 2.0 46.000 2.0 2 7 1 10800 1700.5 2.0 101.000 4.0 3 7 2 0 1682.5 2.0 12.500 1.0 4 7 2 3600 1692.5 2.0 33.500 2.0 5 7 2 10800 1702.5 2.0 86.500 4.0 6 7 3 0 1684.5 2.0 8.500 1.0 7 7 3 3600 1694.5 2.0 15.000 2.0 8 7 3 10800 1704.5 2.0 34.000 4.0 What I need to do is Calculate the deviation (%) from averages with a "seconds"-value not equal to 0 from those averages with a seconds value of zero, where the subject_id and Setting_id are the same i.e. setting_id ==7 & subject_id ==1 would be: (result/baseline)*100 ------> for 3600 seconds: (46/24)*100 = +192% ------> for 10800 seconds: (101/24)*100 = +421% .... baseline = average-result with a seconds value of 0 .... result = average-result with a seconds value other than 0 The resulting df should look like this setting_id subject_id seconds owner_id average deviation duration_id 0 7 1 0 2 24 0 1 1 7 1 3600 2 46 192 … -
populating multiple forms at once in django
I want to populate 'n' forms with my data. Some data will be from database and some from session. 'with this i get the info from session and have it in my view. store/view.py class AddProductToCartView(View): def get(self, request, pk): cart = request.session.get("cart") if cart: for item in cart: if item["id"] == pk: item["quantity"] += 1 break else: cart.append({"id": pk, "quantity": 1}) request.session["cart"] = cart else: request.session["cart"] = [{"id": pk, "quantity": 1}] return redirect("store:cart_view") class CartView(View): def get(self, request): in_cart = [] overall_price = 0 overall_tax = 0 if "cart" in request.session: overall_price = 0 for item in request.session["cart"]: product = Product.objects.select_related("category").get(id=item["id"]) total_price = product.price * item["quantity"] tax = (total_price * product.tax) in_cart.append({ "product": product, "quantity": item["quantity"], "total_price": total_price, "tax": tax }) overall_price += total_price overall_tax += tax part of data will be from a form checkout/forms.py class AddOrderInfoForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['order_by'].disabled = True self.fields['created'].disabled = True class Meta: model = Order fields = '__all__' and checkout/view.py class OrderView(CreateView): template_name = 'order/order_view.html' form_class = AddOrderInfoForm success_url = reverse_lazy('checkout_view') def get_initial(self): return {'order_by': self.request.user} and i want to populate my model several times (depending on the length of my 'cart' dictionary i guess..) model.py class Order(models.Model): order_by … -
Using postgresql with Django
I keep getting this error in the web page Using postgresql. pgadmin 4 Unauthorized The server could not verify that you are authorized to access the URL requested. You either supplied the wrong credentials (e.g. a bad password), or your browser doesn't understand how to supply the credentials required. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': env('DB_PORT'), } } What can i do to fix this issue -
Getting TransactionManagementError on bulk_create with mysql db
I'm trying to create a few objects using Django's bulk_create but I'm getting TransactionManagementError. Django is on django-2.2.24 Mysql is running via docker and I'm using mariadb:10.10.2. Traceback (most recent call last): File "/Users/xyz/Documents/dev/django-proj/sliphy/manage.py", line 21, in <module> main() File "/Users/xyz/Documents/dev/django-proj/sliphy/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/Users/xyz/Documents/dev/django-proj/sliphy/generator/management/commands/generate_backup.py", line 31, in handle self.bulk_create_into_user_trans() File "/Users/xyz/Documents/dev/django-proj/sliphy/generator/management/commands/generate_backup.py", line 78, in bulk_create_trans Transactions.objects.bulk_create(objs, batch_size=100) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/cacheops/query.py", line 411, in bulk_create objs = self._no_monkey.bulk_create(self, objs, *args, **kwargs) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 474, in bulk_create ids = self._batched_insert(objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1211, in _batched_insert self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 1186, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql cursor.execute(sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute return super().execute(sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/cacheops/transaction.py", line 99, in execute result = self._no_monkey.execute(self, sql, params) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers return executor(sql, params, many, context) File "/Users/xyz/opt/miniconda3/envs/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 79, in … -
fetch data from parent model using the foreign key
How can the user access all client details (client model) when the user checks the invoice details(from invoice model) which has a foreign key client model class Clients(models.Model): company_name = models.CharField(max_length=200, blank=True, null=True) clients_name = models.CharField(max_length=200, blank=True, null=True,) phone_number = models.IntegerField(blank=True, null=True ) email = models.EmailField(blank=True, null=True ) invoice model class Invoice(models.Model): clients_name = models.ForeignKey(Clients, on_delete=models.CASCADE, blank=True, null=True) invoice_number = models.CharField(max_length=200, blank=True, null=True) slug = models.SlugField(unique =True) due_date = models.DateField() cost = models.CharField(max_length=200, blank=True, null=True) This is where i get stuck I have a view to fetch details about the invoice. But now i would the user to also view all client details from client model based on the clients_name (the foreign key) def single_invoice_details(request, slug): try: invoice_details = Invoice.objects.get(slug=invoice_number) except: return HttpResponse('cannot be found') return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details}) What i tried def single_invoice_details(request, slug): try: invoice_details = Invoice.objects.get(slug=invoice_number) except: return HttpResponse('cannot be found') clients_details = Clients.objects.filter(clients_name=invoice_details) return render(request, 'invoices/invoice_details.html', {'invoice_details': invoice_details,'clients_details':clients_details}) -
djangoPDF: FileNotFoundError: [WinError 2] The system cannot find the file specified
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable hi; I want to display a PDF file in the navigator; knowing that I installed wkhtmltox-0.12.6-1.msvc2015-win64; but it gives me the following error message in browser: DoesNotExist at /scolar/Prise_en_chargeS2_PDFView/1/ Engagement matching query does not exist. Request Method: GET Request URL: http://127.0.0.1:8000/scolar/Prise_en_chargeS2_PDFView/1/ Django Version: 2.2.10 Exception Type: DoesNotExist Exception Value: Engagement matching query does not exist. Exception Location: C:\Users\LENOVO\workspace\budgetenv\lib\site-packages\django\db\models\query.py in get, line 406 Python Executable: C:\Users\LENOVO\workspace\budgetenv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\LENOVO\workspace\Project_GFC_Remote', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\DLLs', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib', 'C:\Users\LENOVO\AppData\Local\Programs\Python\Python38', 'C:\Users\LENOVO\workspace\budgetenv', in eclipse: File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38\lib\subprocess.py", line 1307, in _execute_child hp, ht, pid, tid = _winapi.CreateProcess(executable, args, FileNotFoundError: [WinError 2] Le fichier spécifié est introuvable need help emergency -
How to use different Pydantic Model in a view to create and respond
Im currently trying to understand the Pydantic FastAPI setup within my Django app and have the following issue: When I create a new Order object, I want to return the newly created object using a different Pydantic model as I use for the creation (as after the creation I now have the ID of the order that I can also return). # routes # Create a new Order @router.post("/create/", response_model=schemas.OrderResponse) def create_orders(order: schemas.OrderResponse): return views.create_order(order=order) # views.py from uuid import UUID from . import models, schemas # Create a new order def create_order(order: schemas.OrderResponse): new_order = models.Order.objects.get_or_create(order) return new_order # schemas.py # pydantic models from uuid import UUID from pydantic import BaseModel # Base Class for Model "Order" class OrderBase(BaseModel): product: str period: str power: int side: str class Config: orm_mode = True class OrderResponse(OrderBase): id: UUID When I now send an API request with this body: { "product": "Base", "period": "Hour", "power": 10, "side": "Buy" } I get this error -- how to set it up such that when creating the instance it doesnt validate for the UUID and after creation and when returning the instance it includes the UUID in the response? { "detail": [ { "loc": [ … -
Docker Image works with docker-compose up but not on Amazon ECS or Heroku
I am trying to host a Django project with a Postgres database in a Docker container. The project is a practice e-commerce site with a database for product info. I was able to get it working with docker-compose up and accessed the site running in the container at localhost:8000 but when I tried hosting it on AWS it didn't work. I uploaded the image to ECR and started a cluster. When I tried running a task with the image, it showed PENDING but as soon as I tried to refresh, the task was gone. I tried setting up cloudwatch logs but they were empty since the task was stopping immediately after starting. After that I tried hosting on Heroku. I was able to deploy the image but when I tried to open the app it showed an error (shown below). It feels like the image is just failing immediately whenever I try hosting it anywhere, but it works fine when I use docker-compose up. I think I'm making a very basic mistake (I'm a total beginner at all this) but not sure what it is. Thanks for taking the time to help. I'll also add my Dockerfile and docker-compose.yml Error … -
Cannot edit user profile and change password of the custom user in django
I have a custom user model in my django project. I can create users using the form based on this model but I'm unable to edit and change the passwords. How can I make this possible? Created the custom user models as shown below. from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): class Role(models.TextChoices): ADMIN = 'ADMIN', 'Admin' DEVELOPER = 'DEVELOPER', 'Developer' TESTER = 'TESTER', 'Tester' base_role = Role.ADMIN role = models.CharField(max_length=20, choices= Role.choices) def save(self, *args,**kwargs): if not self.pk: self.role = self.base_role return super().save(*args, **kwargs) I tried to edit the user the profile and change password using this form. from django.contrib.auth.forms import UserCreationForm from .models import User from django import forms class RegisterUserForm(UserCreationForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email','role', 'password1', 'password2') class EditUserForm(forms.ModelForm): email = forms.EmailField() first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email') corresponding views.py file from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.views.decorators.cache import never_cache from .forms import RegisterUserForm, EditUserForm from django.views import generic from django.urls import reverse_lazy from django.contrib.auth.views import PasswordChangeView from … -
Sent an extra field to serializers -DRF
I have a ModelSerializer with fields from the table SubscriptionsPlans. serializer.py class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = SubscriptionsPlans fields = { 'id', 'name', 'plan_type', 'plan_details', 'price' } I want to sent an extra field name sub_id into this serializer from views. This sub_id will be True or False depending on a table SubscriptionsOrder. If SubscriptionsOrder has rows then the sub_id will be a True else False. SubscriptionsOrder for a specific user is looked here. views.py class SubscriptionView(APIView): def get(self, request): get_sub_id = SubscriptionsOrder.objects.filter(id=request.user).first() sub_id = get_sub_id.plan_selected subscription_details = SubscriptionsPlans.objects.filter(is_deleted=False) user_serializer = SubscriptionSerializer(subscription_details) return Response(user_serializer.data) I want to sent sub_id along with the user_serializer. models.py class SubscriptionsPlans(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255) plan_type = models.CharField(max_length=255) plan_details = models.TextField(max_length=1000) request_per_month = models.IntegerField() price = models.FloatField() is_deleted = models.BooleanField(default=False) created_at = models.DateTimeField() updated_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = 'Subscription Plans' verbose_name_plural = 'Subscription Plans' class SubscriptionsOrder(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey( AppUser, null=True, on_delete=models.SET_NULL ) plan_selected = models.ForeignKey(SubscriptionsPlans, null=True,on_delete=models.SET_NULL) billing_info = models.IntegerField() payment_info = models.IntegerField() class Meta: verbose_name = 'Subscription Order' verbose_name_plural = 'Subscription Order' before sending sub_id the output looks like this { "id": 1, "name": "Professional", "plan_type": "MONTHLY", "plan_details": "{'Details'}", "price": 50.0 }, { "id": 2, "name": "Business", … -
Getting product items from Products table with id's saved in CartItems table (django, sqlite)
I'm new to django and in backend development in general, as well as databases. I have a CartItems and Products models in django. In the CartItems there's only id and product_id columns. How can I get all the products saved in CartItems using the product_id? What I did so far was to use a for loop in CartItems and used the product_id as a parameter to do Products.objects.get(id=id) and append() it to an empty list. And It works. cart_details = [] for item in cart_items: cart_details.append(Products.objects.get(id=item.product_id)) Is this the way to do it? If there's a better way please let me know. Thank you! -
How to get the table details based on post request django
**views.py** from django.shortcuts import render import pymysql from django.http import HttpResponseRedirect from facligoapp.models import Scrapper from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def index(request): user_list = Scrapper.objects.all() page = request.GET.get('page', 1) paginator = Paginator(user_list, 5) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) return render(request, "home.html", { 'users': users }) if request.method == "POST": from_date = request.POST.get("from_date") print(from_date) to_date = request.POST.get("to_date") print(to_date) **home.html** <!DOCTYPE html> <html> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <body> <style> h2 {text-align: center;} </style> <h1>Facilgo Completed Jobs</h1> <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To Date:</label> <input type="date" id="to_date" name="to_date"> <input type="submit"><br> </form> <div class="container"> <div class="row"> <div class="col-md-12"> <h2>Summary Details</h2> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="100%"> <thead> <tr> <th>user_registration_source_id</th> <th>user_type</th> <th>user_id</th> <th>source</th> <th>source_url</th> <th>created at</th> <th>updated at</th> </tr> </thead> <tbody> {% for stud in users %} {% csrf_token %} <tr> <td>{{stud.user_registration_source_id}}</td> <td>{{stud.user_type}}</td> <td>{{stud.user_id}}</td> <td>{{stud.source}}</td> <td>{{stud.source_url}}</td> <td>{{stud.created_at}}</td> <td>{{stud.updated_at}}</td> </tr> {% endfor %} </tbody> </table> {% if users.has_other_pages %} <ul class="pagination"> {% if users.has_previous %} <li><a href="?page={{ users.previous_page_number }}">«</a></li> {% else %} <li class="disabled"><span>«</span></li> {% endif %} {% if user.number|add:'-4' > 1 %} <li><a href="?page={{ page_obj.number|add:'-5' }}">&hellip;</a></li> … -
Django throttling problem when use ManualAPIKey
I am using Django rest API, in one of the views I use manual key authentication when I activate throttling for that view, the request from a same IP address with different API_key count as from same user and reject after several times. For example: I set the rate 12/minute. user1 from a IP 20.40.5.6 send 10 request in a minute, and user2 from a IP 20.40.5.6 send 10 request in a minute. They both get 429 error until next minute. If these user send request from different IPs, there are no problems. class HasManualAPIKey(BasePermission): def has_permission(self, request, view): key = request.META["HTTP_AUTHORIZATION"].split()[1] keys = MyUser.objects.values_list('key', flat=True) if key in keys: return True else: return False class MyUserRateThrottle(UserRateThrottle): rate= '12/minute' class MyUserView(APIView): permission_classes = [HasManualAPIKey] throttle_classes = [DeviceRateThrottle] -
Django Rest Framework : how to specify a serializer to use different fields to create, update and get
I have a doubt with the serializers and so far I have not been able to solve it. I explain the doubt with the following example: I have a User model and this model has the following attributes: username, password, first_name, last_name, age, gender. I also have a serializer, which is called UserSerializer. The UserSerializer should do the following: When inserting information into the database, UserSerializer should only take into account the fields: username, password, first_name, last_name. When retrieving information from the database, UserSerializer should only take into account the fields: age, gender. When updating the database information, UserSerializer should only take into account the fields: password. My solution: class UserSerializer: class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'password', 'first_name', 'last_name'] class UserGetSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['age', 'gender'] class UserUpdateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['password'] Question: The question: is there any way to synthesize the three serializers into one, or what is the best solution for this problem? Thank you very much. -
CORS error appears when I Upload multiple files at once to S3 Bucket with boto3
I have a question about S3 upload, I use boto3 library in python to connect to S3. def get_client(): return boto3.client('s3', aws_access_key_id = 'AWS_ACCESS_KEY', aws_secret_access_key = 'AWS_SECRET_KEY') My Multiple upload file in below for item in img_files: file_type = '' uuid_key = uuid.uuid4() fs = FileSystemStorage() filename = fs.save(f'{S3_TEMP_FOLDER}{uuid_key}-{item.name}', item) file_o_name, file_o_ext = os.path.splitext(filename) if file_o_ext.lower() in ['.jpg', '.png', '.jpeg']: file_type = 'image' else: file_type = 'video' uploaded_file_path = fs.path(filename) try: s3_client.upload_file(uploaded_file_path, bucket_name, f'{folder_key}/{uuid_key}-{item.name}', ExtraArgs={'ACL': 'public-read'}) uploaded_data = { "file_name": item.name, "file_key": f'{folder_key}/{uuid_key}-{item.name}', "bucket_name": bucket_name, "folder_id": get_folder_id.id, "created_by": request.user.username, "updated_by": request.user.username, "bucket_id": bucket.id, "file_type": file_type } S3FileManagement.objects.create(**uploaded_data) except Exception as e: logger.error({'message': str(e)}) logger.error({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}) return Response({'message': S3_FOLDER_MESSAGE['S3_FILE_UPLOAD_FAILED']}, status=status.HTTP_400_BAD_REQUEST) When I upload about 5-10 files at a time, the upload process is no problem, but when I upload > 30 files, there will be some files with 502 - CORS errors. In settings python, I was allows CORS CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOWED_ORIGINS = [ '..{url}..vercel.app', ] CSRF_TRUSTED_ORIGINS = [ '..{url}..vercel.app', ] Additionaly, the python backend I'm using aapanel. Any more additional settings needed? Thanks. -
Django FormView and ListView multiple inheritance error
Problem I have a AccesCheck Mixin, and view named ListFormView that inherits AccessCheck, FormView and ListView to show list and create/update Worker objects. But when I try to add new data by POST method, django keeps returning Attribute Error : Worker object has no attribute 'object_list' error. What is more confusing to me is that whole ListFormView is duplication of another class based view that is used in another app, and the original one is running without any problems. I've doublechecked all my codes and still have no clue to fix this problem. [AccessCheck] class AccessCheck(LoginRequiredMixin, UserPassesTestMixin, View): def test_func(self, *args, **kwargs): access = [x.id for x in Auth.objects.filter(auth_id = self.kwargs['target'])] return self.request.user.is_superuser or selr.request.user.id in access def handle_no_permission(self): return redirect('index') get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['shop'] = Shop.objects.get(shop_id = self.kwars['shop_id']) return context [ListFormView] class Worker(AccessCheck, FormView, ListView): template_name = 'my_template_name.html' context_object_name = 'workers' form_class = WorkerForm success_url = './my_url' def form_valid(self, form): data = form.save() return super().form_valid(form) def get_queryset(self, *args, **kwargs): return Worker.objects.filter(shop_id = self.kwargs['shop_id'])