Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Integrity error not null for ForeignKey id field
I have a model which contains ForeignKeys to a number of other models and find, for some reason, I am able to save one of these models absolutely fine, but another I receive a fault message saying: IntegrityError: NOT NULL constraint failed: app_eofsr.flight_id See below for my models.py: # models.py class Aircraft(models.Model): esn = models.IntegerField() acid = models.CharField(max_length=8) engpos = models.IntegerField() operator = models.CharField(max_length=5, default='---') fleet = models.ForeignKey(Fleet, blank=True) slug = models.SlugField(default=None, editable=False, max_length=50, unique=True) class EoFSR(models.Model): datetime_eofsr = models.DateTimeField(default=None) flight_number = models.CharField(max_length=10) city_from = models.CharField(max_length=4) city_to = models.CharField(max_length=4) and these both feed into this model: # models.py class Flight(models.Model): flight_number = models.CharField(max_length=10) city_from = models.CharField(max_length=4, default=None) city_to = models.CharField(max_length=4, default=None) datetime_start = models.DateTimeField(default=None) aircraft = models.ForeignKey(Aircraft, on_delete=models.CASCADE) eofsr = models.ForeignKey(EoFSR, on_delete=models.CASCADE) The odd thing being, I can save an Aircraft record no problem at all, but cannot save an EoFSR record and receive the NOT NULL constraint error message. I've done the usual deleting of the migrations and even tried deleting the db.sqlite3, but still no luck! Any suggestions? -
i have a django channels backend and i need a react redux typescript frontend to connect with that
from channels.generic.websocket import WebsocketConsumer from channels.db import database_sync_to_async import json from channels.consumer import AsyncConsumer from chat.models import Thread, Chat from chat.serializers import ThreadSerializer, ChatSerializer from network.models import Connection class ChatConsumer(AsyncConsumer): async def websocket_connect(self, event): self.sender = self.scope['url_route']['kwargs']['sender_id'] self.receiver = self.scope['url_route']['kwargs']['receiver_id'] self.thread_id = await self.get_thread(self.sender, self.receiver) self.chat_room = f'thread_{self.thread_id}' chat = await self.get_chat(self.thread_id) await self.channel_layer.group_add( self.chat_room, self.channel_name ) await self.send({ 'type': 'websocket.accept', }) await self.send({ 'type': 'websocket.send', 'text': chat }) async def websocket_receive(self, event): try: data = json.loads(event.get('text'))['text'] if data: recent_message = await self.create_chat(self.sender, self.thread_id, data) await self.channel_layer.group_send( self.chat_room, { 'type': 'send_recent_message', 'text': recent_message } ) else: await self.send({ 'type': 'websocket.send', 'text': 'No text containing message found.' }) except: await self.send({ 'type': 'websocket.send', 'text': 'Error, kindly send data in right format.' }) async def websocket_disconnect(self, event): print('Disconnected :-<', event) @database_sync_to_async def get_chat(self, thread_id): chat = Thread.objects.get(id = thread_id).messages serializer = ChatSerializer(chat, many = True, context = {'sender' : self.sender}) return json.dumps({"messages" : serializer.data}) @database_sync_to_async def create_chat(self, sender_id, thread_id, text): serializer = ChatSerializer(data = {'sender' : sender_id, 'thread' : thread_id, 'text' : text}, context = {'sender' : self.sender}) if serializer.is_valid(): serializer.save() # return json.dumps({"messsage" : serializer.data}) return json.dumps(serializer.data) # return text return serializer.errors @database_sync_to_async def get_thread(self, sender_id, receiver_id): thread = Thread.objects.filter(first_member_id = … -
Uncaught TypeError: dataFn.call is not a function in VueJS 3
I am trying to resolve the following error:- Uncaught TypeError: dataFn.call is not a function at resolveData (vue.global.js:7141) at applyOptions (vue.global.js:6947) at finishComponentSetup (vue.global.js:7718) at setupStatefulComponent (vue.global.js:7649) at setupComponent (vue.global.js:7589) at mountComponent (vue.global.js:5311) at processComponent (vue.global.js:5287) at patch (vue.global.js:4915) at render (vue.global.js:5988) at mount (vue.global.js:4253) I am using VueJS version 3 and I am not sure what is wrong with my following code:- const FormApp = { delimiters: ['[[', ']]'], data: { username: null, password: null, success_msg: "", err_msg: "ERROR", FILE: null, }, methods: { onFileUpload (event) { this.FILE = event.target.files[0] }, submitForm: function(){ this.success_msg = "" this.err_msg = "" const formData = new FormData() // formData.append('avatar', this.FILE, this.FILE.name) formData.append('username', this.username) formData.append('password', this.password) axios({ method : "POST", url:"{% url 'submitform' %}", //django path name headers: {'X-CSRFTOKEN': '{{ csrf_token }}', 'Content-Type': 'application/json'}, data : formData, }).then(response => { this.success_msg = response.data['msg']; }).catch(err => { this.err_msg = err.response.data['err']; }); }, }, }; Vue.createApp(FormApp).mount('#counter') and my HTML looks like below:- <div class="panel-body" id="app"> <div id="counter"> Counter: [[err_msg]] </div> </div> Can anyone explain me what's wrong in my code? -
Gunicorn taking up 100% on 72 core cpu (Django + Nginx)
I have a Django app with Nginx , gunicorn and postgresql as database. I have a aws server c5.18xlarge (72 cores and 137 gb ram). The problem is it gets slow with only 50 concurrent users. Using htop I found out that most of the cpu usage and ram is used by gunicorn workers and postgreql workers. Here is the htop screenshot: In the screenshot the usage is lower (38% load and around 100 gb of ram used ) because users are less. But as soon as there are 50 + concurrent users the usage goes to 100% in both cpu and ram. Here is the gunicorn worker settings: NAME="django_app" # Name of the application DJANGODIR=/home/ubuntu/bodhiai # Django project directory SOCKFILE=/home/ubuntu/env/run/gunicorn.sock # we will communicte using this unix socket USER=ubuntu # the user to run as GROUP=ubuntu # the group to run as NUM_WORKERS=72 # how many worker processes should Gunicorn sp TIMEOUT=120 DJANGO_SETTINGS_MODULE=app.settings # which settings file should Django use DJANGO_WSGI_MODULE=app.wsgi # WSGI module name echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/ubuntu/env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir … -
In Django, how to create join on either primary keys?
So, in Django, we have two models. model1(models): pk1 = models.pk(model2, on_delete=models.CASCADE) pk2 = models.pk(model2, on_delete=models.CASCADE) model2(models) somefield = models.charfield() I'd like to create a query to join then and match on either the first primary key or the second The sql equivalent would be select * from model1 join model2 on (model2.id = model1.pk1__id or model2.id = model1.pk2__id) for now I'm stucked with Model1.objects.select_related('model2') which always match on the first pk -
Change colors using CSS on a bootstrap .collapsed selector
Here is the important code in my Django template: <a class="notibell" data-toggle="collapse" href="#pgsettings"><i class="fa fa-bell"></i></a> <div class="collapse" id="pgsettings"> # content to show using the toggle anchor tag above. </div> I'm using this css in the page <head>: <style type="text/css"> .notibell.collapsed { color: green !important; text-shadow: 2px 2px 2px #ccc; } .notibell { color: red; text-shadow: 2px 2px 2px #ccc; } </style> On page load, the icon color is red (should be green). Then on click, the color remains red (correct color for expanded div). And then another click and the color changes to green (correct color for collapsed div). Then from this point forward the toggle and colors change correctly. The problem is on the page load, the color renders incorrectly despite the !important condition. I've also tried loading css in the head before and after bootstrap loads, but this hasn't made a difference. Thanks in advance, any help is appreciated. -
Django filtering DB items in a chain sequence
I am trying to build a project where I have a DB with toys where there are brands, each brand have products, the products have variety of sizes and sizes have colors. What I want to achieve is to have a home page with filtered the brands which I manage to achieve with the views.py below: def Index(request): toys = Toys.objects.values('brand').distinct().order_by('brand') context = {'index': toys } return render(request, 'index.html', context) with models.py class Vehicles(models.Model): brand= models.IntegerField(max_length=255) product = models.CharField(max_length=255) size = models.CharField(max_length=255) color = models.CharField(max_length=255) Now on the main page I have a list with all the different brans, what I'm trying to do is when I click on any Brand for the home page to redirect me to a result page with list of the Brand's products, product will lead to all available sizes and so on. How to implement that in the views? -
Multiple session in R
Can we create multiple sessions in R language . I am not using Rstudio or shiny app . I am just integrating R and python using pip module pypeR. I cannot see any R code where i can learn to create session. My requirement is to create a new session for every R request from python. Because whenever there are two requests to R at the same time my server gets blocked. Also i have used "pypeR" module to integrate R with python. I am a newbie in R as i have worked more in python.I have searched a lot about this issue and it seems to me that R works only in single session when called as a script through python. Any help would be appreciated. -
Is it good or bad practice to reference a single library.py file with all imports?
I am making a Django project with multiple apps and was wondering if it would be considered good or bad practice to create a single library.py file with all the "import x" and "from x import y, z" statements and then simply put "from library.py import *" at the top of every other file? What would be considered best practice for managing your imported libraries like this? Thanks for the help. -
Include my post with followers post in Django
How I can include my post with the followers' post def get(self, request, *args, **kwargs): logged_in_user = request.user video = Video.objects.filter( author__follow__in=[logged_in_user.id] ).order_by('-created_date') -
Websocket connection getting closed automatically when sending data from an external api
I am new to django channels and trying to send an api response to an active websocket connection, but as soon as I do it, it is getting disconnected. can someone please check this code and tell me what I did wrong? Thanks inside api view: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'chat-{}'.format(str(chat.id)), { 'type': 'external.message', 'text': json.dumps(serializer.data), } ) in consumer def external_message(self, event): print(event) self.send({ 'type': 'websocket.send', 'text': event['text'] }) The event is getting printed, but the connection is getting closed. -
UNIQUE constraint failed: restaurant_payment.transaction_id in django 3
I want to make payment for my project. when clicked button Make Payment in my checkout, field customer and order will be filled automatically and redirect to template PaymentView for enter customer full name, and proof of payment. But i get this error, anybody can help me ? enter image description here views.py def makePayment(request): customer = request.user.customer order = Order.objects.get(customer=customer) payment, created = Payment.objects.get_or_create( order=order, customer=customer) payment.save() print(order) return redirect('restaurant:payment') class PaymentView(CreateView): model = Payment form_class = PaymentForm template_name = 'restaurant/payment.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) if self.request.user.is_authenticated: customer = self.request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.ordermenu_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} cartItems = order['get_cart_items'] context['items'] = items context['order'] = order context['cartItems'] = cartItems context['page_title'] = 'Payment' return context def get(self, *args, **kwargs): if self.request.user.is_authenticated: customer = self.request.user.customer order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.ordermenu_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} cartItems = order['get_cart_items'] if cartItems == 0: return redirect('restaurant:order') else: return super().get(*args, **kwargs) in function makePayment, used for fill in the fields customer and order, and will be redirect to PaymentView. urls.py from django.urls import … -
Return JSONresponse in custom authentication class django
I am trying to write a custom authentication class inside a app called helpers which should be called before every api request Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'helpers.authentication.ExampleAuthentication', ] } helpers/authentication.py class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): IDP_ADDRESS = "https://localhost:8000/api/environments.json" # header = request.headers.get('Authorization') header = "Token token=portal_toke" if header is not None: response = requests.get(IDP_ADDRESS, headers={"Authorization": header}) print(response.status_code) if response.status_code != requests.codes.ok: if response.status_code != requests.codes.ok: return JsonResponse({ "status": "fail", "message": "unauthorized" }) I need to return the json response once validation fails. But am getting below error File "D:\Users\service\env\lib\site-packages\rest_framework\request.py", line 387, in _authenticate self.user, self.auth = user_auth_tuple ValueError: not enough values to unpack (expected 2, got 1) -
Django queryset to order by list of item matches in one of the fields
Im working on a queryset which requires a complex ordering of queryset. here is my model.py class ItemTable(models.Model): item_name = models.CharField(max_length=50) class tableA(models.Model): user = models.OneToOneField(User, primary_key=True) items = models.ManyToManyField(ItemTable, on_delete=models.CASCADE) class tableB(models.Model): type = models.CharField(max_length=50) items = models.ManyToManyField(ItemTable, on_delete=models.CASCADE) Im not sure how do I do a query on tableB to with specific items passed from the request.body and then match/compare the items from tableA and replace the entire items values on tableB obj with only matching queryset and order them based on the counts on the replaces items list for each obj. Eg: tableB_qs = tableB.objects.filter(items__in=["list_of_ids_from_request_body"]) items_list_from_tableA = tableA.objects.get(id=request.user).items then --> Compare items_list_from_tableA with tableB_qs each object property "items". then -->> replace the matched only ingredients to the items list for each obj in tableB qs. then -->> Order the final qs based on the count of items for an obj in tableB qs -
How to redirect a local app to a url on django?
I have a local app running localy on localhost:9000, and my django website (running on docker) on localhost:8000 which is exposed to the internet i.e. mydomain.com. How could redirect this local webapp for exemple to mydomain.com/webapp. I cannot modify the local webapp at all, consider it a black box that can only ouput on localhost:9000. Using Django, how can I do it ? -
checking which decimal is bigger django
Im having problem with one line of code... Im trying to check which decimal is greater, i checked few answers from stackoverflow and they didnt work (probably cuz they were from 7 years ago :P) anyways here is my view: auction = all_auctions.objects.get(id= my_id) comment_num = auction.comments.all().count() all_comments = auction.comments.all() context = { "auction": auction, "bid_auction": auction.bid.all(), "comment_num": comment_num, "all_comments": all_comments } if request.method == "POST" and "bid" in request.POST: if request.user.is_authenticated: highest_bid = request.POST["bid"] if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])): all_bid = bids.objects.create(bid = highest_bid) auction.bid.add(all_bid) if request.method == "POST" and "watch"in request.POST: if request.user.is_authenticated: if auction not in request.user.watchlist.all(): request.user.watchlist.add(auction) else: request.user.watchlist.remove(auction) if request.method == "POST" and "comment" in request.POST: comment = request.POST["comment"] if request.user.is_authenticated: comment_now = comments.objects.create(comment = comment) auction.comments.add(comment_now) return render(request, "auctions/dynamic_auction.html", context) and there is the problematic line: if not Decimal(highest_bid) <= Decimal(int(auction.bid.all().reverse()[0])): in models: from django.contrib.auth.models import AbstractUser from django.db import models class comments(models.Model): comment = models.TextField(blank=False) class bids(models.Model): bid = models.DecimalField(decimal_places = 2, max_digits = 100000) class all_auctions(models.Model): category = models.CharField(max_length= 14, default = "none") title = models.CharField(max_length= 14) description = models.TextField(blank=False) photo_url = models.CharField(max_length= 500000) bid = models.ManyToManyField(bids, blank = True, related_name = "bid_auction") comments = models.ManyToManyField(comments, blank = True, related_name = "comments") … -
Django Signal request_finished get user instanse
I try to understand Signals in Django. I am creating project for DRF. from django.dispatch import receiver from django.contrib.auth.signals import user_logged_in from django.core.signals import request_finished For this Signal I can catch user @receiver(user_logged_in) def last_user_login(sender, request, user, **kwargs): print('User **{}** logged in'.format(user)) And I want to catch user for this signal, but it's impossible as I understood. @receiver(request_finished) def last_user_request(sender, **kwargs): print('User made request') My target: catch last user request and write this data to db. Could someone help me? Thanks. -
it is problem when i open runserver and i dont understand error [closed]
RelatedObjectDoesNotExist at / User has no customer. Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: RelatedObjectDoesNotExist Exception Value: User has no customer. Exception Location: C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\related_descriptors.py, line 421, in get Python Executable: C:\Users\Dell\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.1 Python Path: ['C:\Users\Dell\Desktop\ecommerce', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39', 'C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Mon, 15 Mar 2021 11:58:17 +0000 -
Cannot use ArrayField from Djongo Models
I'm trying to make an app with Django using MongoDB as my database engine, so I'm using Djongo as ORM. In my models, I have defined a Client class, which is intended to contain an array of Profiles (authorized people to login in name of client). In the Djongo Documentation, it says one can use the ArrayField class in models in order to store an array to the database. The point is that I followed the example in the documentation (even I tried to copy without changing anything) and it isn't working. When running the view, I always get this error: "Value: Profile object (None) must be an instance of <class 'list'>" I have the following models.py: from django import forms from djongo import models class Profile(models.Model): _id=models.ObjectIdField() fname = models.CharField(max_length=25) lname = models.CharField(max_length=50) email = models.EmailField() password = models.CharField(max_length=16) class Meta: abstract=True class ProfileForm(forms.ModelForm): class Meta: model = Profile fields =( 'fname', 'lname', 'email', 'password', ) class Client(models.Model): #informacion del cliente _id = models.ObjectIdField() name = models.CharField(max_length=256) authorized = models.ArrayField( model_container=Profile, model_form_class=ProfileForm ) objects = models.DjongoManager() class ClientForm(forms.ModelForm): class Meta: model = Client fields = ( 'name', 'authorized' ) I have a form that uses ClientForm, and the view … -
Get Element inside Array With Django-MongoDB (Djongo)
I am using Django with MongoDB as my database. I create a model (MyObject) and one field is an ArrayField type that contains in wich entry Json Fields. For that I created an abstract model. So my models.py : class MyObject(models.Model): ... myArrayField = models.ArrayField(model_container=NIC, null=True, blank=True, default=[]) ... class MyAbstractObject(models.Model): field1 = models.CharField(null=True, blank=True, max_length=100, default="") field2 = models.IPAddressField(blank=True, null=True, default="") class Meta: abstract = True In mongoDB I have: MyObject: { ... myArrayField: [{field1: "abc", field2: "1.1.1.1"}] ... } Now I want to get the element that have the value "1.1.1.1", how can I do that? I try: q1 = MyObject.objects.filter(myArrayField__contains='1.1.1.1') q2 = MyObject.objects.filter(myArrayField_0_field2='1.1.1.1') q3 = MyObject.objects.filter(myArrayField__contains={'field2':'1.1.1.1}) Can you help me? -
how to send multiple images to user in django?
I am new to Django I wanted to make an app that will send assignment files from teacher to students but I have no idea how to implement it with Django please anybody has an idea about this please help me. -
I'm trying to get in from the main page to another page and there's a problem with slug/url What's the problem with what I wrote?
I write a project of a list of films with their details(IMDB), when I click on the image of a film he doesn't go to the page of that film, i do not understand where the problem is in url on html file or in the models ? husdfguejhfuwkjhruefgwdujshfjrwueruyiwyerwhiuiuen 8yryeriwkeuriwur yehikyrhiwkyrew fyeier Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/movies/%7B$%20url%20'movies:movie_detail'%20movie.slug%20%25%7D Using the URLconf defined in django_movie_center.urls, Django tried these URL patterns, in this order: admin/ movies/ [name='movie_list'] movies/ category/<str:category> [name='movie_category'] movies/ language/<str:lang> [name='movie_language'] movies/ search/ [name='movie_search'] movies/ <slug:slug> [name='movie_detail'] movies/ year/<int:year> [name='movie_year'] ^static/(?P<path>.*)$ ^media/(?P<path>.*)$ The current path, movies/{$ url 'movies:movie_detail' movie.slug %}, didn't match any of these. models.py: from django.db import models from django.utils.text import slugify # Create your models here. CATEGORY_CHOICES = ( ('action','ACTION'), ('drama','DRAMA'), ('comedy','COMEDY'), ('romance','ROMANCE'), ) LANGUAGE_CHOICES = ( ('english','ENGLISH'), ('german','GERMAN'), ('hebrew','HEBREW') ) STATUS_CHOICES = ( ('RA' , 'RECRNTLY ADDED'), ('MW' , 'MOST WATCHED'), ('TR' , 'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') category = models.CharField(choices=CATEGORY_CHOICES , max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField( max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() slug = models.SlugField(blank=True, null=True) def save(self, *args, **kwargs): if … -
How to convert webscraping into django api?
I'm trying to scrape some data on two websites. I successfully scraped it. I also want to develop an API using this scraped data using Django. But when I try to display the scraped data in JSON format in Django. It only shows an empty list. Below I attached my code snippets. from django.shortcuts import render from bs4 import BeautifulSoup import requests import re import json import time data = [] def getURL(url): url = url.replace(' ', '-').lower() for char in url: if char in "?.!:;|/[]&()": url = url.replace(char, '-') if char == "'" or char == ",": url = url.replace(char, '') decodeUrl = re.sub(r'-+', '-', url) # check whether the url is up or not parsedUrl = "http://www.tutorialbar.com/" + decodeUrl + "/" if requests.head(parsedUrl).status_code == 200: return parsedUrl urls = ['https://www.discudemy.com/all', 'https://www.discudemy.com/all/2'] for url in urls: source = requests.get(url).text soup = BeautifulSoup(source, 'html5lib') # print(soup) for content in soup.find_all('section', class_="card"): # print(content) try: language = content.label.text header = content.div.a.text day = content.find('span', class_="category").text i = content.find('div', class_="image") img = i.find('amp-img')['src'] image = img.replace('240x135', '750x422') description = content.find('div', class_="description").text.lstrip() myURL = getURL(header) udemyURL = requests.get(myURL).text udemySoup = BeautifulSoup(udemyURL, 'html5lib') udemylink = udemySoup.find_all('a', class_="btn_offer_block re_track_btn")[0]["href"] entry = { 'language': language, 'header': … -
Django modeltranslation TranslationOptions add external attribute to a model field
I have to add a unique=True attribute to the translated model fields, excluding the original field. E.x.: I have a model class News(models.Model): title = models.CharField(max_length=255) text = models.TextField() and I add such translation option: from modeltranslation.translator import translator, TranslationOptions from .models import News class NewsTranslationOptions(TranslationOptions): fields = ('title', 'text') translator.register(News, NewsTranslationOptions) My project setting file contains language settings: LANGUAGE_CODE = 'ru' gettext = lambda s: s LANGUAGES = [ ('ru', gettext('Russian')), ('en', gettext('US English')), ] MODELTRANSLATION_LANGUAGES = ('ru', 'en',) USE_I18N = True USE_L10N = True After applying migrations, I will get such fields in my news table in db: title, title_en, title_ru, text, text_en, text_ru, and I want to add a unique option to a fields title_en and title_ru, excluding title field. How can I do this without manual adding required attribute to a migration file? -
Celery task and mysql
I will try to simplify this question as much as possible. I have a django project that uses celery tasks for some async job. For simplicity, let's say I have an order. In task, I update the order from waiting to in progress. @task(bind=True) # pylint: disable=E1102 def mytask(self, id: str): """This is my custom task """ order = Order.objects.get(pk=id) order.status = IN_PROGRESS order.save() print(order.status) # This returns 'in progress' But after the task is done, it revers the state to waiting and I'm not sure why. Could be transaction isolation of MySQL, but what would be a way to do this most cleanly there?