Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Removing all password hashing algorithm django
How can i remove all password hashing algorithm including default one and save my password without hashing. -
How can I Convert TypedChoiceField to Int in Django?
I am trying to convert the data from a choicefield into an INT, but gets the error: "int() argument must be a string, a bytes-like object or a number, not 'TypedChoiceField'" However, I don't understand why the coerce=int, doesn't convert the data from the choicefield into an int. My forms.py class class ReviewForm(forms.Form): readability_rating = forms.TypedChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], coerce=int) My views.py function def readerpage(request, content_id): form = ReviewForm(request.POST) if form.is_valid(): review.readability_rating = forms.TypedChoiceField( choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)], coerce=int) review.save() form = ReviewForm() return redirect('home') My model class Review(models.Model): readability_rating = models.IntegerField(null=True) Thanks for reading this -
Secure django_language cookie in django removes it
I'm trying to secure all my cookies. I found no way to secure the django_language cookie which is set by the LanguageCookieMiddleware. Django don't offers the opportunity to set a setting to secure this cookie and set it to httponly. class CustomLanguageCookieMiddleware(LanguageCookieMiddleware): def process_response(self, request, response): response = super(CustomLanguageCookieMiddleware, self).process_response(request, response) language = get_language() max_age = 365 * 24 * 60 * 60 # 10 years expires = datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age) print(settings.LANGUAGE_COOKIE_NAME) response.set_cookie(settings.LANGUAGE_COOKIE_NAME, language, expires=expires, secure=True, httponly=True) # also tried instead of the line above: # response.cookies[settings.LANGUAGE_COOKIE_NAME]['httponly'] = 'True' # response.cookies[settings.LANGUAGE_COOKIE_NAME]['secure'] = 'True' return response With this "solution" I don't even get the django_language cookie. So trying to modify it just removes it...?! In case you're asking why I'm trying to secure a little poor language cookie: Mozilla likes secured cookies... -
On implementing Elastic search with Haystack in Django getting response with third party plugin but not able to get the response in Python
Getting this error on calling search from django but able to get from third party plugins. Failed to query Elasticsearch using 'q:(xx)': RequestError(400, u'parsing_exception', u'no [query] registered for [filtered]') Traceback (most recent call last): File "/home/ubuntu/venv/local/lib/python2.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search _source=True) File "/home/ubuntu/venv/local/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 84, in _wrapped return func(*args, params=params, **kwargs) File "/home/ubuntu/venv/local/lib/python2.7/site-packages/elasticsearch/client/init.py", line 844, in search "GET", _make_path(index, doc_type, "_search"), params=params, body=body File "/home/ubuntu/venv/local/lib/python2.7/site-packages/elasticsearch/transport.py", line 353, in perform_request timeout=timeout, File "/home/ubuntu/venv/local/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 236, in perform_request self._raise_error(response.status, raw_data) File "/home/ubuntu/venv/local/lib/python2.7/site-packages/elasticsearch/connection/base.py", line 162, in _raise_error status_code, error_message, additional_info RequestError: RequestError(400, u'parsing_exception', u'no [query] registered for [filtered]') Not Found: /static/css/bootstrap.min.css.map -
Django ForeignKey is returning ID number instead of actual string value, particularly for form-based request.POST
I have a website contact form that generates a dropdown box of "names" that are defined in another model "Data". The contact form runs off the model "Quote". As such, I use a ForeignKey reference to populate the "Data" information within the "Quote"-driven form. However, the next step is to move this data to more python code (i.e., for calculations and placement in an email). But, when I request.POST "name" in the quote views file, I receive an ID (i.e., 1) instead of the actual string value for "name." I have read this is how ForeignKey inherently transfers data. Like how I returned the actual string version of "name" in the quote dropdown box, how do I get the actual string version of "name" in a data request.POST / data_dictionary assignment? I have seen similar questions, but I am not completely sure of the simplest answer. models.py (Original one) class Data(models.Model): name = models.CharField(max_length=100, null=True) def __str__(self): return self.name models.py (The one tied to the form) class Quote(models.Model): name = models.ForeignKey(Data, on_delete=models.CASCADE) def __str__(self): return str(self.name) views.py def quote_req(request): submitted = False if request.method == 'POST': form = QuoteForm(request.POST, request.FILES) name = request.POST['name'] if form.is_valid(): data_dict = { 'name_': str(name), … -
I have created the tables in django and while inserting data in database errors occurs
models.py File:-> class Publisher(models.Model): name = models.CharField(max_length=30) class Author(models.Model): name = models.CharField(max_length=30) class Book(models.Model): title = models.CharField(max_length=100) authors = models.ManyToManyField(Author) name = models.ForeignKey(Publisher, on_delete=models.CASCADE) publication_date = models.DateField() admin.py File:-> from librarian.models import Publisher, Author, Book # Register your models here. admin.site.register(Publisher) admin.site.register(Author) admin.site.register(Book) Errors 1) Value Error: Cannot assign "'Oxford University Press'": "Book.name" must be a "Publisher" instance. 2) Type Error: Direct assignment to the forward side -
Why does django have both an authenticate method and a login method?
I'm going through an authentication tutorial and the author is using the authenticate() method to authenticate the credentials data from a login form. The result is assigned to a user variable like so user = authenticate(username=username, password=password) next: The user is logged in using login(request, user) But why the 2 different methods? Isn't authenticating credentials supposed to be part of the procedure of loggin in? So why isn't that part handled by the login function as well? Or are there scenario's where you do want to use authenticate but not login ? Also, what happens when the credentials are bad? Will user become null or will an exception be thrown? Thank you -
How to redirect using fetch API?
I have a redirect view like this: def remove_from_cart(request, product_id): product = Product.objects.get(pk=product_id) cart = Cart(request) cart.remove_product(product) cart.save() message = Message(request) message.set(f'{product.name} has been removed from cart!') return redirect('shopping:cart') I am trying to redirect to this views's response URL via fetch API: remove.addEventListener('click', e => { let url = "{% url 'shopping:remove_from_cart' 123 %}".replace('123', e.target.id) fetch(url, { redirect: 'follow', }) .then(response => console.log(response.status)) // logs 200 }) But the redirect does not happen. It works fine if I enter the url manually, though. How can I correct this? -
Django Rest Framework: Create many to many relationship from urls id params
I'm trying to implement how to create a many to many relationship for the following example: I have multiples job_openings and candidates. One candidate can be applied to many job openings and a job opening can have multiple candidates who applied to it. What I want is to send a request as follows (see urls below for details): Verb: POST URL: {{host}}/v1/job-openings/1/candidates/1 Body: {"status": 2} Verb: DELETE URL: {{host}}/v1/job-openings/1/candidates/1 My questions: Is it the correct Restful / DRF way to do this? How do I pass the url params to my serializers? i.e. job_opening_id and candidate_id params defined in the urls file. Is it correct to delete the association as specified above with the DELETE request? Models (simplified): class Candidate(models.Model): name = models.TextField( default='Búsqueda', null=False, blank=False, ) class JobOpening(models.Model): name = models.TextField( default='Búsqueda', null=False, blank=False, ) candidates = models.ManyToManyField( 'Candidate', related_name='candidates', through='JobOpeningCandidateStatus' ) class CandidateStatus(models.Model): name = models.CharField( max_length=50, null=False, blank=False ) class Meta: db_table = 'core_candidate_status' def __str__(self): return self.name class JobOpeningCandidateStatus(models.Model): candidate = models.ForeignKey( 'Candidate', on_delete=models.CASCADE, ) job_opening = models.ForeignKey( 'JobOpening', on_delete=models.CASCADE, ) status = models.ForeignKey( 'CandidateStatus', related_name='status', on_delete=models.CASCADE ) class Meta: db_table = 'core_job_opening_candidate_status' unique_together = ['candidate', 'job_opening'] Serializer class JobOpeningCandidateStatusSerializer(serializers.ModelSerializer): candidate = serializers.PrimaryKeyRelatedField(queryset=Candidate.objects.all()) job_opening = serializers.PrimaryKeyRelatedField(queryset=JobOpening.objects.all()) … -
Why does can't heroku find the gdal204.dll file on app deployment?
I am deploying a django postgres sql app on heroku. Everything is working correctly on my machine(windows 10). However whenever I try to deploy to heroku it says it can't locate the gdal204.dll file. This is how I am currently referencing the gdal file in my app settings: GDAL_LIBRARY_PATH = 'C:\\Users\\IFY\\Downloads\\publish\\Lib\\site-packages\\osgeo\\gdal204.dll' I suspect that the way I'm referencing the file is what's causing the issue. Here is the error that heroku returns on deployment: OSError: C:\Users\IFY\Downloads\publish\Lib\site-packages\osgeo\gdal204.dll: cannot open shared object file: No such file or directory Any idea how to fix this ? -
How to configure setup for Django 2.2.8 on Shared or VPS Hosting
I am trying to configure web server for Django 2.2.8 on VPS Server as well as Shared Hosting but both are not working. I have configure python on the web server and its shell is working and giving output . But when I am trying to configure Django but its not working Its Giving the blank screen. I have followed these steps for Django Configuration and followed this link https://github.com/sparagus/django-shared-hosting-1and1 Access your server via SSH, which will most likely take you to your base directory (your htdocs directory where the directories to your websites are). Make a directory where you want your Python files to reside and cd into it. mkdir python_files cd python_files Run the build-python.sh ./build-python.sh install/python3.6.3/bin/python3 -m venv venv source venv/bin/activate pip install --upgrade pip pip install -r requirements.txt If you get an SSL error here then there's a problem with OpenSSL. Check if Django is installed correctly. python -m django --version Go back to your base directory and start a Django project. cd .. django-admin startproject your_site and so on followed all the steps which are mentioned on the git link but it is showing blank when accessing the url -
Django generic query builder
I have a lot of models in my Django project, and many of them need their own queries for specific pages. While working on the seperation of concerns, I feel like there should be a way to make one (or very few) methods that are generic enough and work with input based to work as queries for ALL models. Say I have model A B and C and I have the following sets of queries: A.objects.filter(id=object_id) A.objects.filter(id=object_id).values("id", "name") A.objects.filter(name="test") B.objects.filter(relationA=A) B.objects.filter(id__in=list_of_ids) C.objects.all() C.objects.all().exclude('last_name') Is there any way to create a query by a given: Model Name (A, B, C) filter type (possibly, least important if this isn't doable? filter, all) comparison field (id, name, relation) comparison type (x=x, x__in=list, x__lte=10) comparison value (object_id, "test", list_of_ids) So for example, X being dyanmic parts would result in a function (Pseudocode) like: def query(model, filter_type, comparison_field, comparison_type, comparison_value): #X.objects.X(X=X) return model.objects.filter_type(comparison_field + compariston_type=comparison_value) When trying it briefly, I immediately ran into the issue of comparison_field not doing what I need it to. Seeing Q objects being mentioned a lot on SO, are they something I should be applying here? and if so, how? -
Django - Connecting to existing RDS postgres
I am trying to make a Django app to connect to an existing RDS postgres instance I have changed my settings.py file to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': <db-name>, 'USER': <username>, 'PASSWORD': <pswd>, 'HOST': 'project-hash.us-east-1.rds.amazonaws.com', 'PORT': '5432', } } After creating Django project, running python manage.py migrate yelds: Tracking file by folder pattern: migrations Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "/home/gustavo.figueiredo/anaconda3/envs/lp_admin/lib/python3.7/site-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) psycopg2.errors.DuplicateTable: relation "auth_permission" already exists -
How to get URL without required parameters
I have the following path in my URLS: path('remove_order/<int:order_id>', RemoveOrder.as_view(), name='md_remove_order') What I would like to do is get the URL WITHOUT specifying an order_id in my template. Like this: {% url 'md_remove_order' %} so it gives me something like this: "remove_order/" I will then pass this value to my Javascript where the order_id will be added dynamically. -
How to test for raised exception in Python/Django?
I've got a Django project in which I have a function which I want to test. Simplified, the function looks like this: class InvalidUrlError(Exception): pass def get_info_from_url(url): try: return url.split(':')[1].split('/')[0] except Exception: raise InvalidUrlError(f"Invalid url: {url}") And my test looks like this: class ToolsTestCase(TestCase): def test_get_info_from_url_wrong_formatted_url(self): self.assertRaises(InvalidUrlError, get_info_from_url("https://acc.images.data.ourcompany.com/")) When I run it though, I get the following output: $ ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ....E ====================================================================== ERROR: test_get_info_from_url_wrong_formatted_url (checker.tests.ToolsTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/kramer65/repos/auth-proxy/app/checker/tools.py", line 10, in get_info_from_url return url.split(':')[1].split('/')[0] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/kramer65/repos/auth-proxy/app/checker/tests.py", line 57, in test_get_info_from_url_wrong_formatted_url self.assertRaises(InvalidUrlError, get_info_from_url("https://acc.images.data.ourcompany.com/")) File "/home/kramer65/repos/auth-proxy/app/checker/tools.py", line 15, in get_info_from_url raise InvalidUrlError(f"Invalid url: {url}") checker.tools.InvalidUrlError: Invalid url: https://acc.images.data.ourcompany.com/ ---------------------------------------------------------------------- Ran 5 tests in 0.037s FAILED (errors=1) Destroying test database for alias 'default'... Why does it raise the exceptions, instead of passing the tests? I think I do a comparable thing in another test, which works great. Does anybody know what I'm doing wrong here? -
Django setting related objects FK in a clean Way
i am developing an app where the user can create the related data once and when he click on the same button it will carry out a check and if it is created it will redirect him to update view. however, i am doing alot of query in each view and i dont see it as clean and practical since it is not inline with django concept dont repeat. hope any advise to do the same in a cleaner way but i dont want to use AJAX in this project. views.py @login_required @str_required def create_startupaboutform(request) : C = Startup.objects.filter ( author = request.user )[0] R = get_object_or_404 ( Startup , startup_name = C ) obj = Startup_About.objects.filter ( str_about = R ) if obj.exists(): return redirect ( 'update_startupaboutform') else: if request.method == 'POST' : form = startupaboutform ( request.POST ) if form.is_valid ( ) : instance = form.save ( commit = False ) instance.str_about = R instance.save ( ) return redirect ( 'appwizard' ) else : form = startupaboutform ( ) return render ( request , 'create_about.html' , { 'form' : form } ) @login_required @str_required def update_startupaboutform(request): C = Startup.objects.filter ( author = request.user )[0] R = get_object_or_404 ( … -
Django custom management command - option used like "flag"
I want to write Django custom management command with option which doesnt require argument. I want to use option like 'flag': for example: # in this case --force serves as flag with value True python manage.py delete --id 25 --force # in this case I don't have --force,and here is case when I want to have flag with value False python manage.py delete --id 25 here is simplified code: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( "--id", type=self.id, ) parser.add_argument( "--force", default = False ) def handle(self, *args, **options): objects = Object.objects.filter(id=id) if objects.count() != 0 or force: # Delete from database objects.delete() -
Why is an unsaved parent class instance causing a NOT NULL constraint error when saving the child instance?
I'm following a tutorial of Pretty printed on youtube. During the tutorial he tries to instantiate a child model instance with a unsaved parent model instance called Language. But when he runs the code he gets an IntegrityError: NOT NULL constraint failed: example_framework.language_id The narrator then explains that this is because he didn't call save() on the parent instance first leaving it without a primary key. This is the code form the tutorial, and heres the youtube part where he encounters the error: https://youtu.be/2KqhBkMv7aM?t=440 java = Language(name='Java') spring = Framework(name='Spring', language=java) java.save() spring.save() I don't understand why this gives an error though. Doesn't spring reference the same object that is referenced by the java variable? So if save() is called on java, shouldn't the Framework object referenced by the spring variable immediately have a primary key? -
django-background-task not functioning
my django-background-task does nothing, even if I just ask it to do something simple like printing a string. I dont know what I am doing wrong though. views.py: from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth import update_session_auth_hash from .forms import UserRegistrationForm from .models import Player, PlayerStats, TotalLevels from django.core import management from background_task import background import random # background task @background(schedule=5) def play_run(): print('it works!') # management.call_command('runscript', 'runnerscript') def random_logo(): logo = random.randint(1, 5) logo_file = 'logo-nav'+str(logo)+'.png' return logo_file # Main website views def home(request): return render(request, template_name='main/home.html') # bloxors website specific views def homepage(request): logo_file = random_logo() return render(request, template_name='bloxors/homepage.html', context={'logo':logo_file}) # view in which background task is called @login_required def play_redirect(request): play_run() return HttpResponse('Please wait while we redirect you...') Can someone help me by telling what is going wrong? As always, I appreciate any and all answers! -
How to plug in Locale folder for root Templates folder?
I have Templates folder in the root of the project, how to plug in locale folder for it? -
Serialize ArrayModelField into JSON in Django DRF
I am using Djongo with Django 2.2. I am using MongoDb and using Djongo. i am facing issues in GET API. The Comment model is not serialized. Following is the code snippet. models.py import uuid from djongo import models class Comment(models.Model): text = models.TextField(); author = models.TextField(); class Meta: abstract = True def __str__(self): return self.author +self.text class Scene(models.Model): id = models.UUIDField(primary_key = True, default = uuid.uuid4,editable = False) title = models.CharField(max_length=100) comments = models.ArrayModelField( model_container = Comment, ); def __str__(self): return self.title serializers.py from rest_framework import serializers from planning.models import Scene, Comment class CommentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Comment fields = ('text', 'author') class SceneSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Scene comments = CommentSerializer(); fields = ('id', 'title', 'comments') viewsets.py from planning.models import Scene, Comment from .serializers import SceneSerializer, CommentSerializer from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework import status from rest_framework import generics from rest_framework.generics import RetrieveUpdateDestroyAPIView class SceneViewSet(viewsets.ModelViewSet): queryset = Scene.objects.all() serializer_class = SceneSerializer class CommentViewSet(viewsets.ModelViewSet): queryset = Comment.objects.all() serializer_class = CommentSerializer Output for GET scene model in DRF HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": "28db3aa8-34ef-4880-a3eb-57643814af22", "title": "scene 1", "comments": "[<Comment: edwardcomment1>, <Comment: … -
How to convert Django Templates to pdf with PyQt5
CONTEXT: Inside my Django app, I want to be able to create A4-size sale orders PDFs based on user input. I have an HTML Django template, and after completing the missing data I want the app to generate a PDF automatically. I've tried the different alternatives suggested in other threads (WeasyPrint, PdfKit, Xhtml2pdf...) but they all messed-up completely the design, looking nowhere near to what I see when I open the HTML. Finally I settled for PyQt5, as it was the first one which generated a PDF that looked exactly as the HTML in my browser. CODE: The Django view, which calls the PDF creator: def new_order(request): template_file = "orders/SaleOrder.htm" rendered_template = render(request, template_file, {}) print_to_pdf.main() return HttpResponse(rendered_template) The PDF creator module: import sys from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets def main(): file = "orders/SaleOrder.htm" app = QtWidgets.QApplication(sys.argv) loader = QtWebEngineWidgets.QWebEngineView() loader.setZoomFactor(1) loader.page().pdfPrintingFinished.connect(loader.close) loader.page().pdfPrintingFinished.connect(lambda *args: print('finished:', args)) loader.load(QtCore.QUrl.fromLocalFile(file)) def emit_pdf(finished): loader.page().printToPdf("test.pdf") loader.page().pdfPrintingFinished.connect(loader.close) loader.loadFinished.connect(emit_pdf) app.exec() CONCERNS: I am unable to pass a rendered template to the PyQt5 app. One bypass would be to complete the HTML and saving it before calling print_to_pdf.main(), and later opening the HTML the same way with QtCore.QUrl.fromLocalFile(file), but that seems inefficient and error-prone. Ideally I would … -
Object of type data is not JSON serializable error in Django
I have a registration page that allows a user to sign up. After doing so, I want to call an API and then, save the data to my model (not saving it to a form though). I tried doing this: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key=True, related_name = 'profile') address = models.TextField() birthday = models.DateField() def __str__(self): return str(self.user) views.py: def signup(request): if request.method == 'POST': user_form = UserForm(request.POST) register_form = RegisterForm(request.POST) if user_form.is_valid() and register_form.is_valid(): username = user_form.cleaned_data.get('username'), first_name = user_form.cleaned_data.get('first_name'), last_name=user_form.cleaned_data.get('last_name'), email=user_form.cleaned_data.get('email'), password=user_form.cleaned_data.get('password2'), birthday = register_form.cleaned_data.get('dob'), address=register_form.cleaned_data.get('address'), payload = {'username': username,'first_name': first_name,'last_name': last_name,'email':email,'password':password,'register' : {'birthday': birthday,'address': address}} response = requests.post('http://127.0.0.1:8000/my_api/',json=payload) return redirect("home") #re-direct if login is successful else: user_form = UserForm() register_form = RegisterForm() return render(request, 'users/register.html', {'user_form': user_form, 'register_form': register_form}) class RegisterAPI(APIView): permission_classes = [AllowAny] def post(self, request, format=None): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() content = {'status': 'You are registered'} return Response(content, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py: from users.models import Profile from django.contrib.auth.models import User class ProfileSerializer(serializers.ModelSerializer): birthday = serializers.DateField(format="%Y-%m-%d") class Meta: model = Profile fields = ('birthday','address') class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ('username','first_name','last_name','email', 'password', 'profile') def create(self, request, validated_data, *args, **kwargs): register_data = validated_data.pop('profile') … -
Django keep data after validation
I need store the values in input form after Djando validations.How can I do that? Still after validation the inputs will be empty. Laravel has function old() for that, but Django doesnt know this function. User have to fill the input once again and this is the problem. Some idea? Thanks for all help I have this for in my template in Django /python3/: <form method="POST"> {% csrf_token %} {{ register_form }} <button type="submit" class="mt-3 btn btn-primary">Register</button> </form> This is my form class: class RegisterForm(forms.Form): username = forms.CharField( label='Uživatelské jméno', label_suffix='', required=False, widget=forms.TextInput( attrs={'class': 'form-control'}), ) email = forms.EmailField( label='E-mail', label_suffix='', required=False, widget=forms.TextInput( attrs={'class': 'form-control','type':'email'}), ) -
Testing python class object instances
I have this function that I want to test: def get_django_model(django_model): try: app_config = apps.get_app_config("myapp") model = app_config.get_model(django_model) return model except Exception: raise DjangoModelMissing(f"Missing django model: {django_model}") And here is my test: class ModelInstanceTest(TestCase): def test_get_django_model(self): model_class = get_djagno_model("Foo") self.assertIsInstance(model_class, models.Foo) The above test fails, saying AssertionError: <class 'models.Foo'> is not an instance of <class 'models.Foo'>. However if I replace assertIsInstance with assertIs the test passes. Can someone explain what is going on here? This post is related, but doesn't really explain the different results: Python test to check instance type.