Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connection.commit() does not persist data in Django Test
I am attempting to test if my db_insert() method works. def db_insert(data, insert_query, limit=100): """Persist data to database :param data: Tuple of tuples :param insert_query: String :param limit: Integer """ # Insert / Merge cursor = conn.cursor() try: for i in range(0, int(len(data) / limit) + 1): sliced_data = data[i * limit:i * limit + limit] if sliced_data: cursor.executemany(insert_query, sliced_data) conn.commit() except Exception as e: conn.rollback() raise DBException('ScriptName:db_manager.py,ErrorType:{}Impact:Unable to insert into database,' 'ErrorMessage:{}'.format(type(e).__name__, e)) This method is called by another method: def insert(cls, new_list): """Insert new data to DB :param new_list: List """ try: insert_query = "insert into TABLE {} values {}" \ .format(tuple(cls.TABLE_ATTR[1:]), ('%s',) * len(cls.TABLE_ATTR[1:])) insert_query = insert_query.replace('\'', '') db_insert(new_list, insert_query) except Exception as e: logger.exception(e) Lastly, the insert() method is invoked in the test case: def test_insert_new_host_iqn_mapping(self): SomeModule.insert(['text1', 'text2', 'text3', 1, settings.SCRIPT_RUN_TIME]) cursor = conn.cursor() cursor.execute("select * from TABLE") data = cursor.fetchall() print(data) # [1] The output in [1] does return 2 tuples. These tuples however are data that have been added into the DB using django models.save() in the setUp(). Can someone show me why the conn.commit() is not persisting the data into the database as expected in a real run? -
Create a model instance with InlinePanel
do you have any idea how can I create an instance of the model by using InlinePanel I do not want to add an existing already one instance but I want to create a new one along with the ParentalKey in my case, the ParentalKey is the family and the person is the ForeignKey @register_snippet class Family(ClusterableModel): title = models.CharField(verbose_name=_("family title"), max_length=100) panels = Page.content_panels + [ InlinePanel("persons", label=_("Persons")), ] class FamilyPerson(Orderable): person = models.ForeignKey("crm.Person", on_delete=models.CASCADE) family = ParentalKey( "crm.Family", on_delete=models.CASCADE, related_name="persons" ) @register_snippet class Person(models.Model): SEX_CHOICES = [("M", _("Male")), ("F", _("Female"))] title = models.CharField(verbose_name=_("person title"), max_length=100) age = models.PositiveIntegerField( verbose_name=_("age") ) sex = models.CharField( max_length=12, choices=SEX_CHOICES ) -
How to solve the ConnectionRefusedError: [WinError 10061] the target machine actively refused it? (Django SMTP)
I have read many solution tried to implement but no luck.Please suggest to fix this issue and below are the things implemented in my code. values passed in .env [EMAIL] IP = 10.29.15.9 PORT = 25 FROM = x@y.com In settings.py file import configparser config = configparser.ConfigParser() config.read_file(open(r'.env')) In views.py file s = smtplib.SMTP('10.29.15.65', '25') print("printing s dict",s.__dict__) s.ehlo() #s.sendmail(config.get('EMAIL', 'FROM'), to_email.email, msg.as_string()) s.sendmail("a@b.com", 'c@d.com', msg.as_string()) print("printing the S object", s.__dict__) s.quit() Output I am getting: Using windows platform, i don't have admin rights, Firewall is disabled. -
clusterize.js with django; static files not found
I am trying to use the https://clusterize.js.org/ javascript package with my Django website for displaying extremely large tables neatly and speedily. I downloaded the package's necessary js and css files, and referenced them in the html getting loaded when i visit my site's url: mysite.com/popularify <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <link href="/static/js/clusterize.css" rel="stylesheet"> <script src="/static/js/clusterize.min.js"></script> </head> And ensured that I have the two files in that location, but am getting these errs in console when I run the site: My settings.py Django file has : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] -
Django HTMLCalendar Previous and Next Month won't show
I am quite new to Django and am currently building an app to display a calendar using Django. I've been following the tutorial here but I can't make the previous and next month button to work. When I go to http://127.0.0.1:8000/calendar I can see this month's calendar, but when I press previous / next month nothing happens, only the url changes to http://127.0.0.1:8000/calendar/?month=[this_year]-[this_month+/-1] Here is my View Class: class CalendarView(generic.ListView): model = Event template_name = 'calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) d_obj = get_date(self.request.GET.get('day', None)) cal = Calendar(d_obj.year, d_obj.month) html_cal = cal.formatmonth(withyear=True) context['calendar'] = mark_safe(html_cal) d_obj = get_date(self.request.GET.get('month', None)) context['prev_month'] = prev_month(d_obj) context['next_month'] = next_month(d_obj) return context def get_date(req_day): if req_day: year, month = (int(x) for x in req_day.split('-')) return datetime(year, month, day=1) return datetime.today() def prev_month(d_obj): first = d_obj.replace(day=1) prev_month = first - timedelta(days=1) month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month) return month def next_month(d_obj): days_in_month = calendar.monthrange(d_obj.year, d_obj.month)[1] last = d_obj.replace(day=days_in_month) next_month = last + timedelta(days=1) month = 'month=' + str(next_month.year) + '-' + str(next_month.month) return month I'm using Django 2.2 so I did a few changes to the urls: urlpatterns = [ path('calendar/', views.CalendarView.as_view(), name='calendar') ] And this is the body part of the … -
Loading Data from an external API into Django models advice
This is more of a design than technical question. What i am doing is trying to present external API data to a user in the form of a table. The data is a list of products (description, price, etc). The user can select the products that they would like to buy from the table (i.e: select the rows in the table) and then proceed to the next page where a table of only the products they have selected is show. (its almost like an ecommerce cart but instead of adding items one-by-one, multiple items can be added at once. ) The API of available products is always changing and growing as new products are added, also the products are one-offs, as in there is only 1 of them and a second user can not select a product once somebody else has chosen it. At the moment i can do this, however it is all on the client side because i am using Ajax to pass the JSON object straight into the html table. From there I use Jquery and javascript to select the table rows by class toggling and complete the process. (It is very 'hacky'). However, doing it this … -
How to set up logging in Elastic Beanstalk for Django app?
I can't get logging to work on my Django app, running on Elastic Beanstalk. Settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "verbose": {"format": "%(asctime)s %(levelname)s %(module)s: %(message)s"} }, "handlers": { "django": { "level": "INFO", "class": "logging.FileHandler", "filename": "/opt/python/log/django.log", "formatter": "verbose", } }, "loggers": { "django": {"handlers": ["django"], "level": "INFO", "propagate": True} }, } If I change log level to DEBUG, there will be lots of action in the logs, but still it won't contain logger.info() or logger.debug() calls. .ebextensions/logging.config: commands: 01_create_file: command: touch /opt/python/log/django.log 02_change_permissions: command: chmod g+s /opt/python/log/django.log 03_change_owner: command: chown wsgi:wsgi /opt/python/log/django.log How I use the logging: import logging logger = logging.getLogger("django") logger.info("Testing") When I run the app locally, logs are successfully sent to console using the following setup: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, } -
Elastic Beanstalk doesn't deliver all environment variables to application
I'm running a Django app on Elastic Beanstalk. Previous version of my app had 11 environment variables in Elastic Beanstalk and worked fine. Latest version requires two more. I have spent several hours wondering why the app doesn't work anymore, before noticing that two environment variables do not exist in os.environ! One of the missing variables is a new variable added today, and the other one worked earlier. Second new variable can be found in os.environ. Length of the variables don't come close to the maximum of 4 KB. How is this possible? -
I want to pass json data from my template to my view
I am trying to pass a JSON object from a JavaScript function to a django view. I am a beginner in django and do not have any idea how to do this. in the template create_proposal.html I have a javascript function called convertToJson that looks like: function convertToJson() { console.log("convert"); var obj = $(".input-form").serializeToJSON({ }); var jsonString = JSON.stringify(obj); } and in my views.py file the function i am trying to receive the json object looks like: def resultPage(request): return render(request, 'result.html') I am trying to pass the jsonString variable in the javascript function to the python function resultPage in the views.py. Thanks in advance. -
How to connect MongoDB with django?
Hello i am using mysql as my primery database in Django but now i want to use MangoDB as my database. I want to know how to connect MongoDB in Django. -
'authapp' is not a registered namespace
Error Message 'authapp' is not a registered namespace I created Django an app in DJango and named it authapp. Root app name is practise 1 and inner app name is authapp. Below is the directory structure. Settings file code INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authapp' ] Inside the inner app, the views.py code is below. from django.shortcuts import render def login(request): if(request.method == "POST"): return render(request, 'login1.html') else: return render(request, 'login.html') Below is the code in login template inside authapp. <form method="post" action="{% url 'authapp:login' %}"> {% csrf_token %} <input type="text" name="email" class="form-control"> <input type="password" name="password" class="form-control"> <button type="submit" class="btn btn-primary"> Login </button> </form> Am I missing anything? Edit 1 Below is code in urls.py from django.contrib import admin from django.urls import path, include from .import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('authapp.urls')), path('', views.home) ] -
Unable to access "uwsgi" gateway in Docker
I want to deploy a Django project in Kubernetes. Right now I'm creating a docker image to understand the project. Dockerfile FROM python:3.7 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip3 install -r requirements.txt docker-compose.yml version: '3' services: mysql: image: mysql:5.7 volumes: - ./mysql:/var/lib/mysql expose: - "3306" restart: always environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=nlpapp - MYSQL_USER=root - MYSQL_PASSWORD=root nginx: image: nginx:alpine volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf - ./nginx/conf:/etc/nginx/conf.d - ./web/staticfiles:/django_static ports: - "80:80" depends_on: - web redis: image: redis:alpine expose: - "6379" restart: always web: build: . command: uwsgi --ini uwsgi.ini working_dir: /code/blog volumes: - .:/code expose: - "8000" depends_on: - mysql - redis celery: build: . command: celery -A blog worker -l info working_dir: /code/blog volumes: - .:/code depends_on: - mysql - redis uwsgi.ini [uwsgi] socket=:8000 chdir=/code/blog module=blog.wsgi:application pidfile=/tmp/blog-master.pid master=True vacuum=True processes=1 max-requests=5000 These are the main files. when I'm going to start docker-compose up command on that time MySQL, Redis, nginx, celery containers are working properly but WSGI(web) container is not running and showing an error. ERROR: for web Cannot start service web: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"uwsgi\": executable file not found in $PATH": unknown ERROR: Encountered errors while bringing up the … -
Use a loader till the page fully loads in Django GET call
I have a URL which fetches some large collection of data and shows in the front django template , but some times loading this data takes a lot of time, so i need to a show a loader till the page completely loads. I can see many solutions related to this questions, but all of them are handling POST call, but in my case its a GET call, For example, URL: /students/list/ class ListRecords(View): """ This class is used to list all the students record """ def __init__(self): self.data = self.get_records() def get(self, request, *args, **kwargs): return render(request, 'list.html', {'data': data_obj}) So how can i show a loader till the page completely loads in list.html, is there any effective and easy way to implement the same. Any help would be greatly appreciated. Thank you.. -
Hosting django on aks behind nginx-ingress
I am trying to host a django website on Azure kubernetes service behide nginx-ingress, and I would like my django web show under a path. e.g. when access the default admin site, I would like to access it at http://example.com/django/admin instead of http://example.com/admin I tried the configure below, when I access http://example.com/django/admin it will forward me to http://example.com/admin and show me 404 error from default ingress backend, as I set django debug to ture I assume this mean ingress did not send my request to my django service apiVersion: extensions/v1beta1 kind: Ingress metadata: name: django-ingress labels: app: django namespace: default annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/rewrite-target: /$2 spec: rules: - http: paths: - backend: serviceName: django-service servicePort: 80 path: /django(/|$)(.*) so I try to curl -I -k http://example.com/django/admin, and it show something like below HTTP/1.1 301 Moved Permanently Server: openresty/1.15.8.2 Date: Wed, 06 Nov 2019 04:14:14 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive Location: /admin/ The same thing happen to any valid page in the site, if I curl -I -k http://example.com/django/any_valid_page it show below: HTTP/1.1 301 Moved Permanently Server: openresty/1.15.8.2 Date: Wed, 06 Nov 2019 04:14:14 GMT Content-Type: text/html; charset=utf-8 Content-Length: 0 Connection: keep-alive Location: /any_valid_page/ I wonder … -
Django loop all existing record to save but only one record save
this is my code in html <tr> <td colspan="2" style="text-align: center;"> <h2 style="font-weight: bold;">Required Documents:</h2> </td> </tr> {% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile-{{d.id}}" value="{{d.id}}" style="outline: none;" required/> {{d.id}}{{d.Description}} </td> <td></td> </tr> {% endfor %} views.py def enrollmentform(request): id = request.GET.get('StudentID') students = StudentProfile.objects.all().filter(id=id) doc = DocumentRequirement.objects.all().filter() return render(request, 'accounts/EnrollmentForm.html', {"doc": doc}) this is my logic on how to save my record myfile = request.FILES['myfile-6'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel, School_Year=schoolyear ) insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() I don't have idea on how to loop this myfile = request.FILES['myfile-6'] with the existing id of Table Documents. please help me guys, im stuck on this problem 3days for example if the student comply the 4 required documents it will save like this correct in my case it save only 1 record, wrong saving -
Showing model entries as a form in a table
I have a model which has data that i need to show to a user in the form of a table. The user can select rows in the table and then proceed to the next page with only those items. I think the way to do this with django is to crate a table where every row is a form, when a user clicks on a row it updates the status of that entry in the table to be "Selected" and when the user proceeds to next page, a new queryset with only entries with a status of "Selected" are shown. Does this make sense? Or is there a better way to achieve this? -
How could I retrieve data from mysql in django to be shown in a modal wherein I could also update it?
What I needed to do is after clicking the view modal button, it will show the information and then there is a button also wherein could update it. Models.py class Employee(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) last_name = models.CharField(max_length=100, blank=True, null=True) middle_name = models.CharField(max_length=100, blank=True, null=True) userid = models.CharField(max_length=45, blank=True, null=True) email_address = models.CharField(max_length=100, blank=True, null=True) I dont have views.py yet( Dont know where to start) MySQL DB -
Deploying Django-Channels app to Heroku with Daphne
I am trying to deploy a Django channels app to Heroku using daphne but cannot find a configuration that works with up-to-date dependencies. I did my initial config with the channels documentation (https://channels.readthedocs.io/en/latest/deploying.html) and have got the application running locally via daphne. I think the issue is probably with my ProcFile config and some missing component for serving the page in production. I have tried a number of configurations, but am limited to one web server and one worker via Heroku's free option. I am not sure if this application will work in deployment configured as ASGI ("daphne chatproject.asgi:application"), but it does work locally. My ProcFile is: web: daphne chatproject.asgi:application worker: python3 manage.py runworker channels I have also tried other things like binding to ports, but am limited in my knowledge. Things like 'daphne -b 0.0.0.0 -p 8001 myproject.asgi:application' (not sure if host ip actually required). In Heroku I have scaled to use both web and worker dynos and they appear in my heroku config. This is my redis config and my asgi.py is configured 100% to the documentation. WSGI_APPLICATION = 'chatproject.wsgi.application' # Channels ASGI_APPLICATION = 'chatproject.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')], }, … -
utf-8' codec can't decode byte 0xa9 in position 112483: invalid start byte in django?
I deployed my django website which is working fine till today.Now, out of nowhere it starts showing unicodedecodeerror Check error message here whilw the full traceback is :- Traceback (most recent call last): File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/gagan/saporawebapp/webapp/views.py", line 214, in explore return render(request,'explore/explore.html',{'query':query,'main':query2,'rank':query3,'sec':query4,'lis':query5,'result':result,'theme':request.user.profile.theme}) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loaders/base.py", line 24, in get_template contents = self.get_contents(origin) File "/home/gagan/saporawebapp/Sapora/lib/python3.6/site-packages/django/template/loaders/filesystem.py", line 24, in get_contents return fp.read() File "/home/gagan/saporawebapp/Sapora/lib/python3.6/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa9 in position 112483: invalid start byte -
Not receiving same OTP in a time step/interval - Django-otp
I have set time step as 300sec and TOTP digit as 6. I'm not receiving same OTP in a time step/interval, means receiving different OTP in a given time step. ie, At 2019-11-03 19:15:00, i will get one code; 19:13:00 , i will get another new code. this is the code: import datetime import time from django_otp.oath import TOTP from django_otp.util import random_hex class TOTPVerification: def __init__(self): # secret key that will be used to generate a token, # User can provide a custom value to the key. self.key = random_hex(20) # counter with which last token was verified. # Next token must be generated at a higher counter value. self.last_verified_counter = -1 # this value will return True, if a token has been successfully # verified. self.verified = False # number of digits in a token. Default is 6 self.number_of_digits = 6 # validity period of a token. Default is 30 second. self.token_validity_period = 300 def totp_obj(self): # create a TOTP object totp = TOTP(key=self.key, step=self.token_validity_period, digits=self.number_of_digits) # the current time will be used to generate a counter totp.time = time.time() return totp def generate_token(self): # get the TOTP object and use that to create token totp = self.totp_obj() … -
How to configure AWS s3 to upload file AWS ec2 instance using Django
I'm currently running a Django project on an AWS EC2 server that has RHEL8 installed as the OS. My AWS environment is configured to store both static files and media files into a S3. My django app model leverages ImageField to upload an image and store in S3. When attempting to save an image to S3 via my django app, I'm currently getting a permission denied HTTP 500 connection error and the issue is not my django app, as I tested the exact same application with same configurations (setting.py) on my localhost and I can successfully upload both static files and media files to s3. Why would it work on my localhost and not in my EC2 instance? The issue is specific to connecting to S3 via the EC2 while uploading the image, as I had no issues uploading static files to S3 from my EC2 instance. In troubleshooting the above issue, I wanted to rule out that the issue was related to my django application, perhaps my settings.py file. I installed the exact same django project on my localhost (laptop) and was able to upload both static files and an image file to my S3 bucket via my django … -
how to add another 0000n_initial.py file from makemigrations command
i want to add another initial.py file from makemigrations file when i try to py manage.py makemigrations it show error you are trying to add a non-nullable field 'role' to user without a default; we can't do that (the database needs something to populate existing rows). Please select a fix : Provide a one-off default now(will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py i want to make another init to make a dependent dropdown this is what i write in models.py import datetime from django.db import models from django.utils import timezone class TableAll(models.Model): table_name = models.CharField(max_length=250) i want to add a foreign key to another model and want to makemigrations to add a new 00002_initial.py(for example) and i want to have something like this(here is the code i found from github source) new initial file (0002_add_initial_data.py) //this is just an example class Migration(migrations.Migration): Country = apps.get_model('hr', 'Country') City = apps.get_model('hr', 'City') india = Country.objects.create(name='India') City.objects.create(name='Bengaluru', country=india) City.objects.create(name='Mumbai', country=india) City.objects.create(name='Chennai', country=india) City.objects.create(name='Hyderabad', country=india) City.objects.create(name='New Delhi', country=india) usa = Country.objects.create(name='United States') City.objects.create(name='New York', country=usa) City.objects.create(name='San Francisco', country=usa) City.objects.create(name='Los Angeles', country=usa) City.objects.create(name='Chicago', country=usa) City.objects.create(name='Seattle', country=usa) russia = Country.objects.create(name='Russia') … -
Increment object's field on creation Django
I'm trying to either get or create an object. However, if I decide to create a new object, I want to keep count of what number in the list, the object is: cat = Cat.objects.get_or_create( profile='Juan' defaults={ counter=Cat.objects.filter(profile='Juan').count() + 1 } ) This looks kinda weird. I was thinking if I could use F() or something related. -
Ordering by m2m field
I have 2 model, and i need ordering to my query. First model: class Author(m.models): name = m.Charfield() Second model: class Book(m.models): title= m.CharField() authors = m.ManyToManyField('Author') I expected what this code return next result Book.objects.all().order_by('authors__name') Some[A] Some[A,B] Some[B,] ... Some[Z, B,D] But I get some like this: Some[A,B] Some[B,] Some[A,B] ... Some[Z, B,D] Why correct way to ordering by m2m field? -
Most efficient way to make continuous sequence of objects in Django
I have model like: city = CharField() order = PositiveIntegerField(default=0) and i'd like to fix sequence and make it uninterruptible. For example if I have: London 0 Paris 5 Boston 7 I need to delete gaps and transform it to: London 0 Paris 1 Boston 2 I can achieve it via something like: current_order = 0 cities = City.objects.all().order_by('order') for city in cities: if not current_order: current_order = city.order else: city.order = current_order city.save() current_order += 1 I found this solution completely inefficient as it hits DB multiple times so I'm thinking how to achieve similar behavior more efficiently, preferable via DB engine (PostgreSQL).