Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
in django ,how to sum a int field and two float field in jsonb using postgresql
I have a model like this: class Priority(models.Model): base = models.FloatField(default=0) job = models.JSONField() users = models.JSONField() and both job and users are similar. like job = {'a':1,'b':2}, user = {'c':3,'d':4} I want to get the sum ( base + job__a + users__c) how can I write the filter statement, and raw sql is fine too. Thanks -
django connect to mysql and mongodb
I have 2 databases mysql and mongo. On mysql people hold all data and on mongo just images. I have defined them like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '1*****', 'PORT': '1*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, } } } Now I want to run inspectdb on mongodb and I het this error manage.py inspectdb --database mongodb django.db.utils.ConnectionDoesNotExist: The connection mongodb doesn't exist The host password port is ok -
Django and Postgres inserting into many-to-many table not working
I'm using python and psycopg2 to scrape some data and insert them into my database. I've already created the movies and actors tables inside my Django models.py and inside my movies table, there is a many to many relationship between movies and actors table. when I create a movie from Django-admin I select which actors are included in the movie and everything works fine and all the related actors for that movie will show up on my website. But the problem is that when I try to insert scraped data into my database outside of my Django project folder, the related actors won't be shown on my website because obviously, I have not set the many to many relationship between them. I have tried creating a junction table using SQL commands which gets the movie id and the actor's id and links them together but I don't know how I should tell Django to use that table and show the related actors for each movie. I would really appreciate it if someone could help me with this. -
Django image not getting uploaded into my 'media/user_profile_picture' folder
So , my website has a feature where user can upload an image of themselves for their profile picture when they register their account . The model for the same is as follows : class Buyer(models.Model): name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) phone = models.BigIntegerField() email = models.EmailField(max_length=20) address = models.CharField(max_length=100) city = models.CharField(max_length=30) state = models.CharField(max_length=30) pincode = models.IntegerField() dp = models.ImageField(upload_to='user_profile_picture/', blank=True, null=True) created_on = models.DateField(auto_now_add=True, blank=True, null=True) created_by = models.OneToOneField(User, related_name='buyer', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name Now for this model , I have made the following views to extract the relevant data (including images) from the form inside the template when the submit button is pressed @login_required def buyer_profile_details(request): if request.method == 'POST': # creating the buyer object firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') phone = request.POST.get('phone') email = request.POST.get('email') city = request.POST.get('city') state = request.POST.get('state') address = request.POST.get('address') pincode = request.POST.get('pincode') # dp is the user submitted image which I want to get from the form dp = request.POST.get('dp') Buyer.objects.create(name=firstname, last_name=lastname, phone=phone, email=email, address=address, city=city, state=state, pincode=pincode, dp=dp, created_by=request.user) UserType.objects.create(user_type=2, created_by=request.user) return redirect('my_profile') return render(request, 'new_buyer_profile_details.html', {}) And finally this is the template containing the form that I made for getting … -
How to configure the JWT token in django-graphql-jwt to obtain the userId in the token instead of just the username?
TLDR - But by default the JWT token sent from the backend only includes the username. I want the userId as well.This is what it contains currently:- HEADER:ALGORITHM & TOKEN TYPE { "typ": "JWT", "alg": "HS256" } PAYLOAD:DATA { "username": "admin", <---- I have the username already. Need the userId as well! "exp": 1621845856, "origIat": 1621845556 } VERIFY SIGNATURE HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret ) secret base64 encoded I have a Django GraphQL API (using Graphene, django-graphql-auth, django-graphql-jwt) and an Angular frontend. I have authentication setup fully. Now the issue I'm facing is that I'm storing the token in the localstorage and so when the user opens the browser again, I want to verify that token and use just the information in there to obtain the user's id and then use that userId to fetch their user profile information, which is an essential step to complete the login process. I am not sure how to customize the payload to include the userId as well. So that when the user opens the browser after shutting down, I can simply use just the information in the token to fully log them in. I'm very new to both Python and Django. … -
Video Bookmark Using django
How to add video bookmark using django? I am creating a simplle project,in which i want to add a video bookmar it will make better satisfaction for me.Anyone can suggest any tutorial or other sources? -
Django error 'SessionStore' object has no attribute '_session_cache'
the error came out of nowhere, I just woke up with it, i need a quick fix I am using legacy database mysql, yesterday it worked well. Now I want to add one more database and while adding this error popped up. I have deleted all changes but error is still here. This is how I tried to add the new database. I have a table that stores djago session keys all ok DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '1*****', 'PORT': '1*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, 'mongodb': { 'ENGINE': 'djongo', 'NAME': '*****', 'USER': '*****', 'PASSWORD': '*****', 'HOST': '*****', 'PORT': '*****', 'TEST': { 'NAME': '*****', # 'CHARSET': 'utf8', }, } } } AttributeError: 'SessionStore' object has no attribute '_session_cache' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PersonalProjects\AuthenticationProject\auth\app\views.py", line 14, in home return render(request, 'app/common/home.html', context) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "D:\PersonalProjects\AuthenticationProject\env\lib\site-packages\django\template\loader.py", line 62, … -
Combine django and react
I am doing this using axios to combine django and react. While running the program in the command prompt I have to use 2 command prompt! One for running (npm start) And the another for backend (python manage.py runserver) My questions: Is there a way to run a single command in a single command prompt then both the commands should managed. How industries merge them both 🤔 Can we use the same program and change as an apk file and use in mobile app? -
'NoneType' object is not iterable in Django rest framework
I am trying to build a post API for creating the products with their variants. But I am getting this error. I am not sure why it's showing. TypeError at /api/addproducts, 'NoneType' object is not iterable My full traceback is as follows: Traceback: File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch 495. response = self.handle_exception(exc) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in handle_exception 455. self.raise_uncaught_exception(exc) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/views.py" in dispatch 492. response = handler(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/generics.py" in post 192. return self.create(request, *args, **kwargs) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/mixins.py" in create 21. self.perform_create(serializer) File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/mixins.py" in perform_create 26. serializer.save() File "/home/aakashlabs/rupseonline/venv/lib/python3.8/site-packages/rest_framework/serializers.py" in save 214. self.instance = self.create(validated_data) File "/home/aakashlabs/rupseonline/apps/products/api/serializers.py" in create 152. for variants_data in variants_data: My models: class Variants(models.Model): SIZE = ( ('not applicable', 'not applicable',), ('S', 'Small',), ('M', 'Medium',), ('L', 'Large',), ('XL', 'Extra Large',), ) AVAILABILITY = ( ('available', 'Available',), ('not_available', 'Not Available',), ) product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = … -
Cannot pass JavaScript variable to Django View.py
I have a JavaScript function that will get the user input and store it into an array called tableData. I want the tableData value in javascript to be use in Django view.py. I had tried to use AJAX and post method to send my tableData. But whenever i clicked on submit it show me error. Html template <!DOCTYPE html> <html lang="en"> <html> <head> <link href="https://fonts.googleapis.com/css?family=Quicksand:300,500" rel="stylesheet" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <style> .buttonSubmit { background-color: #4caf50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .del_img { background-color: Transparent; background-repeat: no-repeat; border: none; cursor: pointer; overflow: hidden; outline: none; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } body { font-family: "Quicksand", sans-serif; } .button { border-radius: 50px; background-color: #ff9633; border: none; color: #ffffff; text-align: center; font-size: 15px; padding: 10px; width: 80px; transition: all 0.5s; cursor: pointer; margin: 5px; margin-left: 500px; } .button span { cursor: pointer; display: inline-block; position: relative; transition: 0.5s; } .button span:after { content: "\00bb"; position: absolute; opacity: 0; top: 0; … -
Django:Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name
I am. trying to. build a search function for my django project base on the enter link description here and the error message popped out "Reverse for 'Search' not found. 'Search' is not a valid view function or pattern name." i have done the searching most of the advise asking me to check if the spelling is error like my "search" in url or my search.html in my render however, i have tried all the solution it still can't work here is some of my code urls.py: from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm,VendorForm def search_product(request): if request.method == "POST": query_name = request.POST.get('title', None) if query_name: results = Product.objects.filter(name__contains=query_name) return render(request, 'products/search.html', {"results":results}) return render(request, 'products/search.html') views.py from django.shortcuts import render from .models import Product from .forms import ProductForm, RawProductForm,VendorForm def search_product(request): if request.method == "POST": query_name = request.POST.get('title', None) if query_name: results = Product.objects.filter(name__contains=query_name) return render(request, 'products/search.html', {"results":results}) return render(request, 'products/search.html') search.html <!DOCTYPE html> <html> <head> <title>Django Search</title> </head> <body> <form action="{% url 'search' %}" method="POST"> {% csrf_token %} <input type="text" name="name"> <input type="submit" name="submit" value="Search"> </form> {% for result in results %} <p>{{result.name}}</p> {% endfor %} </body> </html> and following is my … -
What is the proper way to start the Bagroundscheduler Apscheduler
I have a django rest framework application, whenever a request comes to this API i have to schedule an action to be performed later by the BackgroundScheduler at a specific time. Here is what i did: in views.py from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore def do_someting(): print("doing someting ...") class HumanAgentManagerView(APIView): def post(self, request): timeout = request.data["timeout"] activation_date = datetime.now() + timedelta(minutes=timeout) try: scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") s = scheduler.add_job(do_someting, 'date', run_date=activation_date, args=[]) try: scheduler.start() except: pass except: pass return Response({"success": "ok"}) So what i did here, at each request that comes to this endpoint by a user, i initialize a new scheduler instance, add the job to it then start it. My question is : Is this the proper way to start and implement the scheduler i saw in this link django - apscheduler how to keep job when uwsgi restart a different implementation of the BackgroundScheduler it instanciate it once and uses that instance for adding all jobs. I appreciate your help and advices in advance. -
How to delete table content from sqlite Django
I want to delete the data when pressing the trash bin button. I am able to submit, edit petty cash into the database. I am only left with deleting the data. This is my views.py def deleteclaims(request, id): context = initialize_context(request) user = context['user'] #get id of particular form. claims = SaveClaimForm.objects.get(id=id) if request.method == 'POST': claims.name = request.POST['name'] claims.email = request.POST['email'] claims.claim = request.POST['claim'] claims.claimtype = request.POST.get('claimtype') claims.description = request.POST['description'] claims.receipt = request.FILES['receipt'] claims.cheque = request.POST.get('Cheque') claims.status = request.POST['status'] claims.delete() claims.save() return render(request, 'Login/existingclaims.html', {'claims':claims, 'user':user}, {'action' : 'Delete claims'}) In my html <tr align="center"> <td>{{ claims.id }}</td> <td>{{ claims.name }}</td> <td>{{ claims.email }}</td> <td>{{ claims.claim }}</td> <td>{{ claims.claimtype }}</td> <td>{{ claims.description }}</td> <td><a href="/media/{{ claims.receipt }}"> Click to View </a></td> <td>{{ claims.cheque }}</td> <td>{{ claims.status }}</td> <td><a href="/editclaims/{{claims.id}}"><i class="fas fa-pencil-alt"></i></a></td> <td><a href="/deleteclaims/{{claims.id}}"><i class="fas fa-trash"></i></a></td> </tr> -
Django form if input empty how to show warning
I created a form with file input. User can post the form with or without uploading a document. But how can I show a warning if the user does not upload a form when click upload button? forms.py class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ['title', 'pdf', 'document_type', 'year', 'payment_behavior'] labels = { "payment_behavior": "Please Select the Payment Behavior of the Customer: ", "document_type": "Document Type", "title": "Document Name", "pdf": "Please Select a File to Upload", "year": "Financial Table Year" } models.py class Pdf(models.Model): ... id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) year = PartialDateField(null=True, blank=True) ... template.html <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy }} <div class="btn-group" role="group" aria-label="Basic example"> <button type="submit" class="btn btn-success">Upload File</button> <button type="submit" class="btn btn-warning">Non-report analysis</button> </div> </form> -
ModuleNotFoundError: No module named 'grp' on windows
As i was going through the Celery implementation from the Celery documentation, celery -A tasks worker --loglevel=INFO gave output unexpected that from the documentation, File "d:\101_all_projects\celery-testing\venv\lib\site-packages\celery\platforms.py", line 9, in import grp ModuleNotFoundError: No module named 'grp' Is this because i am on windows? -
django python if statement
I am trying to run a basic if statement in Django. I want to dispaly banner model.py class Banner(models.Model): title = models.CharField(max_length=250) sub_title = models.CharField(max_length=500) banner_img = models.FileField() def __str__(self): return self.title view.py class BannerView(generic.ListView): template_name = 'website/index.html' context_object_name = 'all_banners' def get_queryset(self): return Banner.objects.all() index.html {% if all_banners %} {% for banner in all_banners %} <img src="{{ banner.banner_img.url }}" class="card-img-top" alt="..."> {% endfor %} {% else %} <h3>You don't have any banner</h3> {% endif %} basicly i need display banner. i did upload the banner from admin page i get the output else statement pls give me adivse -
Django - Boolean Fields on Checkbox Input
I have a ModelForm which has Boolean Field and CheckboxInput. The Boolean field provides values of 0 (False) & 1 (True) by default in the MYSQL Database. The form is a modal and uses JSON to output the content from the Model. When the JSON file adds the content it enters either True or False. The issue occurs when I try to change and submit the value of the Checkbox Input from False to True. When I try this I get the following message: Oddly this works the other way around and allows me to submit the change from True to False. Below is the code (I have only included the field with the issue.) The field is First_Time_Booking Model. first_time_booking = models.BooleanField() Form Widget. 'first_time_booking': CheckboxInput(attrs={'class': 'form-check-input', 'id': 'bfbw_edit_first_time_booking', 'name': 'bfbw_edit_first_time_booking'}), View def update_bfbw(request): if request.method == 'POST': bfbw_booking_id = request.POST.get('bfbw_booking_ref') bfbw_data = BFBWBookings.objects.get(id=bfbw_booking_id) bfbw_data.school_name = request.POST['school_name'] bfbw_data.first_time_booking = request.POST.get('first_time_booking', False) bfbw_data.save() else: print(form.errors) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) I have tried writing an If function to alter the value, this then works to change the value to On but not when switching it off. I then get the below message. if request.POST['first_time_booking'] == 'on': bfbw_data.first_time_booking = True else: bfbw_data.first_time_booking = False … -
How to delete an image using default_storage.delete(file_name) in Django View?
So I have been creating a Fingerprint Matching system using Django Rest Framework. Whenever I send a fingerprint from frontend to backend to match with the stored fingerprints. The fingerprint is getting stored there which is not what I want. I want to delete it once it's use is over. Here is the Error Image: https://i.stack.imgur.com/MCXcv.png def post(self, request, format = None): serializer = serializers.MatchSerializer(data = request.data) if serializer.is_valid(): #Fetching the stored fingerprints in a different serializer. queryset = models.Profile.objects.all() serializer2 = serializers.ProfileSerializer(queryset, many=True) data = serializer2.data #Initialized a result list which will be appended with the name of the user whose #fingerprint is matched. result = [] file = request.FILES['fingerprint'] file_name = default_storage.save(file.name, file) file = default_storage.open(file_name) file_url = default_storage.url(file_name) fImage = cv2.imread(str(file)) for i in range(len(data)): print(data[i].get('fingerprint')) DbImage = cv2.imread('C:/Users/ShalomAlexander/Documents/4th Year Project/Django/FingerprintMatch/' + data[i].get('fingerprint')) if(isMatch(fImage, DbImage)): result.append(data[i].get('name')) #This is not working as expected because its raising an error ie. " Process is still #[![enter image description here][1]][1]in use" default_storage.delete(file_name) return Response(result) If you have any better approach to match fingerprints or images that will also be appreciated. Thanks in advance. The current code works fine and matches the fingerprint as expected but its storing the incoming fingerprint image … -
'for' statements should use the format 'for x in y': for allPosts in allPost1 and allPost2 and allPost3 and allPost4
I have so many keys in params and i want to display it on the template than i got an error that 'for' statements should use the format 'for x in y': for allPosts in allPost1 and allPost2 and allPost3 and allPost4 {% for allPosts in allPost1 and allPost2 and allPost3 and allPost4 %} .... {% endfor %} def search1(request): .... params = {'allPost1': allpost1,'allPost2': allpost2,'allPost3': allpost3,'allPost4': allpost4, 'query': query} return render(request, "home/search1.html", params) Please Help me. -
how to make a unique WATCHLIST for every USER in django REST and how to call the watchlist api based on that user
I am working on a practice Video streaming site based on Django and React. I am a little stuck on how to manage the Watchlist model in Django and make requests in React based on currently logged-in users. -
Website get crashed after running the game
I have a gaming website developed using the Python Django framework. In the game, more than 600 people visit at a time and it generates 1-90 random numbers to decide the winners. Every time when the game starts running the complete CPU starts to drain up to 99% and the website gets crashed. I already changed the server multiple time. Please let me know if there is any solution -
Update or Ignore || Update or Add || Add or Ignore || Ignore completely
@require_http_methods(["POST"]) @login_required def edit_guided_answer(request): req = json.loads(request.body) question_no = req["question_no"] guided_answers = req["guided_answer"] for guided_answer in guided_answers: models.ModelAnswer.objects.filter(answer_id=guided_answer["answer_id"]).update( answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"], ) for guided_answer in guided_answers: models.ModelAnswer.objects.create( question_id=models.Questions.objects.get(pk=question_no), answer_mark=guided_answer["answer_mark"], model_ans=guided_answer["model_ans"], ) return success({"res": True}) So what my code above is meant to do is to fit both the update and create at the same time, however i am trying to condition it so that i can update, add, ignore or update and add, however when i try to do this i get a key error.Is there a better solution for this? -
Django DJANGO_SETTINGS_MODULE
Is there a way i can specify the IP:Port in DJANGO_SETTINGS_MODULE (setting.py), instead of using python manage.py runserver <ip>:<port>? like we specify ALLOWED_HOST, INTERNAL_IPS etc -
How to get parent node name while using django mptt package in django rest serializers?
I am only getting parent id with this code, but i need parent node name . Is it possible to get parent node name ? class Department(MPTTModel,NameStatusModelMixin): desc = models.TextField(blank=True, null=True, default=None) slug = models.SlugField(max_length=100, blank=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') related_positions = models.ManyToManyField('Position', related_name='departments') class MPTTMeta: order_insertion_by = ['id'] def __str__(self): return self.name class DepartmentDetailSerializer(ModelSerializer): class Meta: model = Department fields = ('id', 'name', 'status', 'slug', 'desc', 'parent') -
Mysql transaction doesn't work in multi-thread
I'm using django and multi-thread in my task. Main logic code as below showed: # -*- coding: utf-8 -*- import os import logging import json import threading from django.conf import settings from django.core.management.base import BaseCommand from django.db import transaction from user_account.models import FbHandleTask, FbAccountSpendCapHandle, FbAccountBindingBmHandle, \ FbAccountNameHandle, FbAccountUserPermissionHandle, FbPixelBindingAccountHandle, FbPixelBindingBmHandel, FbBusinessUserInfo from utils.common import make_hash fb_batch_operate_logger = logging.getLogger('fb_batch_operate_producer') FB_HANDLE_DICT = { 'spend_cap': FbAccountSpendCapHandle, 'change_name': FbAccountNameHandle, 'user_permission': FbAccountUserPermissionHandle, 'binding_bm': FbAccountBindingBmHandle, 'pixel_account': FbPixelBindingAccountHandle, 'pixel_bm': FbPixelBindingBmHandel } class FbTaskTypeEnum(object): spend_cap = "spend_cap" change_name = "change_name" user_permission = "user_permission" binding_bm = "binding_bm" pixel_account = "pixel_account" pixel_bm = "pixel_bm" class FbTaskHandler(object): def __init__(self, category): self.category = category def work(self): try: accounts = FB_HANDLE_DICT[self.category].objects.filter(status=0, is_delete=0) if accounts: model_ids = [i["id"] for i in accounts.values("id")] with transaction.atomic(): accounts.update(status=4) # the status sometimes changed fb_batch_operate_logger.info("[status changed] with ids: {}".format(json.dumps(model_ids))) temp_id_list = [model_ids[i: i + 20] for i in range(0, len(model_ids), 20)] fb_task_list = [] handle_id_list = [] for handle_ids in temp_id_list: handle_ids = json.dumps(handle_ids) unique_hash = make_hash(self.category, handle_ids) fb_batch_operate_logger.info("[hash generated] hash: {}, with ids: {}".format(unique_hash, json.dumps(handle_ids))) fb_task = FbHandleTask( category=self.category, handle_ids=handle_ids, handle_status=0, user_name="automatic", unique_hash=unique_hash, ) try: FbHandleTask.objects.get(unique_hash=unique_hash) fb_batch_operate_logger.info("[hash existed] with ids: {}".format(json.dumps(handle_ids))) except Exception: fb_task_list.append( fb_task ) handle_id_list.append(handle_ids) fb_batch_operate_logger.info("[hash not existed] with ids: {}".format(json.dumps(handle_ids))) if fb_task_list: FbHandleTask.objects.bulk_create(fb_task_list) # …