Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django multitenant architecture options: what influence on database performance?
I m designing a website where security of data is an issue. I ve read this book : https://books.agiliq.com/projects/django-multi-tenant/en/latest/index.html I'm still thinking about the right database structure for users. And im hesitating between shared database with isolated schemas, isolated databases in a shared app, or completely isolated tenants using docker. As security of data is an issue, i would like to avoid to put all the users in the same table in the database or in different schemas in the same database. However i dont understand well if i should put each user in a separate database (create a database per user, sqlite for example but i dont know if it would communicate well with postgres). What is the best practice for this in terms of security? Im wondering how these options affect database speed compared to a shared database with a shared schema, which was the basic configuration of the course i attended on django. I dont have good knowledge on databases so your help on the performance issue would be very appreciated! Also, if I want to do some stats and use tenants data, how difficult is it to query completely isolated tenants using docker or isolated databases, … -
Django rest framework: Unit testing post request gets status code 400
I'm doing some unit tests in this restaurant app, and the API request to cancel orders returns code 400 when running "manage.py test" command, but doing the same request on Postman works fine (with the server also running on my local machine with the "manage.py runserver" command). I think it's something I'm doing wrong with the unit test, but I'm not sure. In settings, Debug = True and ALLOWED_HOSTS = ['*'] (but I also tried ALLOWED_HOSTS = []). Here's the code: tests.py class CancelOrderAPITest(APITestCase): def setUp(self): test_product = Products.objects.create(id=1, name='testProduct', description='-test-', price=2.56) test_product.save() test_order = Order.objects.create(table=1, status='WA') test_order.save() test_order.product.add(test_product) self.user = User.objects.create(username='test') self.user.set_password('passtest') self.user.save() Payments.objects.create(value=0.0, user=self.user) Token.objects.create(user=self.user) def test_CancelWithCredentials(self): check_login = self.client.login(username='test', password='passtest') self.assertTrue(check_login) token = Token.objects.get_or_create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {token[0].key}') data = {"table": 1} order = Order.objects.filter(table=data['table']).order_by('date')[0] response = self.client.post(reverse('cancel-order'), data=data, content_type='application/json') self.assertEqual(response.status_code, status.HTTP_200_OK) # returning 400. Investigate further self.assertEqual(order.status, Order.Status.CANCELED) views.py class CancelOrder(APIView): # REST API view for waiters to cancel orders. The waiter must be an authenticated user permission_classes = (IsAuthenticated,) parser_classes = (JSONParser,) def post(self, request): data = request.data try: order = Order.objects.filter(table=data['table']).order_by('date')[0] order.status = Order.Status.CANCELED order.save() resp = {"status": "Order canceled!"} except ObjectDoesNotExist: resp = {"exception": "Couldn't find requested product!"} return Response(resp) models.py class Order(models.Model): class Status(models.TextChoices): … -
Can I obfuscate CSS class names in Django?
I'm currently using "Django Compressor" to compress HTML, JS, and CSS files. These are the filters I use COMPRESS_FILTERS = { 'css': ['compressor.filters.yuglify.YUglifyCSSFilter'], 'js': ['compressor.filters.yuglify.YUglifyJSFilter'] } I really like the way it obfuscates my variables in js files. I don't know is it possible to obfuscate class names in CSS files too? -
The value of 'list_display[0]' refers to 'answer_text', which is not a callable when using TabularInline
I am new to Django and making my Quiz app. Unfortunately I face The value of 'list_display[0]' refers to 'answer_text', which is not a callable error while registering my models on the admin.py. Here are the codes models.py from django.db import models from django.utils.translation import gettext_lazy as _ class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Updated(models.Model): date_updated = models.DateTimeField(auto_now=True) class Meta: abstract = True class Quizzes(models.Model): class Meta: verbose_name = _("Quizz") verbose_name_plural = _("Quizzes") ordering = ['id'] category = models.ForeignKey( Category, default=1, on_delete=models.DO_NOTHING) title = models.CharField(max_length=255, default=( 'New Quiz'), verbose_name=_('Quiz Title')) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Updated(models.Model): date_updated = models.DateTimeField( verbose_name=_("Last Updated"), auto_now=True) class Meta: abstract = True class Question(Updated): class Meta: verbose_name = _("Quizz") verbose_name_plural = _("Quizzes") ordering = ['id'] SCALE = ( (0, _('Fundamental')), (1, _('Beginner')), (2, _('Intermediate')), (3, _('Advanced')), (4, _('Expert')), ) TYPE = ( (0, _('Multiple Choice')), ) quiz = models.ForeignKey( Quizzes, related_name='questions', on_delete=models.DO_NOTHING) technique = models.IntegerField(verbose_name=_( "Type of Question"), choices=TYPE, default=0) title = models.CharField(verbose_name=_('Title'), max_length=255) difficulty = models.IntegerField(verbose_name=_( "Difficulty"), choices=SCALE, default=0) date_created = models.DateTimeField( auto_now_add=True, verbose_name=_('Date Created')) is_active = models.BooleanField( default=False, verbose_name=_('Active Status')) def __str__(self): return self.title class Answer(Updated): question = models.ForeignKey( Question, related_name='answers', on_delete=models.DO_NOTHING) class Meta: verbose_name = … -
django saved queryset values returns empty on update
why does django filtered queryset returning empty queryset even after saving the queryset values to variable? [check the #outputs] I need to get the user emails but as updated returns boolean, I have to get that before applying the update. But I am not getting the expected output. def approve_gpa_over_two(self, request): application_statuses = ApplicationStatus.objects.filter(application__gpa__gte=2.0,status='application_submitted') application_email = application_statuses.annotate(email=F('application__email')).values_list('email',flat=True) print(application_email) > #output: ['abc@gg.com'] application_statuses = application_statuses.update(status='approved') send_approval_email(application_email) print(application_email) > #output: [] self.message_user(request, 'Approved all applications with GPA over 2.0') return HttpResponseRedirect("../") -
Not able to install non English traineddata on Heroku for Django app
I have tried many things to install non-English tessdata but I could not install trained data for Hindi or other language on Heroku. Following is my setup to install pytesseract and tessdata Buildpack https://github.com/heroku/heroku-buildpack-apt Aptfile tesseract-ocr tesseract-ocr-eng tesseract-ocr-mar libgl1 libsm6 libxrender1 libfontconfig1 libarchive-dev libtesseract-dev *libarchive13* When I am pushing the repo I am getting as follows … remote: -----> Installing libxcb-xfixes0_1.14-2_amd64.deb remote: -----> Installing libxfixes3_1%3a5.0.3-2_amd64.deb remote: -----> Installing libxrender1_1%3a0.9.10-1_amd64.deb remote: -----> Installing libxshmfence1_1.3-1_amd64.deb remote: -----> Installing libxxf86vm1_1%3a1.1.4-1build1_amd64.deb remote: -----> Installing mesa-vulkan-drivers_21.2.6-0ubuntu0.1~20.04.2_amd64.deb remote: -----> Installing tesseract-ocr_4.1.1-2build2_amd64.deb remote: -----> Installing tesseract-ocr-eng_1%3a4.00~git30-7274cfa-1_all.deb remote: -----> Installing tesseract-ocr-hin_1%3a4.00~git30-7274cfa-1_all.deb remote: -----> Installing tesseract-ocr-osd_1%3a4.00~git30-7274cfa-1_all.deb remote: -----> Writing profile script remote: -----> Rewrite package-config files When I am listing the tessdata folder I am getting only eng data ~ $ find -iname tessdata ./vendor/tesseract-ocr/share/tessdata ~ $ ls -l vendor/tesseract-ocr/share/tessdata/ total 22920 -rw------- 1 u59429 dyno 23466654 Oct 17 2018 eng.traineddata Can someone help me to install non English traineddata of my choice on Heroku? -
IntegrityError in django duplicated key
Hello I have a simple form in django, I'm trying to make it return simple error message saying: "this employee already exists", but at the moment the app just crashes whenever I do it, the validation targets the email field of the form, to that I was using the default email field that comes with get_user_model method from django, and I've since added a normal email field to the model but the results are the same. Here's my form: class EmployeeForm(Form): first_name = CharField(max_length=40, label=_('Nombre')) last_name = CharField(max_length=40, label=_('Apellido')) children = IntegerField(label=_('Cantidad de Hijos'), required=False) email2 = EmailField(label=_('Correo electrónico personal'), required=False) email = EmailField(label=_('Correo electrónico Corporativo')) company = ModelChoiceField(queryset=Company.objects.all(), required=False, label=_('Empleado de')) def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, user=None): super().__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted) if not user.is_staff: self.fields['company'].queryset = Company.objects.filter(id=user.employee.company.id) def clean(self): cd = super(EmployeeForm, self).clean() email = cd.get('email2', None) try: obj = Employee.objects.get(email__iexact=email.lower().strip()) if self.instance and not obj == self.instance: raise ValidationError(_('Ya existe un empleade con ese nombre en ese email'), code='not_unique_in_province') except Employee.DoesNotExist: pass return cd my model: class Employee(models.Model): user = models.OneToOneField(User, verbose_name=_('Usuario'), on_delete=models.CASCADE) name = models.CharField(max_length=100, default=' ', verbose_name=_('nombre')) auth_code = models.CharField(max_length=5, verbose_name=_('Codigo autorizacion')) children = models.IntegerField(null=True, blank=True, default=0, … -
A Python Image Capture (include Django if needed)
[ I'm trying to create a web image capture in python (Django if needed) that takes a photo and displays the record of the time capture with the picture taken, and arranges every picture taken in a chronological order. #here is the code of my camera capture # tried adding time capture with chronologically slideshow but I experienced major errors # I hope to hear some feedback (Thank you in advance) import cv2 as cv cam_port = 0 cam = cv.VideoCapture(cam_port) result, image = cam.read() if result: cv.imshow("freetry", image) cv.imwrite("freetry.png", image) cv.waitKey(0) cv.destroyWindow("freetry") else: print("No image") -
How to pass int from python flask back end to front end?
I have an int variable in my python backend id = 1 I want to pass this to my front end, so when the user clicks on a button like <button id = 'next'> <a href="view/<id>"> Where I have a pathway in my server.py @app.route('/view/<id>') def view(id): return render_template('view.html') How can I pass the id variable to my html file so I can link it via ahref? -
Django annotating fields with null values
I have list of Demand objects that have allocated field that would either be null or have a name (denoting this demand's allocation). I use annotations to count allocated/unallocated numbers per team: Demand.objects.filter(project=project).values('team').annotate( unallocated=Count('allocated', filter=Q(allocated__isnull=True)), allocated=Count('allocated', filter=Q(allocated__isnull=False)) ) What's weird is that the numbers for the allocated annotation come out right, but the numbers for the unallocated are always zero. For instance: list(Demand.objects.filter(project=project).values('allocated', 'team')) With the following outcome: [{'allocated': None, 'team': 'Design'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Engineering'}, {'allocated': None, 'team': 'Delivery'}, {'allocated': None, 'team': 'Product'}] but the annotations with have just this: <QuerySet [{'team': 'Delivery', 'unallocated': 0, 'allocated': 0}, {'team': 'Design', 'unallocated': 0, 'allocated': 0}, {'team': 'Engineering', 'unallocated': 0, 'allocated': 0}, {'team': 'Product', 'unallocated': 0, 'allocated': 0}]> Am I doing it wrong or it may be a bug? -
How to use Pyunit test for my code than given below?
class CheckoutView (CreateView): template_name = "checkout.html" def checkout(request): if request.user.is_authenticated: customer = request.user cart, created = 'Cart'.objects.get_or_create(owner=customer, completed = False) cartitems = cart.cartitems_set.all() else: cart = [] cartitems = [] cart = {'cartquantity': 0} context = {'cart': cart, 'cartitems': cartitems} return render(request, 'cart/checkout.html', context) This is my code for checkout and I need unit test for this using pyunit test I tried but failed so I need help -
How to run function in background in Django view
I have Django project with one view. When i refresh page i want to call some function which is very complicated and take same time to execute. How and what is the best way to do it in backround? import time import psycopg2 from django.http import HttpResponse def long_time_function(sec): time.sleep(sec) print('DONE') def index(request): long_time_function(100) return HttpResponse('INDEX page') There is some built in solutions to do that or i need to run this function with thread or multiprocessing and set Deamon = True ? -
Django throws an integrity error while deleting an user
I have a project in which students can be added, when i try to delete the student who has been added django shows an error like this IntegrityError at /student/delete/1 FOREIGN KEY constraint failed Request Method: GET Request URL: http://127.0.0.1:8000/student/delete/1 Django Version: 3.1.1 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed Exception Location: C:\Users\name\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\base\base.py, line 242, in _commit Python Executable: C:\Users\name\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.2 Python Path: ['C:\\Users\\name\\Desktop\\test-projects\\college-management-sytem_withstaffsentmailFinal', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\name\\AppData\\Local\\Programs\\Python\\Python310\\lib\\site-packages'] Server time: Mon, 18 Apr 2022 06:35:06 +0100 here is the django model class Student(models.Model): admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, null=True, blank=False) session = models.ForeignKey(Session, on_delete=models.DO_NOTHING, null=True) def __str__(self): return self.admin.last_name + ", " + self.admin.first_name class Staff(models.Model): course = models.ForeignKey(Course, on_delete=models.DO_NOTHING, null=True, blank=False) admin = models.OneToOneField(CustomUser, on_delete=models.CASCADE) def __str__(self): return self.admin.last_name + " " + self.admin.first_name is there any way to fix this error ? -
Django Web-sockets
I have two pages in the web-application Tickets List and Ticket detail. On the ticket list page, I used datatable to show all data. I used Django channels and WebSockets for real-time updates. Now I want to implement functionality like this. Whenever someone added comments on the ticket detail page(I created a room using the unique ID of the ticket), I want to refresh my API-based data table on the ticket list page. Like -> User comment on detail page (comment consumer sends a response to detail page as well as broadcast an event to another channel to update the table). How can I implement this functionality? -
Need help Implementing a count, retrieve score from user, increment count, then find average implementation Django Python
Need help Implementing a count, retrieve score from user, increment count, then find average implementation Django Python CrystalPrototype_Django_WebsiteV1/prototype/HomeScreen/admin.py from django.contrib import admin from .models import * # Register your models here. admin.site.register(Profile) admin.site.register(Element) admin.site.register(Edit) admin.site.register(TOS) """ This function allows for deletion of elementTexts and will update the auto ranking score after deletion. """ @admin.action(description = 'Delete elements for one TOS and reset weight') def deleteElementText(modeladmin, request, queryset): allElement = Element.objects.all() # allText = ElementText.objects.filter(tos = instance) # filter to get all elements in tos tosElements = allElement.filter(tos = queryset[0].tos) queryElements = queryset.values_list('element', flat = True) excluded = tosElements.exclude(id__in = queryElements) weights = excluded.values_list('weight', flat = True) # get absolute weight absTotal = sum(abs(w) for w in weights) regTotal = sum(weights) # get total total = absTotal + regTotal # set rating TOS.objects.filter(pk=queryset[0].tos.pk).update(weightRating = round((total / absTotal) * 100)) queryset.delete() class ElementTextAdmin(admin.ModelAdmin): actions = [deleteElementText] admin.site.register(ElementText, ElementTextAdmin) -
The word keyword “lazy”
Can anyone explain me the meaning of “lazy”. I can’t understand the meaning of the word “lazy” in Django. For example. In Lazy Translation Topic. These functions store a lazy reference to the string or lazy suffix I met that word many times in many programming languages but I can’t catch it. -
ModuleNotFoundError: No module named 'paystack.urls'
i'm trying to integrate payments subscription with Paystack using Django but it's throws me an error every time i do /manage.py runserver. the error ModuleNotFoundError: No module named 'paystack.urls' for the first time i try to install it with this github repo but it throws me an error pip install -e git+https://github.com/gbozee/pypaystack.git@master#egg=paystack the error ERROR: No matching distribution found for paystack (unavailable) I solved it using this: Future users should change egg=paystack to egg=pypaystack pip install -e git+https://github.com/gbozee/pypaystack.git@master#egg=pypaystack when i add this into my urls.py its throws me an error: urlpatterns = [ path('admin/', admin.site.urls), path('', include('myschool.urls')), path("paystack", include(('paystack.urls','paystack'),namespace='paystack')), ] the error ModuleNotFoundError: No module named 'paystack.urls' the settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'myschool', #crispy Module 'crispy_forms', #Bootstrap Module 'crispy_bootstrap5', 'bootstrap5', 'storages', 'paystack' ] I'm I the first person having this error, because i do my research but i can't found it. -
Does not display image in button [duplicate]
I'm just learning how to use Django and HTML, and I've run into a problem that my image is not displayed on the button, instead I get an icon with a leaf that has a hill and a cloud, I don't understand what the error is, and I will be grateful if someone that will help me fix it. <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title></title> <style> </style> </head> <body> <button> <img src="images/i.jpg" alt="" style="position: relative; float: right; width: 320px; height: 320px"> </button> </body> </html> -
Best way to integrate Square Pay into a Django Web App?
So I've been working on a django e-commerce app, and to allow payment I planned on implementing some form of Square Payment API. When doing research for documentation on this, I couldn't find anything for django. Does anyone have an experience doing this or could anyone point me in the right direction? -
Site admin in django must have site name and password for login
I am making a site management program. 1. Site 2. Block and 3, Door No. the manager charges those sitting there every month. Administrator The site name and password will be entered to login and select the desired site. 1st site will be selected among the residents, the block will be selected according to the 2nd site According to the 3rd block, those who are seated after choosing the door number and password will enter. I couldn't find an example for this. It will always be entered via persons, this is via entity. thank you for your help -
How can i get select value in django html?
I have a modal form like this. I want to show a different form in front of the user according to the selected value here, but I can't get the selected value. How can I do that? <form> <div class="modal-body"> <div class="mb-3" id="modal-id" style="display: none;"> <label for="id-field" class="form-label">ID</label> <input type="text" id="id-field" class="form-control" placeholder="ID" readonly /> </div> <div class="mb-3"> <select class="form-select" aria-label="Disabled select example" name="typeselect"> <option value="1">Type 1</option> <option value="2">Type 2</option> <option value="3">Type 3 </option> <option value="4">Type 4 </option> </select> </div> {% if typeselect.val == "1" %} <div class="mb-3 typeforms typeone"> {{typeoneform}} </div> {% elif typeselect.val == "2" %} <div class="mb-3 typeforms typetwo"> {{typetwoform}} </div> {% elif typeselect.val == "3" %} <div class="mb-3 typeforms typethree"> {{typethreeform}} </div> {% elif typeselect.val == "4" %} <div class="mb-3 typeforms typefour"> {{typefourform}} </div> {% endif %} </div> <div class="modal-footer"> <div class="hstack gap-2 justify-content-end"> <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-success" id="add-btn">Add Customer</button> <button type="button" class="btn btn-success" id="edit-btn">Update</button> </div> </div> </form> I want to display according to option values from the forms I send to the html page. -
Importing CSV file with NULL values to Django Models
I'm importing csv files into Django models using a BaseCommand as such: load_data.py import csv from django.core.management import BaseCommand from api.models import Location, LocationData class Command(BaseCommand): help = "Load data from csv file into database" def add_arguments(self, parser): parser.add_argument('--path', type=str) def handle(self, *args, **kwargs): path = kwargs['path'] with open(path, 'rt') as f: reader = csv.reader(f, dialect="excel") next(reader, None) for row in reader: LocationData.objects.create( location = Location.objects.get(name=row[1]), date = row[2], hour = row[3], measurement = row[4] if row[4] else None ) The measurement column has empty/NULL values so I set up the models.py as such: class LocationData(models.Model): location = models.ForeignKey(Location, on_delete=models.CASCADE) date = models.DateField() hour = models.PositiveSmallIntegerField( validators=[ MinValueValidator(0), MaxValueValidator(24) ], ) measurement = models.FloatField(default=None, null=True, blank=True) def __str__(self): return self.name However, when I try to use the load_data.py which I have created, it resulted in an error: django.db.utils.IntegrityError: NOT NULL constraint failed: api_locationdata.measurement What I have tried: Deleting my migrations files and remigrating using python manage.py makemigrations but the error still occurs. What am I missing here? -
Django Error: Ensure this value has at most 10 characters (it has 321)
i have page file that i am update the details of the user. (Student User) and i create field for student: ID = models.CharField(max_length=10, null=True) and i also do clean_ID in StudentForm, but when i press the correct amount of characters i got the this error: Ensure this value has at most 10 characters (it has 321). you can see this in the photo down here. i don't understand how to fix the problem. VIEWS FILE class DetailsStudentView(View): def get(self,request, student_id): student = Student.objects.get(pk=student_id) userStudent = User.objects.get(pk=student_id) form_student = StudentForm(request.POST or None, instance=student) form_user = StudentUserUpdate(None,instance=userStudent) return render(request, "details.html",{'form_student':form_student, 'form_user':form_user}) def post(self,request,student_id): form_student = StudentForm(request.POST, request.FILES) if form_student.is_valid(): user = User.objects.get(pk=student_id) email = form_student.cleaned_data['email'] user.email = email user.save() student = Student.objects.get(pk=student_id) student.first_name = form_student.cleaned_data['first_name'] student.last_name = form_student.cleaned_data['last_name'] student.Phone = form_student.cleaned_data['Phone'] img = request.POST.get('imag_profile') if img != None: student.imag_profile = img student.ID = form_student.cleaned_data['ID'] student.save() return redirect('HomePage:home') userStudent = User.objects.get(pk=student_id) form_user = StudentUserUpdate(None,instance=userStudent) return render(request,'details.html',{'form_student':form_student, 'form_user':form_user}) Form FILE class StudentForm(forms.ModelForm): email = forms.EmailField(widget = forms.TextInput(attrs={ 'type':"text" ,'class': "bg-light form-control" })) class Meta(): model = Student fields = ('first_name','last_name','Phone','imag_profile','ID') widgets = { 'first_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'last_name': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'Phone': forms.TextInput(attrs={ 'type':"text" ,'class':"bg-light form-control", }), 'ID': forms.TextInput(attrs={ … -
Django - how to access request body in a decorator?
I need to access the body of a request inside of a decorator, how can i do that? I'm calling the cache_page decorator from get in a class based view. In order to perform some logic, i need to access the URL of the request in the decorator. Here is my code: def custom_cache_page(timeout, *, cache=None, key_prefix=None): #print(request) return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=85, cache_alias=cache, key_prefix=key_prefix, ) class Sales_View(APIView): http_method_names = ['get'] @method_decorator(custom_cache_page(1.5)) def get(self, request, format=None): ... -
What the meaning of None . for test result [closed]
When testing in django For example self.assertEqual(response.status_code, 200) self.assertContains(response,"hello") self.assertContains(response,"my page") self.assertContains(response,"my list") self.assertContains(response,"article by") Mainly . is shown but sometimes None is shown. Either case, OK appears the last. such as Ran 8 tests in 3.413s OK