Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django perpetual 404s when visiting project directory URL
I have a very strange problem with Django and OLS. I am using the OpenLitespeed Django one click install droplet on Digital Ocean. In both my custom app and the example app in the droplet, if I visit a URL that matches the django project directory (in the example app, this is /demo/), then any subsequent page visits give a 404 error, no matter what URL you do. To reproduce, I've spun up a completely clean install of the droplet, then do the following steps: Go to / -> see "Hello world!" as expected Go to /demo/ -> also see "Hello world!" even though this should be a 404, as this URL is not specified in the urls.py or anywhere else Go back to / -> 404! It seems to be looking for /demo/demo/ which doesn't exist Trying any other URL also results in a 404. The only way to get back to the normal behavior is to restart the OLS process. Everything then functions as expected unless any URL that starts with the project directory name is visited, in which case the whole thing crashes and returns 404s again. Any help that can be provided to try and further … -
Django file read error - Filename must be 1-8 alphanumeric characters
I am trying to temporary save a file in the os and read it to convert it into ZPL format. It is working fine in jupyter notebook but when I tried to run the same in Django function it is showing the following error: zplgrf.GRFException: Filename must be 1-8 alphanumeric characters Views.py for i in items: barcode = get_barcode(value=i, width=600) a = barcode.save(formats=['PNG'], fnRoot=i) print("a ",a) with open(a, 'rb') as image: grf = GRF.from_image(image.read(), str(i)) grf.optimise_barcodes() print(grf.to_zpl()) os.remove(a) zpl = grf.to_zpl() where items = ['YNT929951321', 'YNT929951322', 'YNT929951323', 'YNT929951324'] How can I resolve this ? -
Sending Payouts in django
Hello i am working on a 3d-model selling platform. I would like to add payout functionality without using Paypal. Anyone with an idea of a workaround; kindly advice. -
How can I submit 3 forms in tabs by click of one button in django?
I have 3 forms, first one collects user's personal information, second collects users educational information and the third one has a submit button along with checkbox. My forms.py class PersonalInfoForm(ModelForm): CHOICES = [('female','female'),('male','male')] enrolment = forms.IntegerField(widget=forms.HiddenInput) date_of_birth = forms.DateField(widget=DateInput) gender = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect) class Meta: model = Personal_Info fields = [ 'enrolment', 'first_name', 'middle_name', 'last_name', 'date_of_birth', 'gender', 'address' ] class EducationalInfoForm(ModelForm): username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Educational_Info fields = [ 'ssc_marks', 'ssc_percentage', 'ssc_board', 'hsc_marks', 'hsc_percentage', 'hsc_board', 'college_name', 'university', 'semester' ] class AgreeInfoForm(ModelForm): agree = forms.BooleanField() username = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = Agree_Info fields = [ 'agree' ] template named 'eligible-scholarships.html' <div class="row"> <div class="col-lg-12"> <div class="card"> <!-- open the below card body for the from --> <div class="card-body"> <h4 class="header-title mb-3"></h4> <ul class="nav nav-tabs nav-bordered nav-justified" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="personal-tab-b2" data-toggle="tab" href="#personal-b2" role="tab" aria-controls="personal-b2" aria-selected="true"> <span class="d-block d-sm-none"><i class="fa fa-personal"></i></span> <span class="d-none d-sm-block">Personal</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="educational-tab-b2" data-toggle="tab" href="#educational-b2" role="tab" aria-controls="educational-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-educational"></i></span> <span class="d-none d-sm-block">Educational</span> </a> </li> <li class="nav-item"> <a class="nav-link" id="complete-tab-b2" data-toggle="tab" href="#complete-b2" role="tab" aria-controls="complete-b2" aria-selected="false"> <span class="d-block d-sm-none"><i class="fa fa-complete"></i></span> <span class="d-none d-sm-block">Complete</span> </a> </li> </ul> <div class="tab-content"> <div class="tab-pane show active" id="personal-b2" role="tabpanel" aria-labelledby="personal-tab-b2"> … -
Query to get maximum x in django
My database: id | user_id | fat_intake | item_id 38 1 10 12 39 1 15 11 40 1 30 10 41 1 14 13 42 2 20 11 43 2 30 10 44 2 50 13 What will be the query to get user_id with the maximum fat intake till, i.e the response should be : Output: - Response Code: 200 - { "user_id": 1, "total_fat_count": 46 } -
Error runnning django channels server on localhost
I am following along on this tutorial: https://codyparker.com/django-channels-with-react/2/ and am getting this strange error: File "~/.local/lib/python3.6/site-packages/channels/management/commands/runserver.py", line 83, in inner_run ws_protocols=getattr(settings, 'CHANNELS_WS_PROTOCOLS', None), TypeError: init() got an unexpected keyword argument 'channel_layer' I am a total beginner with django and channels, and have no idea what could be causing the issue. The command I am running is: python3 manage.py runserver 8080 I am using the same versions of django and channels as the tutorial, channels 0.17.2 and django 1.9 Thank you for your help! -
How to map docker connect's to localhost to machine's localhost
I have a Django project which needs to be containerized for deployment. Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev gcc -y COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /eitan_app WORKDIR /eitan_app COPY . /eitan_app EXPOSE 8000 RUN python manage.py makemigrations RUN python manage.py migrate # RUN python manage.py runserver 127.0.0.1:8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I am able to create an image with the command docker build . and then docker run <image id> to run Django application. Once I run this image I get this output - System check identified no issues (0 silenced). March 17, 2020 - 05:40:04 Django version 3.0, using settings 'eitan.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. We can see the Django application has started perfectly fine inside the container but I am not able to access it from my machine's 127.0.0.1:8000. -
How to autodeploy Django in EC2 and React in S3
I have an app created in Django and React, but there are few problems that I am facing :- As I will have a large database(postgres) exclusily for a single user, I am creating different AWS EC2 instance for every user. Whenever there is a new user then I have to go and manually install postgres, setup nginx and other important things and this is just for Django in EC2. Then I setup ReactJS frontend in Amazon S3. How can i automate this so that when a paid user signs up, everything happens automatically. The following should happen automatically: - Automatically create a new EC2 instance, and deploy backend (This including installing several libraries, Postgres, Redis, async task queue (We use Huey which is like Celery), making migrations and other trivial stuff) - Automatically make an S3 bucket and deploy frontend for the user. We will have to setup domains .etc for this. Would like to know your inputs on how to approach this problem. -
django throws 'Direct assignment to the forward side of a many-to-many set is prohibited
while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my models class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True) user_name=models.CharField(max_length=10,blank=True,null=True,unique=True) date_of_birth=models.DateField(null=True,blank=True) mobile_number=models.CharField(max_length=20,blank=True,null=True) address=models.CharField(max_length=100,blank=True,null=True) country=models.CharField(max_length=20,blank=True,null=True) joining_date=models.DateField(null=True,blank=True) Rating_CHOICES = ( (1, 'Poor'), (2, 'Average'), (3, 'Good'), (4, 'Very Good'), (5, 'Excellent') ) Rating=models.IntegerField(choices=Rating_CHOICES,default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] def __str__(self): return str(self.user_name) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Meta: ordering=('user_name',) class Session(models.Model): Host=models.ForeignKey(MyUser,on_delete=models.CASCADE,related_name='host') game=( ('cricket','cricket'), ('football','football'), ('basketball','basketball'), ('hockey','hockey'), ('gym','gym'), ('baseball','baseball'), ) Sport=models.CharField(max_length=20,choices=game) SPORT=( ('Indoor','Indoor'), ('Outdoor','Outdoor'), ) Sports_category=models.CharField(max_length=10,choices=SPORT) SESSIONS=( ('General','General'), ('Business','Business'), ) Session_category=models.CharField(max_length=15,choices=SESSIONS) TYPE=( ('Paid','Paid'), ('Free','Free'), ) Session_type=models.CharField(max_length=10,choices=TYPE) Created=models.DateField(null=True,blank=True) Session_Date=models.DateField(null=True,blank=True) Location=models.ForeignKey(MyUser,related_name='street',on_delete=models.CASCADE) Player=models.CharField(max_length=100,blank=False) Start_time=models.TimeField(auto_now=False, auto_now_add=False) End_time=models.TimeField(auto_now=False, auto_now_add=False) Duration=models.DurationField() status=( ('1','Active'), ('2','UnActive'), ) Status=models.CharField(max_length=20,choices=status) Equipment=models.TextField() Duration=models.CharField(max_length=20,blank=False) #Level=models.ForeignKey(IntrestedIn,blank=True,on_delete=models.CASCADE) GENDER=( ('Male','Male'), ('Female','Female'), ('Male and Female','Male and Female'), ('Other','Other'), ) Gender=models.CharField(max_length=20,choices=GENDER ,blank=True) Fee=models.CharField(max_length=50,blank=True,default='0') User_Id=models.CharField(max_length=10,blank=True,null=True) Players_Participating=models.ManyToManyField(MyUser,related_name='related') def __str__(self): return str(self.Host) class Meta: ordering=('Host',) while posting data from the postman i am getting this error(Django throws 'Direct assignment to the forward side of a many-to-many set is prohibited.' error) my viewset class SessionViewSet(viewsets.ViewSet): def create(self, request): try: Host= request.data.get('Host') Sport = request.data.get('Sport') … -
How to used python filter json string based on key that given in array form?
I have below json string: a={"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "7":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "6":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"0A", } } } ], } The key from above json string get by a.keys() is: dict_keys(['44', '49', '7']) How to filter the a so that it remain the key of 44 and 49 only if the array given is ['44', '49'], below is my expected output: {"44":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], "49":[ { "16":{ "unitData":[ ], "unitHeader":{ "t9u":"P3P34", "sum":"807", } } }, { "17":{ "unitData":[ ], "unitHeader":{ "t9u":"BFB", "sum":"8A", } } } ], } -
Can you please guide me to implement Dual Factor Authentication in Django?
I am currently working on a scenario where a user after login has the option to switch to private mode by means of flipping a switch button. Whenever a user logs in and then switches on to private mode for the first time, then the user must be verified by dual factor authentication once and then he can switch back and forth between private and public mode, without triggering 2FA Authentication every subsequent time when he switches to private mode till he logs out. That is the 2FA must be triggered every first time per session when a user switches to private mode. Can you please provide some suggestions or ideas on how to implement this functionality? I am not clear on how to implement this. I have tried reading documentations and feel that a concise approach would be better. Please do suggest. -
Using commas to separate large numbers in Django FloatField
I'm setting up an app with Django and I need to show large numbers (sometimes many billions) on my home page. Right now I have set up my model with a classic: required_number = models.FloatField() Which yields me a number similar to 126645602100.0. Naturally I find this very hard to read, and it becomes really problematic to compare this number to another one which would be in the order of millions instead of billions. Would there be a way to format this number in order to get something like 126,645,602,100 or even 126'645'602'100? I'm thinking maybe FloatField is not adequate, or maybe the answer lies in my html treatment of this variable. Thank you very much for your help! -
FileField PDF Won't Open Django
I am creating and saving a PDF as such in my views: views.py @login_required(login_url="/login") def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): if 'preview' in request.POST: ... elif 'save' in request.POST: pdf_contents = form file = ContentFile(pdf_contents) item = PackingListDocuments.objects.get(pk=1) item.PackingListDocument.save('test.pdf', file) #saving as FileField in model form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') I see that the test.pdf is saved. I can see it in my file explorer as well as in the admin, but every time that I attempt to open it, the file seems to be corrupted. What do I need to add or subtract in my code to get this working? Thanks! -
Django without Page Refresh using AJAX
When the teacher update the student behavior, There is a pop up message "Update Success", in my case when the teacher update the student behavior the page is appear blank this is the source https://www.youtube.com/watch?v=KgnPSmrQrXI <form method="POST" id="DogForm" action="/Updatestudentbehavior/" class="myform" style="width: 100%" enctype="multipart/form-data">{% csrf_token %} <table class="tblcore"> <input type="text" value="{{teacher}}" name="teacher" id="teacher"> {% for students in student %} <tr> <td colspan="2"><input type="hidden" value="{{students.id}}" >{{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Lastname}} {{students.Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Students_Enrollment_Records__Student_Users__Firstname}}</td> {% for corevalues in studentsbehaviorgrade %} <td colspan="4"> <input type="hidden" value="{{corevalues.id}}" name="id" id="student"> <select name="Marking" id="marking"> <option value="{{corevalues.Marking.id}}" >{{corevalues.Marking.id}}-{{corevalues.Marking.Marking}}</option> {% for behaviors in behavior %} <option value="{{behaviors.id}}">{{behaviors.id}}-{{behaviors.Marking}}</option> {% endfor %} </select> </td> {% endfor %} </tr> {% endfor %} </table> <input type="submit" value="Update"> </form> this is my script <script type="text/javascript"> $(document).on('submit', '#DogForm', function(e)){ e.preventDefault(); $.ajax({ type:'POST', url:'/Updatestudentbehavior/' data:{ teacher:$('#teacher').val(), student:$('#student').val(), marking:$('#marking').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, succes:function(){ alert('Update Success'); } }) } </script> my views.py def Updatestudentbehavior(request): ..... return HttpResponse('') urls.py path('Updatestudentbehavior/', Homepage.views.Updatestudentbehavior, name='Updatestudentbehavior'), -
Automatically assigning User token to custom profile model django rest framework
I currently have a signal that automatically creates a Token object for a User when they sign up to the website. I also have a custom User model, UserProfileInfo, in which I have a field that connects a Token to the User token = models.OneToOneField(Token,related_name='token',on_delete=models.CASCADE,blank=True,null=True) However, I want this to be automatically assigned when the userprofileinfo is created, which happens in a signal. @receiver(post_save, sender=User) def create_auth_token(sender, instance, created, **kwargs): if created: token = Token.objects.create(user=instance) UserProfileInfo @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: UserProfileInfo.objects.create(user=instance) else: instance.userprofileinfo.save() (the first signal creates a token, the second creates the userprofileinfo) I want to know how I can automatically assign a token to a user when the userprofileinfo is created. -
Django ModelAdmin use custom query
Hi currently i'm having trouble add a custom ModelAdmin section to the app admin side without using any defined model in the models.py For example i have 3 models(topups, withdrawals, transfers) and i would like to add a separate ModelAdmin transactions section that a combination from those 3 model, because i like it's paging, change listing and detail view. So if i have a query for example like so: cursor = connection.cursor() cursor.execute(''' SELECT * FROM (SELECT id, user_id, 1 AS transaction_type, method, NULL AS to_bank, NULL AS to_address, user_id AS to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(received) AS confirmed FROM topups WHERE deleted IS NULL UNION ALL SELECT id, user_id, 2 AS transaction_type, method, NULL AS to_bank, to_address, to_account, NULL AS to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM transfers WHERE deleted IS NULL UNION ALL SELECT id, user_id, 3 AS transaction_type, method, to_bank, to_address, NULL AS to_account, to_card, currency_id, amount, fee, status, UNIX_TIMESTAMP(created) AS created, UNIX_TIMESTAMP(confirmed) AS confirmed FROM withdrawals WHERE deleted IS NULL ) AS T WHERE (user_id =''' + str(user.id) + ''' OR to_account =''' + str(user.id) + ''') ORDER BY created DESC''' ) row = namedtuplefetchall(cursor) … -
need help separating a Django function into 2 distinct parts
I'm continuing to make progress on a personal cycling data website. What I'm currently working on is trying to take a function which, at the moment, is run all at once, and turn it into two separate pieces. I'm pulling data from Strava via their API, and what I hope to do is first, via a button, pull and display a list of recent rides (this part is accomplished) and then once that list is displayed select an individual ride to import. At the moment, it's a bit of an all or nothing scenario where I can extract all ride files at once but I wanted to do it more "on-demand" So what I'm hoping to do is get the portion which collects the streams and make that into it's own function that can receive data from this first rendering function and call upon a single ride stream to add to a model/file/whatever. Just curious to see if someone had any insight on what stuff to explore def stravadownload(request): adict={} actdict={} activitydict={} if "downstrav" in request.POST: client = Client() activity=Activity() with open("stravtoken.json", "r") as stravtoken: tokendict = json.load(stravtoken) access_token = tokendict["access_token"] refresh_token = tokendict["refresh_token"] expires_at = tokendict['expires_at'] client.access_token=access_token client.refresh_access_token= refresh_token … -
Failed to push an app in heroku with python
im trying to deploying an app with python django.. But when i get this error: From my build log in heroku.. -----> Python app detected .... -----> Installing requirements with pip ... Collecting psycopg2==2.6.2 Downloading psycopg2-2.6.2.tar.gz (376 kB) ERROR: Command errored out with exit status 1: command: /app/.heroku/python/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-a0nakbaj/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-a0nakbaj/psycopg2/pip-egg-info cwd: /tmp/pip-install-a0nakbaj/psycopg2/ Complete output (7 lines): ..... Error: could not determine PostgreSQL version from '12.2' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed Here is my requeriments.txt if you need it: colorama==0.4.1 dj-database-url==0.5.0 Django==2.2.1 django-qr-code==1.0.0 gunicorn==19.9.0 Pillow==6.0.0 psycopg2==2.6.2 pytz==2019.1 qrcode==6.1 six==1.12.0 sqlparse==0.3.0 whitenoise==4.1.2 Anyone can help me with whis? Thank you! -
Django: no module named "django_haystack" but here it is, I think
pip3 install django-haystack ... comfortingly says: Successfully installed django-haystack-2.8.1 But then `./manage.py migrate' ... says ModuleNotFoundError: No module named 'django-haystack' In my .virtualenvs/[...]/ I find these directories: django_haystack-2.8.1-py3.6.egg-info haystack ... but pip3 uninstall haystack says Skipping haystack as it is not installed. ... and pip3 uninstall django-haystack is ready to delete the directories aforementioned. Okay, so if pip3 install finds it, what's migrates problem? My INSTALLED_APPS hash includes django-haystack ... -
Multiple database router
The project is about two databases, the first one: default (which I've been working and contains several models) and the second one: customer (it must handle only 1 model). App name: cities Database's names: default and customer Model in customer's db: mail_receiver I've been following some Django's manuals but it doesn't work. The routers that I'm using are: routers.py class defaultRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'cities': return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'cities': return db == 'default' return None class customerRouter(object): def db_for_read(self, model, **hints): """ Attempts to read user models go to default. """ if model == 'mail_receiver': return 'customer' return None def db_for_write(self, model, **hints): if model == 'mail_receiver': return 'customer' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'cities' or \ obj2._meta.app_label == 'cities': return True return None def allow_migrate(self, db, app_label, model_name='mail_receiver', **hints): if app_label == 'cities': return db == 'customer' return None settings.py DATABASES = { 'default': { 'NAME':'cities', 'USER': 'root', ... }, … -
Django - model with several tag fields
I need a model with several "tag" fields. For example: class Food(models.Model): type = SomeTagField() manufacturer = SomeTagField() It could be done using many-to-many relationships, but I'm not sure if this is a correct approach. It looks a little bit overcomplicated. I've tried django-tagit and its TaggableManager but without luck: ValueError: You can't have two TaggableManagers with the same through model. What would be a correct way to handle that? -
Django sqlmigrate not showing raw sql
I tried to get the raw sql from Django migrate file. I took the following steps: $ python manage.py makemigrations $ python manage.py sqlmigrate app_name 0001 and raw sql command should display, but the result only contains: BEGIN; -- -- Create model User -- -- -- Create model Config -- COMMIT; How to get the raw sql from sqlmigrate? -
Call function when call another function
I want to call some function from django view. Class view(view): Def get(self): Some stuff... Return httpresponse Def a(): Some stuff I want to call a() function when view is called, without calling a() in view body. Maybe there is any decorator or something else, which helps me with it. Something like: Class view(view): Def get(self): Some stuff from view Return httpresponse @call_with_view Def a(): Some stuff from a >> View() >> some stuff from view >> Some stuff from a -
Django Rest Framework: Custom Forms, Custom JSON output
I have to use Django Rest Framework to develop a form that accepts 2 inputs, customer ID and seat number, and this form is to be limited to 10 customers. My Output JSON should have customer ID, seat number, customer_occupancy (which is 2*customer_id) and total customer occupancy (which is sum of all customer_occupancy values entered up until that point). I've added my code for models.py and views.py down below. I have no idea how to ensure the form doesn't have more than one field for which value is to be entered (seat number) nor why the queryset.update() is not resulting in any change in the output. Any help to resolve this would be much appreciated. models.py: from django.db import models class Hero(models.Model): seat_number = models.CharField(max_length=160, default='No Comment') customer_occupancy = models.IntegerField(default = 0) total_cust_occupancy = models.IntegerField(default = 0) def __int__(self): return self.id views.py: from django.shortcuts import render from rest_framework import viewsets from .serializers import HeroSerializer from .models import Hero global total total = 0 class HeroViewSet(viewsets.ModelViewSet): global total queryset = Hero.objects.all().order_by('id') for idx, i in enumerate(queryset): queryset[idx].customer_occupancy = 2*int(queryset[idx].id) total += queryset[idx].customer_occupancy queryset[idx].total_customer_occupancy = total print(queryset[idx].customer_occupancy) print(total) print(queryset[idx].total_customer_occupancy) queryset.update() serializer_class = HeroSerializer serializers.py: from rest_framework import serializers from .models import Hero … -
Whats the most performant way to reverse a lookup on a dict of tuples?
I have a choices field, with a list of tuples: EVENT_CHOICES = [(1, "queued"), (2, "sent"), (3, "failed")] This is stored as a PositiveSmallIntegerField rather than a CharField for performant reasons: event_type = models.PositiveSmallIntegerField(choices=EVENT_TYPE_CHOICES) In my app, the field is populated by a webhook to an external source, which POSTS the str component of the tuple. E.g. I receive queued, sent, or failed as a POST variable. What's the easiest/most performant way to reverse a lookup on EVENT_CHOICES to return the int from the str? E.g, a clumsy long form way would be: if event == "queued": event_type = 1 if event == "sent": event_type = 2 if event == "failed": event_type = 3 Given I actually have a lot of choices, I assume there has to be a neater way for this?