Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In model my image field is showing blank even though I have inserted the image from html
In model my image field is showing blank even though I have inserted the image from html -
admin dashboard for ecommerce - react & django
I'm building an ecommerce app in react and django and I also have to build a a dashboard. What would be a good approach to build the dashboard? This dashboard will be used to upload products, see users and their enquiries and also if the order was successful and stuff like that. I've never done anything like this before so would love your suggestions. Edit: I'm asking if usually we build the dashboard from scratch or is there something else we use? -
Django serializer validate related serializer
I have two Django Model, one depend on another. I made serializers for them, but I don't understand how i'm supposed to link the serializer so one call the validation of the child. class Tree(Model): id = AutoField(primary_key=True, auto_created=True) class Leaf(Model): id = AutoField(primary_key=True, auto_created=True) tree= ForeignKey(Tree, on_delete=SET_NULL, db_column="etude") My serializers look like this class TreeSerializer(ModelSerializer): leafList = LeafSerializer(source="leaf_set", many=True) class Meta: model = Tree fields = [ "id", "leafList", ] def create(self, validated_data): leafs = validated_data.pop("leaf_set", []) instance = Tree.objects.create(**validated_data) for leaf in leafs : leaf.update({"tree": instance}) Leaf.objects.create(**leaf) class LeafSerializer(ModelSerializer): class Meta: model = Leaf fields = [ "id", "tree" ] def validate(self, attrs): return False But my LeafSerializer seems to never be called. All objects are properly created, but LeafSerializer's validate method is never run, thus don't prevent creation when a Leaf is invalid. I can't find in the django rest documentation instructions on how to do validation on related object. I've looked at django rest relations documentation but i'm not sure it is what i'm looking for. I'm thinking about explicitly creating a LeafSerializer inside the create function of TreeSerializer. I would be able to check the data, but i'm not sure if that's the right way … -
Automatic Time and Date Insertion
I want to automatically add the date and time information of that time to a certain field in the project I am doing. I am using Django, HTML, JavaScript in my project, how can I do it with any of them? -
How to send back the data to react frontend after callback from google OAuth in django?
I am working on an application with two parts as frontend and backend in react and django , I am using server side flow and using token authentication for login and authentication system with OAuth . When user clicks on the frontend on LOGIN WITH GOOGLE it is allowed to choose the email and login with the react server with port 3000 and the redirect url or callback url is my django backend with port 8080 and when it will be in production there will be an ip or domain for that . But now when i login with frontend , it goes to callback and sends all the data there . Now the thing is that after receiving the authorization_code , getting access_token and then data , the request resides in the backend code and the connection with the react frontend is completely broken . Now I don't understand how to send data back to the frontend with auth token and all other data. my views.py "http://localhost:8080/api/callback/" @api_view(["GET"]) def getCallBack(request , *args , **kwargs): if request.method == "GET" : data = { "scope" : request.GET.get("scope").strip().lstrip().rstrip() , "authuser" : request.GET.get("authuser").strip().lstrip().rstrip() , "prompt": request.GET.get("prompt").strip().lstrip().rstrip() , "code" : request.GET.get("code").strip().lstrip().rstrip() , "client_id" :"", … -
How to access ForeignKey properties from models.py in django
I want to access a property of another model from a model via ForeignKey. For example, if invoice_details is a ForeignKey to InvoiceMaster, then I want invoice_details to store the value of InvoiceMaster's invoice_number, instead of the primary key. How can I achieve this? I have tried the following: class OrderDetails(models.Model): purchase_order_number = models.IntegerField(blank=True, null=True) purchase_request_number = models.IntegerField(blank=True, null=True) delivery_no = models.IntegerField(blank=True, null=True) delivery_equipment = models.CharField(max_length=500, blank=True, null=True) delivery_quantity = models.IntegerField(blank=True, null=True) warranty_start_date = models.DateField() warranty_end_date = models.DateField() invoice_details = models.ForeignKey(InvoiceMaster, on_delete=models.CASCADE, blank=True, null=True).invoice_number vendor_id = models.ForeignKey(VendorDetails, on_delete=models.CASCADE, blank=True, null=True).vendor_id equipment_id = models.ForeignKey(EquipmentMaster, on_delete=models.CASCADE, blank=True, null=True).equipment_id is_visible = models.IntegerField(default=1) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) creation_date = models.DateTimeField(default=timezone.now) Check invoice_details - I've tried adding .invoice_number at the end of the ForeignKey. Adding .invoice_details to InvoiceMaster within the ForeignKey parentheses gave me the following error: TypeError: ForeignKey(<django.db.models.query_utils.DeferredAttribute object at 0x10d632fd0>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' Here is the InvoiceMaster module: class InvoiceMaster(models.Model): invoice_number = models.CharField(max_length=50, blank=True, null=True) equipment_name = models.ForeignKey(EquipmentMaster, on_delete=models.CASCADE, blank=True, null=True).name quantity = models.IntegerField(blank=True, null=True) is_visible = models.IntegerField(default=1) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) creation_date = models.DateTimeField(default=timezone.now) For some reason, although I have done the same … -
How can I use a module from npm in a django-admin widget, without installing node?
Background I have a django app that I want to create an admin widget for. The widget will display text in a particular way (like a terminal). It's so that app admins can see forwarded logs from an analytics process that is orchestrated by django (the app is django-twined). To do that I want to use something like terminal-kit or one of the other libraries requiring npm install <whatever> Building the app The app is built in docker, and I don't want the entire node stack to end up in my production image. I could use a multi-stage docker build; so install node and a lib from NPM in the first stage, then copy the library from node_modules in the second stage, but this feels unnecessarily slow. Also, because all I'm doing then is using the raw js static assets that get bundled with the django app, I'm not sure how to go about importing the module (or if this is even possible). The questions Can I install an npm module without having the node stack present, and therefore avoid dealing with unwieldy multi stage builds? How can I then import or require the contents of that module into vanilla … -
Key (id)=() is still referenced from table for onetoone field
I have 1 to 1 field in my model where i would still need to link the data with other while i delete them on the other table.In my view i am deleting model 2 instance while that is deleted i am setting the completed to Tue but it is throwing error. models.py class Model1(models.Model): model_2_attribute = models.OnetoOneField('Model2' on_delete=models.DO_NOTHING) completed = model.BooleanField(default=False) -
Can't import from views.py django
I have the following code in my views.py file. def home(request): fromDate = request.GET.get('fromDate', 'This is a default value') toDate = request.GET.get('toDate', 'This is a default value') I want to import fromDate and toDate from views.py to another file I created (countries.py), but every time I try to use from . import views I get the error. partially initialized module 'website.views' has no attribute 'toDate' (most likely due to a circular import) Even using from website import views # gives the same error Any help would be appreciated. -
3-way dependent drop down using javascript
I am trying a 3-way drop-down using javascript and Django. but the query works only for 2. can anyone help me with this? Here I am sharing the javascript code as well as HTML code. <div class="row"> <div class="col-md-4"> <select id = "s" > <option selected disabled = "true"></option> {% for it1 in item1 %} <option value ="{{it1.id}}">{{it1.Zone}}</option> {% endfor %} </select> <select id = "department" > <option selected disabled = "true"></option> {% for it1 in item2 %} <option value ="{{it1.id}}">{{it1.Circle}}</option> {% endfor %} </select> <select id = "Employee" > <option selected disabled = "true"></option> {% for it1 in item3 %} <option value ="{{it1.id}}">{{it1.Division}}</option> {% endfor %} </select> </div> <script> $(document).ready(function(){ var $s = $("#s"); var $department = $("#department"); var $Employee = $("#Employee"); var $options = $Employee.find('option'); var $option1 = $department.find('option'); $department.on('change',function(){ $Employee.html($options.filter('[value="'+ this.value +'"]')); }).trigger('change'); $s.on('change',function(){ $department.html($options.filter('[value="'+ this.value +'"]')); }).trigger('change'); }); -
how do I send direct parameter into django def?
How can I pass "g" as a direct value into def show-category? What should I write in href in a tag? How should I write related path? I have follow code in html, models and views and related path. <li><a class="dropdown-item" href="{% url 'category' %}" >Game</a></li> ...... class Listing_page (models.Model): winner = models.ForeignKey(User,on_delete=models.CASCADE,related_name='winner') urls= models.URLField(max_length=200000) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='urls') discription = models.CharField(max_length=280) title = models.CharField(max_length=64) open = models.BooleanField(default=True) price = models.IntegerField() item_category = [ ('g','Game'), ('t','technology'), ('l','learn') ] categori = models.CharField(choices=item_category,max_length=5000) def __str__(self) -> str: return f"{self.id}:{self.title}" ........ def show_category(requst, categorys): posts = Listing_page.objects.filter(categori=categorys, open=True) return render(requst, 'auctions/category.html', { "posts": posts }) ...... path("category/<str:categorys>",views.show_category,name="category"), -
Filling the model with sample images
models.py class Phrase(models.Model): image = models.ImageField(blank=True, default="", null=False, upload_to=UploadTo(folder=UPLOAD_TO.VOCABULARY_IMG_FOLDER).save_path) Script sample_img_dir = os.path.join(settings.BASE_DIR, 'doc', 'samples', 'img') sample_images = os.listdir(sample_img_dir) img = random.choice(sample_images) f = open(os.path.join(sample_img_dir, img)) sample_img = File(f) obj = Phrase( image=sample_img ) obj.save() I have a model with an ImageField. I want to fill it with sample data. This is not about testing. I just want to fill the database for development purposes. I saved some 50 jpg files and decided to add them programmatically. I failed miserably. This code blows up with the exception: File "/usr/lib/python3.8/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte python-BaseException Process finished with exit code 130 (interrupted by signal 2: SIGINT) Could you help me? -
django form live update based on another select
So i have this kind of form class AddressForm(forms.ModelForm): class Meta: model = Address fields = ( 'country', 'province', 'city', ) and this how i've done it in template <div class="form-group col-md-6 col-lg-6"> <label for="address_province2">province<span class="required-f">*</span></label> {{form.province}} </div> <div class="form-group col-md-6 col-lg-6"> <label for="address_province">city<span class="required-f">*</span></label> {{form.city}} </div> each city has foreign key to its own province. so i want to modify city options based on what user has selected from province. and they are all in the same page and form so i need this to be updated live. PS: if you think this can be done with ajax, I would really appreciate the full code. -
ArrayField including multiple DateTimeFields
I want to develop a django model, which includes ArrayField of DateTimeField as follows: from django.db import models from django.contrib.postgres.fields import ArrayField class Predictions(models.Model): timestamp = ArrayField(models.DateTimeField(auto_now_add=True, null=True)) ip = ArrayField(models.FloatField(blank=True, null=True)) ip_status = ArrayField(models.FloatField(blank=True, null=True)) The timestamp will be from now until 2 minutes later, namely something like {04/10/2022 09:30, 04/10/2022 09:31, 04/10/2022 09:32}. Is something like that feasible? -
Is it possible to allow a user to add data into a table of foreignkeys as opposed to primarykeys in Django?
Say I have 3 tables (or Python classes): Two tables contain primary keys and so are LOOKUP tables. Another table (say table X) contains both foreign keys from the first 2 tables along with some more primary keys. Is it possible to upload data directly into table X in Django? If so, would the primary keys automatically inherit these data values? -
Ask model field only in creating user not super user. (Django)
I am making a college - student contacting Django app. Question : I wanted my Django app to not ask for "roll_number" when creating a superuser which it does not, but I am still getting this error (the error is at the bottom) and I can't make it null or blank because I want it to be asked in the Django form for student registering. How do I do it? The code : model.py #accounts/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager from .manager import UserManager # AbstractUser can also be used because it already has some predefined model fields # and we can add more if we want to. class Account(AbstractBaseUser): # choices for department class Department(models.TextChoices): CSE = "COMPUTER SCIENCE" IT = "INFORMATION TECHNOLOGY" EE = "ELECTRIC ENGINEERING" CE = "CIVIL ENGINEERING" TE = "TEXTILE ENGINEERING" ME = "MECHANICAL ENGINEERING" OT = "OTHER" email = models.EmailField(max_length=100, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) roll_number = models.CharField(max_length=10, unique=True) department = models.CharField( max_length=30, choices=Department.choices, default=Department.OT, ) # required date_joined = models.DateTimeField(auto_now=True) last_login = models.DateTimeField(auto_now_add=True) is_admin = models.BooleanField(default=False) is_superadmin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD: str = "email" REQUIRED_FIELDS = ["first_name", "last_name", "department"] object = UserManager() … -
How can I copy all the hastags in clipboard using typescript which are also in django pagination?
Hi I was developing a project in Django front end I was using html5 and TypeScript it's looks like this Frondend My problem is that I have to implement copyAll button functionality , but when I do that I was getting only first 10 results not understand how to get all of that 60 results all together into clipboard . I tried different codes but none of them worked , I am very new to Typescript nothing helped , there was a stackoverflow post but that also did not helped because my problem is with pagination. the last code I was working with () => { let selectAll = document.getElementById("{{ i.id }}") as HTMLInputElement; let locationElements=document.getElementsByClassName("mainClass"); for(let i=0;i<locationElements.length;i++){ if(selectAll.checked && ((<HTMLInputElement> locationElements[i]).checked==false)){ } } } -
Remove data from postgres using html.Button
I created a generatable charts that saved in postgresql. And I added some buttons like a delete button for every charts. It look like this I use for loop to create the charts and append it. How can I use the delete button? I tried to create another callback, if I click the other delete button it's printing "None" but, if I click the last one it's printing "1". Is there another solution? If I clicked the delete button, get the value of dcc.input which is the ID from the postgresql and then call the charts model ChartsModels().objects.get(id=value of dccinput).delete() I'm open with any suggestion to improve my work. app.layout = html.Div(id='graphs', children=[ ]) @app.callback(Output('graphs', 'children'), Input('graphs', 'children')) def update_extend_traces_traceselect(child): app.layout = html.Div(id='graphs', children=[ ]) @app.callback(Output('graphs', 'children'), Input('graphs', 'children')) def update_extend_traces_traceselect(child): i = 0 for b in barData: fig = go.Figure() fig.add_trace( go.Bar( x=[d['value'] for d in y][0], y=newdatetime, name=barname[i], marker_color=barcolor[i], orientation=orientation[i], marker_line_color=markerlinecolor[i], marker_line_width=float(markerlinewidth[i]) )) else: fig = go.Figure() fig.add_trace( go.Bar( y=[d['value'] for d in y][0], x=newdatetime, name=barname[i], marker_color=barcolor[i], orientation=orientation[i], marker_line_color=markerlinecolor[i], marker_line_width=float(markerlinewidth[i]) )) fig.update_layout( # barmode=barmode[i], xaxis_title=xtitle[i], yaxis_title=ytitle[i], title=title[i], showlegend=ast.literal_eval(showlegend[i]), xaxis_showgrid=ast.literal_eval(showgrid[i]), yaxis_showgrid=ast.literal_eval(showgrid[i]), xaxis_showticklabels=ast.literal_eval(showticklabels[i]), yaxis_showticklabels=ast.literal_eval(showticklabels[i]) ) child.append(html.Div(id="div-id", children=[dcc.Input( id="charts-id", type="text", value=chart_ID[i] ), html.Button('EDIT', id='edit-chart', style={'margin': '5px'}), html.Button('Delete', id='delete-chart', n_clicks=0, style={'margin': '5px'}), … -
django forms don't show clear image button
I have a Django form modalform. There is an image field in it. The issue is that when the user clicks on the clear image, the image is removed from the models, but when the html file tries to retrieve the image, an error message appears The 'image' attribute has no file associated with it. So I'm planning to remove the clear button from django forms or is there any other best practises? -
I keep getting this Syntax Error running python manage.py runserver
I am using Django with Twitter API to make a Twitter app. I am running it using python3.7 and pip 22.0.4 in a python venv. I get this error when trying to run python manage.py runserver Traceback (most recent call last): File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/oauth_tokens/models.py", line 160 except (TokenRequestDenied, AccountLocked, LoginPasswordError, WrongAuthorizationResponseUrl), e: ^ SyntaxError: invalid syntax The only additions … -
I'm trying to create a login page in Django with remember me functionality and session management
after the cookie used to save the password has expired the signin functionality stops working can someone help me figureout the problem. If the run the code without the the cookie having an expiry time it works properly but not with.... i have showed the views.py file from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from accounts.models import userData from django.contrib import messages from django.db import connection # Create your views here. def signUp(request): if request.method == 'POST': if request.POST.get('username') and request.POST.get('passwd'): saverecord = userData() saverecord.username = request.POST['username'] saverecord.passwd = request.POST['passwd'] saverecord.save() messages.success(request, 'User Created......!') return redirect('signIn') else: return render(request, 'SignUp.html') def signIn(request): if request.COOKIES.get('cid'): return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid'],'cookie2': request.COOKIES['cid2']}) # if request.COOKIES.get('cid'): # return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid']}) # if request.COOKIES.get('cid2'): # return render(request, 'signIn.html', {'cookie2': request.COOKIES['cid2']}) if request.method == 'POST': if userData.objects.filter(username=request.POST.get('username'), passwd=request.POST.get('passwd')): request.session['uid'] = request.POST.get('username') # messages.success(request, "Login Successful...") if request.POST.get("chk"): response = HttpResponse("User Credentials") response.set_cookie('cid', request.POST['username']) response.set_cookie('cid2', request.POST['passwd']) # response.set_cookie('cid2', request.POST['passwd'], max_age=180) return response return redirect('index') else: messages.success(request, "Invalid User....") return render(request, 'SignIn.html') else: return render(request, 'SignIn.html') def index(request): if request.session.has_key('uid'): return render(request, 'index.html') else: return redirect('signIn') def signOut(request): del request.session['uid'] return render(request, 'signIn.html') -
Netsuite Customer statements
I am looking to send a customer statement from Netsuite to multiple email addresses that I have stored in a custom field in the customer record. Right now it will only send to the primary email on the customer record which can only be 1 email. Is there a way to send to multiple emails when generating the statement for a customer from the statements page? If not, is there a way around this? Thanks. -
Add custom field to admin fields
models.py class Video(models.Model ): embedded_code = models.TextField(blank=False, null=False, default='') This field represents youtube's embedded code. In the form for editing an instance I'd like to have a link to a detail view where I would like to show the video. In other words, I don't want to shoow the video in the admin site, I'd like just to create a link. And it is not about list_display. For that purpose in the model I could organise something like that: def preview(self): href = reverse('vocabulary-videos:detail', kwargs={'pk': self.id}) a = "<a href='{}'>Preview</a>".format(href) return mark_safe(a) Is it possible to show this link in the edit form without substituting the template? -
How to make DRF ordering and filtering work with custom query_params that generated by bootstrap-table extension
I have working version without api, filling table with loop in templates. Works as i need, but because there is thousands rows of data, page loading 5-20 seconds. So i want use server side pagination. Problem is - bootstrap-table script generates url like this for example: /api/parcels/?search=&sort=Size&order=desc&offset=0&limit=25&multiSort[0][sortName]=Price&multiSort[0][sortOrder]=asc&multiSort[1][sortName]=Region&multiSort[1][sortOrder]=asc bootstrap-table.js can sort by single column, also have extension for multiple column sort, and own pagination. Probably best way is to rewrite JS more into format of DRF. But i want do it opposite way, at least to get more experience with DRF. So, i know DRF have own ordering accodring docs: http://example.com/api/users?ordering=account,username ordering_fields = ['account', 'username'] and with ORDERING_PARAM you can change name for query param. But format offered by bootstrap-table.js not fits at all. So question is - is there a way to change DRF ordering according to my needs and which is better way? Just in case, my view and serializer so far. class ParcelViewSet(generics.ListAPIView): serializer_class = ParcelSerializer def get_queryset(self): queryset = Parcels.objects.all() return queryset def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response_data = { "total": len(serializer.data), "totalNotFiltered": len(serializer.data), 'rows': serializer.data } return Response(response_data) class ParcelSerializer(serializers.ModelSerializer): class Meta: model = Parcels fields = '__all__' -
Django Timer issue
I'm writing a Chess App with Django and Django Channels. The problem I have ran into is this: During the game, each time a player makes a move, the opponent's timer starts to count down. I've managed to achieve this using tasks. The issue is that each time the loop decrements the timer and broadcasts both timers to the clients, it calls the database and saves the current timer value to the model. That happens every second, and I've come to realize that it is a bad practice (saving to the database every second), and it's been causing me some bugs. My question is, what is the correct approach here? I want to keep track of the timers on the backend's side, so for example when it hits zero, I can stop the game, or when a player disconnects, the timer will keep on counting down. async def timer_handler(self, event): moving_color = event['text'] username = self.scope['user'].username consumer_color = self.game_obj.get_color(username) if consumer_color == moving_color: if self.timer_task != None: asyncio.Task.cancel(self.timer_task) self.timer_task = None elif consumer_color == self.opposite_color(moving_color): if self.timer_task == None: self.timer_task = asyncio.create_task(self.timer_countdown(self.opposite_color(moving_color))) else: try: raise Exception("Scheduled a timer task for a timer that's already running") finally: print('self.timer_task:', self.timer_task) async def …