Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What permission/user does apache2 use to write django loggs
I have very good question which I would like an expert to comment on that for me please. (perhaps Graham Dumpleton) So I have a Django web application (developed on ubuntu 16.04) which loges some failures as below on /var/log/apache2/APPNAME.log. since all files in /var/log/apache2 have root:adm owner, I granted ownership of my log file the same way and I made sure www-data is a member of adm group. Then I granted rwx to adm group for owner group and I tested everything was working fine. After 24hr the permission of the file and the parent folder has changed and I can see the write permission has been revoked from the log file and the parent directory causing permission denied error in error because the log file couldn't be written. Here are my questions if you could kindly help: 1) where is the right place to put Django log files? 2) What process under what user permission writes the file? 3) Which process resets permissions in the /var/log/apache and why? Thank you much in advance, I hope this question help others too. Cheers, Mike views.py from django.shortcuts import render from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django … -
Djangosaml2 configuration
Please help me for saml configuration for the OneLogin IdP with djangosml2 library(djangosaml2==0.14.5). Once i come back on my app after successfully login it fails to parse xml response. I'm getting error "SAML response has errors. Please check the logs" Here is my configuration:- SAML_CONFIG = { 'xmlsec_binary': '/usr/bin/xmlsec1', 'entityid': 'http://localhost:8006/saml2/metadata/', 'service': { 'sp' : { 'name': 'Federated Django sample SP', 'allow_unsolicited': True, 'endpoints': { 'assertion_consumer_service': [ ('http://localhost:8006/saml2/acs/', saml2.BINDING_HTTP_POST), ], 'single_logout_service': [ ('http://localhost:8006/saml2/ls/', saml2.BINDING_HTTP_REDIRECT), ('http://localhost:8006/saml2/ls/post', saml2.BINDING_HTTP_POST), ], }, 'required_attributes': ['uid'], 'optional_attributes': ['eduPersonAffiliation'], 'idp': { 'https://app.onelogin.com/saml/metadata/595757': { 'single_sign_on_service': { saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-post/sso/595757', }, 'single_logout_service': { saml2.BINDING_HTTP_REDIRECT: 'https://isystango16.onelogin.com/trust/saml2/http-redirect/slo/595757', }, }, }, }, }, 'metadata': { 'local': [os.path.join(BASE_DIR, 'new_onelogin_metadata.xml')], }, 'debug': 1, 'cert_file': os.path.join(BASE_DIR, 'new_onelogin .pem'), 'contact_person': [ {'given_name': 'Lorenzo', 'sur_name': 'Gil', 'company': 'Yaco Sistemas', 'email_address': 'lgs@yaco.es', 'contact_type': 'technical'}, {'given_name': 'Angel', 'sur_name': 'Fernandez', 'company': 'Yaco Sistemas', 'email_address': 'angel@yaco.es', 'contact_type': 'administrative'}, ], 'organization': { 'name': [('Yaco Sistemas', 'es'), ('Yaco Systems', 'en')], 'display_name': [('Yaco', 'es'), ('Yaco', 'en')], 'url': [('http://www.yaco.es', 'es'), ('http://www.yaco.com', 'en')], }, 'valid_for': 24, } -
Django cms file uploaded files not listing
I am a beginner in Django. I installed Django cms 3.4.1.Login to the admin area and try to upload a file using filter.The upload is seeing successful but the uploaded file is not listed in the folder.Please help me solve this issue. And my media folder is also seeing empty. -
django TypeError: get() got multiple values for keyword argument 'invoice_id'
I am relatively new in python and django, i have following rest api view, class InvoiceDownloadApiView(RetrieveAPIView): """ This API view will retrieve and send Terms and Condition file for download """ permission_classes = (IsAuthenticated,) def get(self, invoice_id, *args, **kwargs): if self.request.user.is_authenticated(): try: invoice = InvoiceService(user=self.request.user, organization=self.request.organization).invoice_download( invoice_id=invoice_id) except ObjectDoesNotExist as e: return Response(e.message, status=status.HTTP_404_NOT_FOUND) if invoice: response = HttpResponse( invoice, content_type='application/pdf') response['Content-Disposition'] = 'inline; filename={0}'.format( invoice.name.split('/')[-1]) response['X-Sendfile'] = smart_str(invoice) return response else: return Response({"data": "Empty File"}, status=status.HTTP_400_BAD_REQUEST) using following urls, urlpatterns = [ url(r'^invoice/(?P<invoice_id>[0-9]+)/download/$', views.InvoiceDownloadApiView.as_view()), ] root url pattern is as following, url(r'^api/payments/', include('payments.rest_api.urls', namespace="payments")), when i call the endpoint, localhost:8000/api/payments/invoice/2/download/ it arise the following error, TypeError at /api/payments/invoice/2/download/ get() got multiple values for keyword argument 'invoice_id' can't figure it out what actually causing this error -
Failed to detect set buildpack in heroku
While trying to deploy my Django application over Heroku, this is the error I am getting $ git push heroku master Counting objects: 53, done. Delta compression using up to 2 threads. Compressing objects: 100% (49/49), done. Writing objects: 100% (53/53), 88.34 KiB | 0 bytes/s, done. Total 53 (delta 11), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Failed to detect set buildpack https://codon-buildpacks.s3.amazon aws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-fa ilure remote: remote: ! Push failed remote: Verifying deploy.... remote: remote: ! Push rejected to murmuring-fortress-39283. remote: To https://git.heroku.com/murmuring-fortress-39283.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/murmuring-fortress-39 283.git' The contents of my directory. $ ls _DS_Store guide/ manage.py* requirements.txt static_in_pro/ venv/ db.sqlite3 hacko/ Procfile runtime.txt templates/ Output to git remote version. $ git remote -v heroku https://git.heroku.com/murmuring-fortress-39283.git (fetch) heroku https://git.heroku.com/murmuring-fortress-39283.git (push) Output to git status $ git status On branch master nothing to commit, working tree clean Contents of requirements.txt dj-database-url==0.4.1 dj-static==0.0.6 Django==1.9 django-toolbelt==0.0.1 gunicorn==19.6.0 psycopg2==2.6.2 static3==0.7.0 -
Why named arguments for django model classes
I want to know that why do we specify names for parameters for model classes like CharField in django.like this for example. first_name = models.CharField(max_length=40, blank=True) why not first_name = models.CharField(40, True) In java we call new charField(40,true) like this.If they are default arguments we specify these in the definition of constructor (in java). Why are we writing here.please,explain. -
Django LEFT JOIN - One to Many
I have the following models: class Employee(models.Model): def getFullname(self): return '{}, {} {}'.format(self.empLastname,self.empFirstname, self.empMiddlename) empID = models.CharField(primary_key=True, max_length= 50, null=False) empLastname = models.CharField(max_length=50) empFirstname = models.CharField(max_length=50) empMiddlename = models.CharField(max_length=50, null=True) fullname = property(getFullname) def __str__(self): return self.fullname class Picture(models.Model): empID = models.ForeignKey(Employee, related_name="pictures", to_field='empID', on_delete = models.CASCADE) picture = models.ImageField('Uploaded image') isDefault = models.BooleanField(default=False) I want to query for all employee that the isDefault field is True in Picture model. But not all Employee have pictures. So basically I want to query all Employee which isDefault=True not all Employee that have no picture(s). My query is look like this: SELECT manager_employee.`*`, manager_picture.* FROM manager_employee LEFT JOIN manager_picture ON (manager_employee.empID = manager_picture.empID_id AND manager_picture.isDefault) this query gave me the correct result.. The problem is on how to do it in Django.. Please somebody help me.. TIA.. -
How to change value of a field (textbox or textarea) from view.py file in Django
I have a webpage named configure.html, which has a from and that from coantains several fields. here is the code for form: <form id="confForm"> <div id="configureWrapper"> <label for="size">HPG Size: </label><label for="hpgsize">2MB</label> <label for="num">HPG Num: </label><label for="hpgnum">49152</label> </div> <div id="textarea"> <label for="aboutDescription" id="aboutHeading">Logs:</label> <textarea id="logs" name="logs"></textarea> </div> </form> And this is code of view.py file when user got to configure.html page: class ConfigureView(TemplateView): def post(self, request, *args, **kwargs): size = request.POST.get('size','') num = request.POST.get('num','') flavorName = request.POST.get('flavor_name','') d = '/home/stack/' p = Popen(['python', d+"/enable_hugepages.py"], stdout=PIPE,stderr=PIPE) logs ="All Logs: \n " while True: nextline = p.stdout.readline() // here i want to append data in nextline to the data of "logs" field in configure.html -
How do I comment out jinja within html
I'm using django to make a simple website. However I can't figure out how to comment out jinja when it's inside an html statement. For example in the code <!DOCTYPE html> <html lang="en"> <head> <title>Harrison Kinsley</title> <meta charset="utf-8" /> {% load staticfiles %} <!-- <link rel='stylesheet' href="{% static 'css/bootstrap.min.css %}" type='text/css'/> --> <link rel='stylesheet' href="/static/css/bootstrap.min.css" > <!--instead of hardcoding we use jinja --> </head> the comment method seems to not comment out the jinja logic, giving this error: TemplateSyntaxError at / Could not parse the remainder: ''css/bootstrap.min.css' from ''css/bootstrap.min.css' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.9 Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: ''css/bootstrap.min.css' from ''css/bootstrap.min.css' Exception Location: C:\Python27\lib\site-packages\django\template\base.py in parse, line 514 Python Executable: C:\Python27\python.exe Python Version: 2.7.12 Saying that this is the specific error: 9 <!-- <link rel='stylesheet' href="{% static 'css/bootstrap.min.css %}" type='text/css'/> --> highlighting the href="{% static 'css/bootstrap.min.css %}" part -
Django admin: sort on column from reverse foreign key
# models.py class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def get_rating(self): return self.playerrating_set.order_by('modified').last().level class PlayerRating(models.Model): modified = models.DateTimeField(auto_now=True) player = models.ForeignKey(Player, on_delete=models.CASCADE) level = models.FloatField(default=0.0) # admin.py class PlayerInline(admin.StackedInline): model = Player class PlayerAdmin(UserAdmin): inlines = (PlayerInline,) list_display = ('first_name', 'last_name', 'rating') def rating(self, obj): try: return obj.player.get_rating() except: return 0 rating.admin_order_field='????' I need my player admin page to contain a 'Rating' column that the user can sort asc or desc. How can I do this? I started out as shown above, hoping to add a property for get_rating(), and then use that property for admin_sort_field, but that won't work. I found solutions for similar problems, but they're ordering by a quantity, and they're able to override get_queryset() in a manager and annotate the count: Django admin: how to sort by one of the custom list_display fields that has no database field Is there a solution for my situation? Or should I denormalize, and add a 'rating_level' attribute to my Player class? -
Accessing many-to-many set field in django relation
I have a set of models similar to that below, where a person can be a member of many clubs, but have a different membership type. In this instance, I consider Membership to be a weak entity of Club class Person(models.Model): name = models.TextField() class Club(models.Model): members = models.ManyToManyField( Member, related_name="members" through='Person' ) class Membership(models.Model): person = models.ForeignKey(Person) club = models.ForeignKey(Club) member_type = models.TextField() I know that I can access the membership details from a club by going: instance_of_club.membership_set.all() And I can get a listing of all the people by using this: instance_of_club.membership_set However, I am trying to write a serialiser for this sort of scenario and am having trouble correctly finding the "membership" details from the django Meta class. Club._meta.many_to_many gives the members field: <django.db.models.fields.related.ManyToManyField: members> But nothing on members gives any indication on how to get the _set accessor - and I need to be able to get these programatically. What I want is to be able to get a list of all ManyToMany through relations, and then get the objects these hold and not just the foreign objects. How can I get a list of the through relation objects on a ManyToMany field? -
When does the queryset use its _result_cache, not hitting the database?
I am confused with the time queryset uses its _result_cache or it directly hits the database . For example (in python shell), user = User.objects.all() # User is one of my models print(user) # show data in database (hitting the database) print(user._result_cache) # output is None len(user) # output is a nonzero number print(user._result_cache) # this time, output is not None So, my 1st question is "Why the _result_cache is None after hitting the database ?" 2nd question is "Does the queryset is evaluated mean that the _result_cache is not None ?" Fin question is "When does the queryset use its _result_cache, not hitting the database ?" -
Cannot get my delete button link to show up in django
I can't figure out what is wrong with my code to get my delete message link to show up. All help is greatly appreciated. views.py def remove_message(request, message_id): Message.objects.filter(id=message_id, user=request.user).delete() return redirect(reverse('dashboard:show', args=user_id)) show.html {% for message in messages%} <div class="message"> <p class='bg-primary wall_content'><strong>{{message.messageuser.first_name}} wrote:</strong></p> <p class='wall_content'>{{message.message}}</p> {% if message.id == request.user %} <a href='{% url "dashboard:remove_message" message.id %}'>Delete Message</a> {% endif %} {% endfor %} -
Returning multiple values independently from django model for modelchoicefield
I have a model called group and another called group membership. What I'm trying to do is return a seperate string, for one of my fields in my form. It displays correctly in the front end but when writing to the database it's all in one string. All im trying to do is get the group_name and cut out the rest of the string when writing to the database. My Model # Group # ######### class Group(models.Model): created_by = models.ForeignKey('auth.User', related_name='group_created_by') id = models.AutoField(primary_key=True) company = models.ForeignKey(Company) department = models.ForeignKey(Department) group_name = models.CharField(max_length=100) role = models.CharField(max_length=100) status = models.CharField(max_length=8) created_date = models.DateTimeField(default=timezone.now) modified_date = models.DateTimeField(blank=True, null=True) modified_by = models.ForeignKey('auth.User', related_name='group_modified_by', blank=True, null=True) def create(self): self.save() def __str__(self): return '{}{}{}'.format(self.company, self.department, self.group_name) My Form # Group Name # ############## class GroupNameModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return '{}'.format(obj.group_name) # Group Membership # #################### class GroupMembershipForm(forms.ModelForm): options = (('Enabled', 'Enabled',), ('Disabled', 'Disabled')) member_id = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}) ) company = forms.ModelChoiceField( queryset=Company.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}), empty_label='' ) department = forms.ModelChoiceField( queryset=Department.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}), empty_label='' ) group_name = GroupNameModelChoiceField( queryset=Group.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}), empty_label='' ) user_id = forms.ModelChoiceField( queryset=Person.objects.filter(status='Enabled'), widget=forms.Select(attrs={'class': 'form-control'}), empty_label='' ) full_name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), ) status = forms.CharField( widget=forms.Select( attrs={'class': 'form-control'}, choices=options ) … -
Django Model Entries Not Available to Other Developers
I have manually added entries (rows) to the models in my Django project through the admin interface. I have also ran the following commands python3 manage.py makemigrations & python3 manage.py migrate The issue is I am the only one that can see the data in the database, and other developers cannot see them. They are all using the same project files as present on my computer. -
Failed to start gunicorn.service: Unit gunicorn.service not found
I am trying to deploy a basic application to Amazon EC2 using Django, Gunicorn, and Nginx. I have the app git clone'd into my AWS Ubuntu instance and am running Django 1.10. I am able to run my app using Gunicorn with the following command... gunicorn --bind 0.0.0.0:8000 blackspruceherbals.wsgi:application I am running into trouble though when I try to create a upstart file for Gunicorn. The file path is as follows... /etc/init/gunicorn.conf and the upstart code looks like this... description "Gunicorn application server handling black spruce herbals" start on runlevel [2345] stop on runlevel [!2345] respawn setuid ubuntu setgid www-data chdir /home/ubuntu/websitename exec gunicorn --workers 3 --bind unix:/home/ubuntu/websitename/websitename.sock websitename.wsgi:application When I run... sudo service gunicorn start I get the following error... Failed to start gunicorn.service: Unit gunicorn.service not found. What gives? I have scoured the internet looking for an answer, but have found nothing. Can you see something obvious I am doing wrong? Thanks in advance. -
Django Unit Test - POST a list for a field
I am writing a test case in Django to test a formset, and I tried to POST a list for field "field1" as below, however, the views in Django is not getting any data for "field1" at all? Am I doing something wrong there? data = {'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1000, 'form-0-name': 'my name', 'form-0-field1': 'abc', 'form-0-field1': 'efg', 'form-0-field1': 'hij', 'form-0-id': '1', 'form-0-ORDER': '1'} response = self.app.post(self.url, user=self.user, params=data, status=200) -
django rest framework post multiple related objects
i d like to post and save an html form with related objects of a model using django-rest-framework. ex: <input type=text name="title"> <input type=text name="images[0][description]" value="test"> <input type=file name="images[0][image]"> <input type=text name="images[1][description]" value="test"> <input type=file name="images[1][image]"> and my serializer classes are like this class GalleryImageSerializer(serializers.ModelSerializer): class Meta: model = Image class GalleryCreateSerializer(serializers.ModelSerializer): images = GalleryImageSerializer(many=True) def create(self, validated_data): images = validated_data.pop('images') gallery = Gallery.objects.create(**validated_data) for image_data in images: Image.objects.create(gallery=gallery, **image_data) return gallery class Meta: model = Gallery fields = ('images') i could not manage to do a successful post. either it is complaining about there is no file submitted or saving it without the related images. thanks in advance -
How to really deploy a Django websocket app with nginx?
For an small Django (1.10.3) app I'd like to have websockets and I'm new to the whole websockets business. So I searched for a relatively easy to understand project for django that enables websocket connections and I've found django-websocket-redis, which looks easy to use and deploy. So I created a very small example project (see the github page) where I can test the things I've learnt while reading the documentation of django-websocket-redis and I was very quickly able to write something that works. If I start the app with ./manage.py runserver 0.0.0.0:3000 and go to http://localhost:3000, then the page is able to make the websocket connection, subscribe to a channel and add a <li>content</li> on the page whenever a new message from the server arrives. In the django app I started a thread that broadcast over the websocket interface randomly between 2 and 9 seconds a random string. I was happy with that and I planned to see if the deployment is as easy as it seems. So I took a closer look at documentation and almost made copy & paste changing only the things that apply to me. I created a file websockets/wsgi_websocket.py with import os import gevent.socket import … -
Lots of errors with pymysql and Django when trying to run server
I just created a Django project and trying to use virtual environment. I have successfully installed: django 1.9.11. virtual environment python 3.4.4. pymysql I thought I was doing everything right, but I am not able to run django development server and it gives me alot of errors inside files: base.py __init__.py connections.py err.py It gives me this right after I try to run the server: python manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors. <locals>.wrapper at Traceback (most recent call last): How would i fix this so I can run the development server with mysql? Thank you. -
Django- jQuery AJAX POST response- trouble parsing JSON
I'm using an app that allows me to post forms responses, from an html template, asynchronously. I've verified that my POST works fine, but I'm having trouble with the response. This is the main code for the corresponding Django view: #views.py from the app........ def post(self, request, *args, **kwargs): published = Form.objects.published(for_user=request.user) form = get_object_or_404(published, slug=kwargs["slug"]) form_for_form = FormForForm(form, RequestContext(request), request.POST or None, request.FILES or None) if not form_for_form.is_valid(): form_invalid.send(sender=request, form=form_for_form) else: # Attachments read must occur before model save, # or seek() will fail on large uploads. attachments = [] for f in form_for_form.files.values(): f.seek(0) attachments.append((f.name, f.read())) entry = form_for_form.save() form_valid.send(sender=request, form=form_for_form, entry=entry) self.send_emails(request, form_for_form, form, entry, attachments) if not self.request.is_ajax(): return redirect(form.redirect_url or reverse("form_sent", kwargs={"slug": form.slug})) context = {"form": form, "form_for_form": form_for_form} return self.render_to_response(context) def render_to_response(self, context, **kwargs): if self.request.method == "POST" and self.request.is_ajax(): json_context = json.dumps({ "errors": context["form_for_form"].errors, "form": context["form_for_form"].as_p(), "messag": context["form"].response, }) if context["form_for_form"].errors: return HttpResponseBadRequest(json_context, content_type="application/json") return HttpResponse(json_context, content_type="application/json") return super(FormDetail, self).render_to_response(context, **kwargs) and this is the javascript part of my html template responsible for the post: //My html template..... <script type="text/javascript"> var frm = $('#theform'); frm.submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), headers: {'X-CSRFToken': '{{ csrf_token }}'}, data: frm.serialize(), dataType: 'json', success: function … -
How to edit select option values of the form from Django forms?
In my view I am validating if the input is legal def tenant_new(request,pk,uri): lease = get_object_or_404(Lease, pk=pk) title = 'tenant' uri = _get_redirect_url(request, uri) if request.method == "POST": form = LeaseTenantForm(request.POST) if form.is_valid(): tenant = form.save(commit=False) tenant.lease = lease if LeaseTenant.objects.filter(tenant=tenant.tenant, lease=tenant.lease).count() > 0: messages.add_message(request, messages.ERROR, str(tenant.tenant) + "-tenant already exists for lease") return redirect(uri) tenant.save() messages.add_message(request, messages.SUCCESS, str(tenant.id) + "-SUCCESS Object created sucssefully") return redirect(uri) else: form = LeaseTenantForm() return render(request, 'object_edit.html', {'form': form, 'title': title, 'extend': EXTEND}) I do it in the view since my form doesn't have a field I populate in the view and I have to use this field during my validation. However I also want to limit what they can select as input for tenant field so users will not see fields they can not use in the form. How can I do it from the view? -
How to connect Faceboook Authentication (OAUTH) to Django app
I have a Django web app that I've made an I'm trying to configure the login/registration system to use Facebook accounts through OAUTH. I'm using the framework allauth which I already have setup. In following this video for the setup, I came to the step where I had to create the Facebook developers App which will allow users of my Django app to be redirected to a facebook login page when they login. I've been able to successfully create and configure the app making sure to heed instructions such as the ones in this post but for some reason, when I try to test the facebook login feature, I get redirected to a page that says: Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. I'm currently running the app on localhost and have the site URL as http://localhost:8000/ After the app logs the user in, they are supposed to be redirected to http://localhost:8000/profile which I have added as an app domain. Why might I be getting this error when the … -
Pass python/django variable into javascript as JSON?
Woking on personal project website with django 1.9 and python 3.4. I am using FullCalendar. The idea is to pass a set of appointment objects into the html page containing the javascript for the calendar. But right now, I am just trying to pass a single default appointment. In views.py I have the following: appt = json.dumps({ "title": "meeting", "start": "2016-11-20"}); return render(request, 'healthnet/profile_patient.html', {'patient': patient, 'appt': appt_set}) In profile_patient.html: <script> var data = jQuery.parseJSON("{{appt}}"); var events; events = []; events.push(data); $(document).ready(function() { $('#calendar').fullCalendar({ editable: true, eventLimit: true, // allow "more" link when too many events events: events }); }); </script> appt is not getting properly parsed I believe. When the web page is loaded, the calendar does not display at all. When I substitute appt with the direct string, it does work: var data = jQuery.parseJSON('{"title": "meeting", "start": "2016-11-20"}'); When I call alert("{{appt}}"); I get the following: enter image description here So there's something wrong with the way I'm using ths varibale. Any ideas? -
Django: TransactionManagementError when using migrated db but not my dev db
I've been working on what is essentially version 2.0 of my project for months now. It includes boosting from Django 1.4 to Django 1.9. I have a Client model and there is an additional model ClientAccountNumber that keeps track of account numbers (so that the account number will remain as used forever, even if the client record is deleted) I've cut out most of the code for brevity but in the Client model's save method I am querying the ClientAccountNumber table and saving a record there. class Client(models.Model): .... def save(self, *args, **kwargs): ... if not ClientAccountNumber.objects.filter(practice=self.practice, account_number=self.account_number, client=self).exists(): ClientAccountNumber(client=self).save() This code could probably be better but this has not changed from version 1, nor has it caused any problems during development of version 2 whatsoever. But I'm now testing post migration of a copy of the real production database and am suddenly getting this error when I try to update a client object: TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. I've read up on the error and vaguely understand it, but this sounds like a programming logic error and this hasn't come up at all in development. …