Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to keep different files(/versions of files) on local branches and not show them in git status?
Me: I work (develop) on a Django project in a team. And we use postgresql as the database. I had untracked the migrations folders (and files) for obvious reasons. Problem: Sometimes I work on multiple branches and when there is a difference in the models which extend django.db.models.Model the makemigrations fails. My approach on the Problem: I decided to have a different database on my machine for each branch. Found out that this could be done using pygit2 (keep the name of database same as that of the branch). Problem with my approach: The migrations are same in every branch as I have them untracked. I dont want to track migrations because pushing them would disturb the production server migrations. Requirement: Whenever i switch branch, the migrations should change, but at the same time they should remain not pop up during 'git status'. Thank you in advance -
Validate Sign Up User data in serializers - Django Rest Framework
I have an issue with Validate Sign Up User data in serializers - Django Rest Framework. Hope your guys help me! My request: I want to create sign up form with user enter Duplicate email, it'll raise serializer object which duplicate. My serializers: class UserDuplicateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'full_name', 'first_name', 'last_name', ] class UserSignUpSerializer(ModelSerializer): username = CharField(required=True, allow_blank=False) class Meta: model = User fields = [ 'username', 'email', 'password' ] extra_kwargs = {"password": {"write_only": True}} # Validate duplicate username def validate_username(self, value): data = self.get_initial() username = data.get("username") username_qs = User.objects.filter(username=username) if username_qs.exists(): duplicate_obj = User.objects.get(username=username) serializer = UserDuplicateSerializer(duplicate_obj) print(serializer.data) raise ValidationError("This username has been registered!" + serializer.data) else: pass return value def create(self, validated_data): username = validated_data['username'] ... user_obj.save() return validated_data Error: Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Python27\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 489. response = self.handle_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in handle_exception 449. self.raise_uncaught_exception(exc) File "C:\Python27\lib\site-packages\rest_framework\views.py" in dispatch 486. response = handler(request, *args, **kwargs) File "C:\Python27\lib\site-packages\rest_framework\generics.py" … -
Rsync inside container
I have a command inside my django application to copy file from server to local using rsync. It was working fine normally. But when i containerized the code, the file is not getting copied. How am i supposed to copy file using rsync inside container? COMMAND="rsync -avzhe ssh @:/path/test.txt /destination/path/" ssh = subprocess.Popen(COMMAND, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print ssh result = ssh.stdout.readlines() print result result gives [] after containerizing, while normally i had [received xx bytes, sent xx bytes etc] -
How to plot bullet chart using python-nvd3?
I am completely new to python web development and this is my first web app using Python and Django. For plotting purposes I am using python-nvd3. I followed the instructions here : http://python-nvd3.readthedocs.org/en/latest/introduction.html#documentation In python-nvd3 has lots of chart types like Barchart,Line Chart and pie chart etc..In my project i need to plot a Bullet Chart but i didn't get.I have no idea to plot bullet chart using python-nvd3. If anyone have idea to plot bullet chart using python-nvd3 kindly share with me. Thanks in advance. -
hwo to connect redis server with django in dockerizing it?
Currently i am working on django app and trying to work with reddis server. i have add all configuration settings for reddis server in settings.py my settings are like this. redis_host = os.environ.get('REDIS_HOST', 'my-ip-of-reddis-server') # Channel layer definitions # http://channels.readthedocs.org/en/latest/deploying.html#setting-up-a-channel-backend CHANNEL_LAYERS = { "default": { # This example app uses the Redis channel layer implementation asgi_redis "BACKEND": "asgi_redis.RedisChannelLayer", "CONFIG": { "hosts": [(redis_host, 6380)], }, "ROUTING": "multichat.routing.channel_routing", }, } its working fine when i run python manage.py runser or python manage.py runworkers but when i dockerize this django app, it does not make connection with reddis server. it gives following error. redis.exceptions.ConnectionError: Error -2 connecting to redis:6380. Name or service not known. 2018-01-30 06:00:47,704 - ERROR - server - Error trying to receive messages: Error -2 connecting to redis:6380. Name or service not known. 201 my dockerfile is this. # FROM directive instructing base image to build upon FROM python:3-onbuild RUN apt-get update ENV PYTHONUNBUFFERED 1 ENV REDIS_HOST "redis" # COPY startup script into known file location in container COPY start.sh /start.sh # EXPOSE port 8000 to allow communication to/from server EXPOSE 8000 #RUN python manage.py runserver RUN daphne -b 0.0.0.0 -p 8000 --ws-protocol "graphql-ws" --proxy-headers multichat.asgi:channel_layer # CMD specifcies the … -
Safari: Video is not playing from aws or heroku both
I have developed django-framework website video is playing in Chrome, Firefox, IE but i am facing problem with playing video on safari mac. Video is uploaded on aws ec2 ubuntu machine <video id="video" muted controls class="col p-0" poster="http://54.197.43.10/static/images/bg/poster.png" preload="auto"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.mp4" type="video/mp4"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.ogg" type="video/ogg; codecs=theora, vorbis"> <source src="http://54.197.43.10/media/video/cds_1nTIdN6.webm" type="video/webm; codecs=vp8, vorbis"> </video> Is there anything which block server videos on safari ?? -
Django-notification delete API from front-end
Can you please help me about django-notification??? I am able to implement it, but stuck in delete from front end using this API delete/(?P\d+)/ what I suppose to provide in place of (?P\d+)/ , when I call this API -
Django Channels and websockets are not working when run as Docker Image
Django Channels and websockets are not working when run as Docker Image with error Meassage:Error trying to receive messages: Error -2 connecting to redis:6380/6379. Name or service not known. -
how to implement date, consist in two date field in django orm?
this is my model, class HonorKegiatan(models.Model): id = models.AutoField(primary_key=True) jenisKegiatan = models.CharField(max_length=100, null=True, choices=masterkegiatan) honor = models.IntegerField(null=True, blank=True) keterangan = models.CharField(max_length=100, null=True, blank=True) startdate= models.DateField(null=True) enddate= models.DateField(null=True) i want to show honor from this django orm filter where datetime.datetime.now() include between startdate and enddate fields . How to use django orm implement it? honor = HonorKegiatan.objects.filter(startdate__gte=datetime.datetime.now(),enddate__lte=datetime.datetime.now()).values_list('honor',flat=True) but it's not return value? is my django orm is true? -
Python Client error: [Errno 111] Connection refused
hey guys i doont really know the problem but i go an error connection refused. i dont know what to do please help me. im trying to send a count when the button is pressed on android app and im using nanpy to connect to arduino but i got an error. import socket from nanpy import (ArduinoApi, SerialManager) ledpin = 13 buttonpin = 12 buttonpin1 = 2 buttonpin2 = 3 buttonstate1 = 1 buttonstate2 = 1 buttonstate3 = 1 connection = SerialManager() a = ArduinoApi(connection = connection) a.pinMode(ledpin, a.OUTPUT) a.pinMode(buttonpin, a.INPUT) a.pinMode(buttonpin1, a.INPUT) a.pinMode(buttonpin2, a.INPUT) ADDR2 = ('192.168.1.7', 21568) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(ADDR2) while True: try: buttonstate1 = a.digitalRead(buttonpin) buttonstate2 = a.digitalRead(buttonpin1) buttonstate3 = a.digitalRead(buttonpin2) if buttonstate1: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate2: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) if buttonstate3: a.digitalWrite(ledpin, a.HIGH) else: a.digitalWrite(ledpin, a.LOW) add += 1 s = str(add) sock.sendall(s) time.sleep (.5) finally: sock.close this is the error some know how to fix this? Traceback (most recent call last): File "/home/pi/Desktop/counter.py", line 24, in <module> sock.connect(ADDR2) File "/usr/lib/python2.7/socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 111] Connection … -
Autofilling the models in one app with that of another
So basically I want to autofill all model fields in one app with that of another. I want make it clear though I am not talking about only using the save function inside the model as I have already done that The idea is that once I have filled and submitted the information for App A I dont have access the form for App B as the fields for the second field would be automatically filled APP 1 model class Product(models.Model): user=models.ForeignKey(user,on_delete=models.CASCADE,default=1) Name=models.CharField(max_length=120,null=True,blank=True) Category=models.CharField(max_length=80,choices=CATEGORY_CHOICES,null=True,blank=True) Type=models.CharField(max_length=10,choices=GENDER_CHOICES,null=True,blank=True) slug=models.SlugField(null=True,blank=True) Image=models.ImageField(null=True) Description=models.TextField(null=True,blank=True) Price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) Color=models.CharField(max_length=10,null=True,blank=True) Size=models.CharField(max_length=10,choices=SIZE,null=True,blank=True) Delivery_date=models.DateTimeField(null=True,blank=True) Delivered=models.BooleanField(default=False) Timestamp=models.DateTimeField(auto_now=True) def get_absolute_url(self): return reverse('Products:DetailView', kwargs={'slug': self.slug}) def __unicode__(self): return self.name def __str__(self): return self.Name App2 Model class Category(models.Model): name=models.ForeignKey(Product,on_delete=models.CASCADE,null=True,blank=True) type=models.CharField(max_length=13,null=True,blank=True) category=models.CharField(max_length=13,null=True,blank=True) image=models.ImageField(null=True,blank=True) categoryslug=models.CharField(max_length=10,null=True,blank=True) typeslug=models.CharField(max_length=10,null=True,blank=True) slug=models.CharField(max_length=90,null=True,blank=True) color=models.CharField(max_length=10,null=True,blank=True) size=models.CharField(max_length=10,null=True,blank=True) price=models.DecimalField(default=0.00,max_digits=10,decimal_places=2) def save(self, *args, **kwargs): self.category=self.name.Category self.type=self.name.Type self.image=self.name.Image self.typeslug=(self.name.Type).lower() self.slug=self.name.slug self.color=self.name.Color self.size=self.name.Size self.price=self.name.Price super(Category,self).save(*args,**kwargs) def Category_slug(instance,sender, **kwargs): instance.categoryslug=(instance.category).lower() def rl_post_save_reciever(sender, instance,created,*args,**kwargs): print("saved") pre_save.connect(Category_slug, sender=Category) post_save.connect(rl_post_save_reciever, sender=Category) -
why am I getting jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got 'string'
{% for game in scoreecard|slice:":1" %} <tr> <th class="bg-danger text-lg-left">{{game['2nd-innings-runs']}}-{{game["2nd-innings-wickets"]}}({{game["2nd-innings-overs"]}}) </th> <th class="bg-danger text-lg-left">{{game["2nd-innings-batteam"]}} </th> </tr> {% endfor %} I'm trying to break the for loop after one iteration. -
Django Admin DateTimeField Showing 24hr format time
I tried on google but i did not found the solution , In Django Admin side , i showing start date and end date with time . But time is in 24 hr format i want to it in 12 hr format class CompanyEvent(models.Model): title = models.CharField(max_length=255) date_start = models.DateTimeField('Start Date') date_end = models.DateTimeField('End Date') notes = models.CharField(max_length=255) class Meta: verbose_name = u'Company Event' verbose_name_plural = u'Company Events' def __unicode__(self): return "%s (%s : %s)" % (self.title, self.date_start.strftime('%m/%d/%Y'), self.date_end) I also found some thing but this is not helping me What i found I am new in python and django please help me out . -
unable to make RDS queries on heroku
I can access my RDS postresql database on a local machine no problem. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xxxxxxx', 'USER': 'XXXXXXXX', 'PASSWORD': 'XXXXXXXX', 'HOST': 'XXXXXXrds.amazonaws.com', 'PORT': '5432', } I pushed this to Heroku and I get a ProgrammingError at /saferdb/query/ In manage.py shell on heroku I tried to access the database: from saferdb.models import Question q = Question.objects.all() q.count() got the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: relation "saferdb_question" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "saferdb_question" ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/query.py", line 387, in count return self.query.get_count(using=self.db) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/query.py", line 491, in get_count number = obj.get_aggregation(using, ['__count'])['__count'] File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/query.py", line 476, in get_aggregation result = compiler.execute_sql(SINGLE) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1063, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__ raise … -
Django app - What do I install in virtualenv vs system wide?
I'm working on creating my first "real" web app using Django. Yesterday I learned I should be using a web server like Nginx to serve static files and pass off requests for dynamic content to my web app. I also learned that I need something like Gunicorn as the intermediary between the web server (Nginx) and my Django app. My question is about virtualenv. It makes sense that we would contain app related software in it's own separate environment. What should I install in virtualenv, and what gets installed system wide? For example, in this guide we seem to install Python, Nginx and the database system wide (because they're installed before virtualenv is installed) while Django and Gunicorn are installed in virtualenv. It makes sense that Gunicorn would have to go in the virtualenv since its importing our python app, as explained here. Are the other things required to be installed system wide? Or can I pick either way? Is one way preferred over another? Thanks! -
Process large dictionary response in chunks for operations
I have a large dictionary response by which i am creating object in bulk. Since It is a simple object creating in bulk, so it's taking too much time. I am trying to do it by multiprocessing or thread. So I can create bulk object in pieces of data(by single file) and store them together at end. here is my function def create_obj(self, resp): school_db = Schools.objects.bulk_create( [Schools( **{k: v for k, v in value.items() })for key, value in resp.items() ]) return school_db and sample of my large dictionary response- response = { 'A101': { 'VEG': True, 'CONTACT': '12345', 'CLASS': 'SIX', 'ROLLNO': 'A101', 'CITY': 'CHANDI', }, 'A102': { 'VEG': True, 'CONTACT': '54321', 'CLASS': 'SEVEN', 'ROLLNO': 'A102', 'CITY': 'GANGTOK', }, } So is there any way to split up the dictionary into 15-20 chunks by which I can use multiprocessing to process. Any help would be appreciated. -
Django api call in view to save foreign key of user model
What i am doing is django 2 project call api to django 1 project to book an appointment in Appointment table and save the details into BookAppt table. After updating my code based on one of the answer given, i got this error now. {"patientId":["This field is required."]} I have no idea why even though i did include it in already. Please help as i have been stuck at this part for 2 days now. Here is my code: Do note that it is django 2 calling to django 1 model.py django 1 class Appointments (models.Model): patientId = models.IntegerField() clinicId = models.CharField(max_length=10) date = models.DateField() time = models.TimeField() created = models.DateTimeField(auto_now_add=True) ticketNo = models.IntegerField() STATUS_CHOICES = ( ("Booked", "Booked"), ("Done", "Done"), ("Cancelled", "Cancelled"), ) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default="Booked") django 2 class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) class BookAppt(models.Model): clinicId = models.CharField(max_length=20) patientId = models.ForeignKey(MyUser, on_delete=models.CASCADE) scheduleTime = models.DateTimeField() ticketNo = models.CharField(max_length=5) status = models.CharField(max_length=20) serializer django 1 class AppointmentsSerializer(serializers.ModelSerializer): class Meta: model = Appointments fields = ('id', 'patientId', 'clinicId', 'date', 'time', 'created', 'ticketNo', 'status') django 2 class MyUserSerializer(serializers.ModelSerializer): class Meta: model = … -
Wagtail: filter results of InlinePanel ForeignKey dynamically
I have a categorypage -> articlepage hierarchy in wagtail. The article page has an author field, which currently shows all users in the system. I want to filter the authors of the article based on the group of the parent category page. class CategoryPage(Page): ... subpage_types = ['cms.ArticlePage'] class ArticlePage(Page): # how to do X with query service ... author = models.ForeignKey(User, on_delete=models.PROTECT, default=1, # limit_choices_to=get_article_editors, help_text="The page author (you may plan to hand off this page for someone else to write).") def get_article_editors(): # get article category # get group for category g = Group.objects.get(name='??') return {'groups__in': [g, ]} This question (limit_choices_to) is almost what I'm after, but I'm not sure how to retrieve the group for the parent page before the article itself is created? -
Override default Django field with custom widget
I'm using Django 1.11.9 on Ubuntu, with an app structure as such: VisitorTrackingApp | ---> admin.py ---> forms.py ---> models.py ---> static | ---> textboxes.css ---> templates | ---> index.html ---> signin.html ---> views.py ---> widgets.py In my models.py I've defined a model Visitors with an attribute Company (among many others): class Visitors(models.Model): Company = models.CharField(max_length = 50, blank = True) In widgets.py I've defined a custom widget like: from django import forms class TextWidget(forms.TextInput): class Media: css = {'all': ('textboxes.css',)} Then I put it all together in forms.py: from django.forms import ModelForm from models import Visitor from widgets import TextWidget class VisitorsForm(ModelForm): class Meta: model = Visitors fields = ('VisitorType', 'FirstName', 'LastName', 'Company', 'Phone', 'Email') widgets = {'Company': TextWidget(),} All of this executes without error. But my understanding based on the Django documentation here and here is that because I have widgets = {'Company': TextWidget(),}, then Company should render according to the CSS in textboxes.css, but it is not. When I do a sanity check like this: t = TextWidget() print >>sys.stderr, t.media and look at my Apache log, I find that my custom widget does indeed have the correct path to my CSS file! The post at Django … -
djangorestframework browsable api: how to show all available endpoints urls?
In djangorestframework, there is a browsable api. But how do I show a user an entire bird's eye view of all the possible API calls that he/she can make? I can only see one at a time right now and the user would have to already know the correct URL beforehand i.e., http://localhost:8000/users http://localhost:8000/books http://localhost:8000/book/1/author Thank you! -
Django Read png image from url then pass it to HttpResponse
I want to to read png image from private url then write it to HttpResponse. I have this view that will get a layer from geoServer as a png image then open it and read it then return it as HttpResponse: def get_layer(request): #this url will return png image url='https://example.com/geoserver/layer/wms?.......' r = requests.get(url) with open(r, "rb") as fp: img = Image.open(fp) return HttpResponse(img) I am getting an error: Exception Type: TypeError Exception Value: invalid file: Response [200] /main/views.py in test1 with open(r, "rb") as fp: ... ▼ Local vars Variable Value r <Response [200]> request <WSGIRequest: GET '/test/'> url 'https://example.com/geoserver/layer/wms?.......' All want I want is get the png file from the url then pass it the the HttpResponse so when one call my view, he/she will get the image only with my Django path. I do not want to save the image locally I just want to assign it to a variable and pass it. I am using: Django 1.11, python3.5. -
Django model's field default function references unmigrated model
I have two models, one with a foreign key to another. It uses a function to give a dynamic default value to the foreign key. A simplified example: class Model_1(models.Model): x = models.PositiveSmallIntegerField(default=0) def __str__(self): return "Model 1" class Model_2(models.Model): model_1 = models.ForeignKey(Model_1, on_delete=models.CASCADE, default=get_model_1) def __str__(self): return "Model 2" get_model_1 does things like initialize Model_1 if necessary, and dynamically add values to it as needed. In it, I need to run a query: Model_1.objects.filter(model_2=None). My problem is with migrations. I originally did this in two steps (as I added the relevant models and fields). First I added Model_1, then migrated, then added the foreign key with the function. The problem is that I have to build this app on a different machine, so I ran makemigrations and migrate. makemigrations completes sucessfully, but migrate gives an error relating to get_model_1 referencing an nonexistant Model_1. psycopg2.ProgrammingError: column webclient_Model_2.model_1_id does not exist. My question is how to do this without any extra work like temporarily replacing the function with a different one for migration then switching back to this one. -
Cant save the data from excel to database in django
I am new to programming. I have uploaded an excel and wanted to save the data in to database. But i m getting various errors when i try to solve it by checking with stackoverflow. Here is my code MY view: def createSchool(request): if request.method == 'POST' and request.FILES['excel']: localvar= kidDetailsForm(request.POST) myfile = request.FILES['excel'] book = xlrd.open_workbook(myfile.name) sheet = book.sheet_by_index(0) for r in range(1, sheet.nrows): if localvar.is_valid(): temp = localvar.save(commit = False) temp.childname = sheet.cell(r,0).value temp.dob = sheet.cell(r,1).value temp.sex = sheet.cell(r,2).value temp.save() return render(request, 'littleStar/createSchool.html') return render(request, 'littleStar/createSchool.html') my form: class kidDetailsForm(forms.Form): class Meta(): model = kidDetails fields = ("childname","dob","sex") my Model: class kidDetails(models.Model): childname= models.CharField(max_length=245) sex = models.CharField(max_length=245) dob = models.DateField(max_length=245) def __str__(self): return self.childname But when i print the form. i see required errors. Is there a way to bypass the form. I would like to upload the excel and save the data to database. Any help would be great and much appreciated, Thanks. -
Django model create expire date
I would like to automatically create an expire date in my model based on the create date. Say 60 days? class Something ( models.Model ): created = models.DateTimeField ( auto_now_add = True ) expires = models.DateTimeField ( ) What is the best way to accomplish this? Thanks! -
InterfaceError when using Celery's pytest plugin
I'm using Celery's pytest plugin when writing integration tests for a Django app. In development, everything works as intended. However, when I run a sample test, I get an InterfaceError whenever my test uses the plugin. Haven't been able to make much headway on it and would love any advice. Sample code: @pytest.mark.django_db def test_does_become_stale_with_no_messages(self, auth_client, periodic_tasks, celery_session_worker, user_factory, message_factory, session_factory): original_time = datetime.now(pytz.timezone('UTC')) - timedelta(minutes=29, seconds=59) user = user_factory(is_bot=False) session = session_factory(time_start=original_time) message = message_factory(session=session, author=user, time=original_time) wait_until(condition=lambda: Session.objects.get(pk=session.id).is_stale, timeout=5) assert Session.objects.get(pk=session.id).is_stale Sample stacktrace: > user = user_factory(is_bot=False) tests/func/questions/test_monitoring_sessions.py:15: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ venv/lib/python3.6/site-packages/factory/base.py:69: in __call__ return cls.create(**kwargs) venv/lib/python3.6/site-packages/factory/base.py:623: in create return cls._generate(True, attrs) venv/lib/python3.6/site-packages/factory/base.py:548: in _generate obj = cls._prepare(create, **attrs) venv/lib/python3.6/site-packages/factory/base.py:523: in _prepare return cls._create(model_class, *args, **kwargs) venv/lib/python3.6/site-packages/factory/django.py:181: in _create return manager.create(*args, **kwargs) venv/lib/python3.6/site-packages/django/db/models/manager.py:82: …