hash
stringlengths
64
64
content
stringlengths
0
1.51M
5b6246f7a854b6d8a71137e49c593f2d93a4876461d1e687246caa852fd6b56c
from django.http import HttpRequest from django.test import SimpleTestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango40Warning @ignore_warnings(category=RemovedInDjango40Warning) class TestDeprecatedIsAjax(SimpleTestCase): def test_is_ajax(self): request = HttpRequest() ...
32509125a469567c1549802d6cfe02881b27b568256bec86cafa688c2d82f30c
from unittest import TestCase from django.http import HttpRequest from django.http.request import MediaType class MediaTypeTests(TestCase): def test_empty(self): for empty_media_type in (None, ''): with self.subTest(media_type=empty_media_type): media_type = MediaType(empty_me...
281e03f5574893007d1d0372f54b83f3475af1d259f65c2055efcdae18aaec6a
import datetime import pickle import sys import unittest from operator import attrgetter from django.core.exceptions import EmptyResultSet, FieldError from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Count, Exists, F, OuterRef, Q from django.db.models.expressions import RawSQL from djang...
bcfb4de721dadd16c2924ec7e11094d0d318eb7e70907497ccceb6b7164dd8ac
""" Various complex queries that have been problematic in the past. """ import threading from django.db import models from django.db.models.functions import Now class DumbCategory(models.Model): pass class ProxyCategory(DumbCategory): class Meta: proxy = True class NamedCategory(DumbCategory): ...
1090ce66447714067c5681447fd695e9068ba3f153eec7a6170c954bd73ccc7e
from django.db import DatabaseError, NotSupportedError, connection from django.db.models import Exists, F, IntegerField, OuterRef, Value from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import Number, ReservedName @skipUnlessDBFeature('supports_select_union') class QuerySetSetOpera...
0527d2a4b2bd28b86550e6ae96038f4bf5086eebdd97329c1ff2b4f2fc81f244
import datetime from django.core.exceptions import FieldDoesNotExist from django.db.models import F from django.db.models.functions import Lower from django.test import TestCase, skipUnlessDBFeature from .models import ( Article, CustomDbColumn, CustomPk, Detail, Individual, JSONFieldNullable, Member, Note, N...
6cfbf03abacba58ac13f98a13f96a628d3ae0499c9f77112688cfaf0a2467c46
import pickle import time from datetime import datetime from django.template import engines from django.template.response import ( ContentNotRenderedError, SimpleTemplateResponse, TemplateResponse, ) from django.test import ( RequestFactory, SimpleTestCase, modify_settings, override_settings, ) from django.tes...
5bb730a20c6d681f9f810530cb41aeaa2121b0b97375090c6537499be0d1b604
import datetime from unittest import skipIf, skipUnless from django.db import connection from django.db.models import CASCADE, ForeignKey, Index, Q from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import override_settings from django.utils impo...
5a3cd01877bad2cfd4af490c388e0e00c73c8998ae727a37144d7364dc25c43c
from datetime import datetime from django.db import models # M2M described on one of the models class Person(models.Model): name = models.CharField(max_length=128) class Meta: ordering = ('name',) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToMan...
88eb94cbbac86eeb0c022fcc4ab8d7b92ec816cfc7fcbe5d1cecfb0d7d280ce2
import datetime import re from datetime import date from decimal import Decimal from django import forms from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.forms.models import ( BaseModelFormSet, _get_foreign_key, inlineformset_factory, modelformse...
df5f4f2a558c664c40c85ca4a237830e02681a46f53c582d36ed2f1e9940678f
import datetime from copy import deepcopy from django.core.exceptions import FieldError, MultipleObjectsReturned from django.db import IntegrityError, models, transaction from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, ChildNullabl...
52a790c53f1b899a39a86a85231db2dad3c71bc888273f534edd587f7b3492bb
""" Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): ret...
178fc3056873667c83c846040af83f14a36fd57becc1036df1f202bcd01cb915
import base64 import os import shutil import string import tempfile import unittest from datetime import timedelta from http import cookies from pathlib import Path from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.contrib.sessions.backends.cache import SessionS...
b32e78774461ab6fcdf9dc04a4cf7bb5111ccb06d4840455fa70ee4f993542f5
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) class Choice(models.Model): poll = models.ForeignKey(Poll, models.CASCADE) choice = models.CharField(max_length=200) # A set of models with an inner one pointing to two outer ones. class OuterA(models.M...
4d46d757ccca02cb4e0c67c1fd1e9208413d8a0c8ea046d47d62e3ff20a9f193
"""Tests for django.db.utils.""" import unittest from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS, ProgrammingError, connection from django.db.utils import ConnectionHandler, load_backend from django.test import SimpleTestCase, TestCase class ConnectionHandlerTests(Simpl...
82b9dc98c39853d10b9c7de71bbaea3215f72be36bfba73a492a0bc9b8ddb2d5
""" DB-API Shortcuts ``get_object_or_404()`` is a shortcut function to be used in view functions for performing a ``get()`` lookup and raising a ``Http404`` exception if a ``DoesNotExist`` exception was raised during the ``get()`` call. ``get_list_or_404()`` is a shortcut function to be used in view functions for per...
bf57d66ed5e3743061522f92a918b5ba95d5bea03d59d12beaa59eff04df3360
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and temp...
a6674a84fb5f0078d94498123a0179e31a3ee18249f48bc7e98baad7dc70eb53
from django.contrib.auth import views as auth_views from django.urls import path from django.views.generic import RedirectView from . import views urlpatterns = [ path('upload_view/', views.upload_view, name='upload_view'), path('get_view/', views.get_view, name='get_view'), path('post_view/', views.post_...
4b4c21a52f40bdcd8fadfba8736c8e0a6edfce59ec668d819ae3b94779e92447
import json from urllib.parse import urlencode from xml.dom.minidom import parseString from django.contrib.auth.decorators import login_required, permission_required from django.core import mail from django.core.exceptions import ValidationError from django.forms import fields from django.forms.forms import Form from ...
93678c55a319661690e91c56971438129b9a25ef7960273879b084c0857e9bc1
from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name from django.core.signals import request_finished, request_started from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, ...
5485ea7ad5e279108bdf68b89fc3aa80237a801a11e400dd77a253056436b848
from django.urls import path from . import views urlpatterns = [ path('regular/', views.regular), path('async_regular/', views.async_regular), path('no_response_fbv/', views.no_response), path('no_response_cbv/', views.NoResponse()), path('streaming/', views.streaming), path('in_transaction/',...
7b4a03b73f36ba37c1993685592518cfb6e6c2feff1e6bfc11f9dd78f27f0c09
import asyncio from http import HTTPStatus from django.core.exceptions import SuspiciousOperation from django.db import connection, transaction from django.http import HttpResponse, StreamingHttpResponse from django.views.decorators.csrf import csrf_exempt def regular(request): return HttpResponse(b"regular cont...
6d404c04cc7e0aeb51e3dd9166ef1c16e8c5babcde4c945488045787f6ffef9b
"""Tests for django.db.backends.utils""" from decimal import Decimal, Rounded from django.db import NotSupportedError, connection from django.db.backends.utils import ( format_number, split_identifier, truncate_name, ) from django.test import ( SimpleTestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDB...
00470378c1922d8e296dcd8244d66f7d6d2a95dfdd93c216b595b766677bbd9d
"""Tests related to django.db.backends that haven't been organized.""" import datetime import threading import unittest import warnings from django.core.management.color import no_style from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connection, connections, reset_queries, transaction,...
b47e6ebc88e53dd2cb39bcd21327b9034d9ae9f775d499a06494675ea5eb78d8
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class Square(models.Model): root = models.IntegerField() square = models.PositiveIntegerField() def __str__(self): ret...
36e511dcbf3edfcc5a979b04716d2209046057721bedad5ab9f234b484636798
from unittest import skipUnless from django.db import models from django.template import Context, Template from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from django.utils.version import PY37 from .models import ( AbstractBase1, AbstractBase2, Abstra...
3293e8b0e68e127369b6298c3864f4876d3878e03cbbf679b6b59a457557b977
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.management.color import no_style from django.db import ( DatabaseError, DataError, IntegrityError, OperationalError, connection, ) from django.db.models import ( CASCADE, PROTECT, AutoField, BigAut...
845157e6ab08631930274618d6b92d9d5fd88212db78b444489b34860ffc3207
from django.apps.registry import Apps from django.db import models # Because we want to test creation and deletion of these as separate things, # these models are all inserted into a separate Apps so the main test # runner doesn't migrate them. new_apps = Apps() class Author(models.Model): name = models.CharFie...
a89f4885cd83eb5642e7ea1b5851c2b9d5c3eff776f7174ad7079cf75ba17106
from functools import partial from django.db import models from django.db.models.fields.related import ( RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor, RelatedField, create_many_to_many_intermediary_model, ) class CustomManyToManyField(RelatedField): """ Ticket #24104 - Need to have a custom ...
320cceead058a5acdf16f0bc949dac109c9f1859a68cba1aef19c129129546c1
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import Requ...
276408e31165072cc61d8b4ee8731e2f4ba1f2617597e0163baa52dc78cf3643
""" Testing of admin inline formsets. """ import random from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Parent(models.Model): name = models.CharField(max_length=50) def __str__(self): retur...
cf90d521078385bf26ed51d34b2c4bf82fcd90f0fdbb0d7718fe68adf90f5c9a
from django import forms from django.contrib import admin from django.core.exceptions import ValidationError from django.db import models from .models import ( Author, BinaryTree, CapoFamiglia, Chapter, Child, ChildModel1, ChildModel2, Consigliere, EditablePKBook, ExtraTerrestrial, Fashionista, FootNote, H...
66aa72ec5c22d3f2df0e0645744d892503871497e84bf1a1d1d892d7be59c67f
import decimal from django.db import models class Cash(decimal.Decimal): currency = 'USD' class CashField(models.DecimalField): def __init__(self, **kwargs): kwargs['max_digits'] = 20 kwargs['decimal_places'] = 2 super().__init__(**kwargs) def from_db_value(self, value, express...
23c94641862180eb48eea3c31da6bdffe63521521db0d92334524ada0c5b3f13
from django.core.checks.caches import E001, check_default_cache_is_configured from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCacheSettingsAppDirsTest(SimpleTestCase): VALID_CACHES_CONFIGURATION = { 'default': { 'BACKEND': 'django.core.cache.ba...
863b94ddf447d5a51641f10c5a41312aa10953ecd03004f1babb4decf678ad10
import sys from io import StringIO from django.apps import apps from django.core import checks from django.core.checks import Error, Warning from django.core.checks.registry import CheckRegistry from django.core.management import call_command from django.core.management.base import CommandError from django.db import m...
c112e7de961b41b72be3776b2f6ea6d08213d38552c77c0b42fe915d670c41b9
from django.conf import settings from django.core.checks.security import base, csrf, sessions from django.test import SimpleTestCase from django.test.utils import override_settings class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[...
7f4f929070fec201a671b02f468e1c2ef48069c28d1b4ae6e05895b78bc9f14b
import os from unittest import mock from django.core.checks.async_checks import E001, check_async_unsafe from django.test import SimpleTestCase class AsyncCheckTests(SimpleTestCase): @mock.patch.dict(os.environ, {'DJANGO_ALLOW_ASYNC_UNSAFE': ''}) def test_no_allowed_async_unsafe(self): self.assertEqu...
aa0892233ad0658d48bb602a9c4c427cfc96a867287c514c5f88a4600e477b62
from unittest import mock from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings class TestRouter: """ Routes to the 'other' database if the model name starts with 'Other'. """ def allow_migrate(self, db, app_labe...
cf9c01384530ccaa8d36dfa21800af2973ec0088e030b2413c61ba2df8f2ffc8
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.urls import ( E006, check_url_config, check_url_namespaces_unique, check_url_settings, get_warning_for_invalid_pattern, ) from django.test import SimpleTestCase from django.test.utils import override_...
77d8dafa922fc3122640732b1f63cd00d5a5214299219db013c74a7f302b9b84
from copy import copy, deepcopy from django.core.checks.templates import ( E001, E002, check_setting_app_dirs_loaders, check_string_if_invalid_is_string, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckTemplateSettingsAppDirsTest(SimpleTestCase): TEMPLA...
c08cf2cfc41bd16a4c15f3145f0372f516df970e82b163c2299d6f9cbf670b0d
import unittest from unittest import mock from django.core.checks.database import check_database_backends from django.db import connection, connections from django.test import TestCase class DatabaseCheckTests(TestCase): databases = {'default', 'other'} @mock.patch('django.db.backends.base.validation.BaseDa...
29abed9ed7d9edde5db87b2204b083975aef9d2d2f2b8d24821af3ad687b7264
import datetime from decimal import Decimal from django.contrib.humanize.templatetags import humanize from django.template import Context, Template, defaultfilters from django.test import SimpleTestCase, modify_settings, override_settings from django.utils import translation from django.utils.html import escape from d...
a714c527d71c50f0bcd9e6e480cf0b624e36e681e04ade37dd6de2e631b9f62d
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotA...
6285093c5f6402d46b1f84ff56ade608ae6c1b903e0c3eb79dc719996df8a8be
import copy import datetime from django.contrib.auth.models import User from django.db import models class RevisionableModel(models.Model): base = models.ForeignKey('self', models.SET_NULL, null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.dateti...
95461c75ffd43a45afaed99ca69c335da043a82339e8805a4cc76fe486ec11f9
import os import shutil import tempfile from django import conf from django.test import SimpleTestCase from django.test.utils import extend_sys_path class TestStartProjectSettings(SimpleTestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup...
4c814a8efbac81f32c12b985444fcfcb0a248bbc065edb364ad9bbe3fa369d9a
""" Giving models a custom manager You can use a custom ``Manager`` in a particular model by extending the base ``Manager`` class and instantiating your custom ``Manager`` in your model. There are two reasons you might want to customize a ``Manager``: to add extra ``Manager`` methods, and/or to modify the initial ``Q...
e18503392a368d68f82c45d2017b8dc21c5a4c2a0be9b3a4a402f0ab796be57e
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import subprocess import sys import tempfile import unittest from io imp...
001f37c1e0b6a582dbea6bdc1706125d9503b0e2988352ee2525b083585cf4d8
from django.contrib import admin from django.test import SimpleTestCase class AdminAutoDiscoverTests(SimpleTestCase): """ Test for bug #8245 - don't raise an AlreadyRegistered exception when using autodiscover() and an admin.py module contains an error. """ def test_double_call_autodiscover(self):...
1eba324b8204bf48980dea7a0bca711602a903ecba4c70c07c5efaa453cd2dd4
from math import ceil from operator import attrgetter from django.db import IntegrityError, NotSupportedError, connection from django.db.models import FileField, Value from django.db.models.functions import Lower from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from ....
aa9eb3a32b8b6ab436b80d1dbb41c41191e9e49720e1608d00bf55a128d33ac2
import datetime import uuid from decimal import Decimal from django.db import models from django.utils import timezone try: from PIL import Image except ImportError: Image = None class Country(models.Model): name = models.CharField(max_length=255) iso_two_letter = models.CharField(max_length=2) ...
a84aaf0ca097da175a76554dcaf48c2a8d320555f78e61ca49095fe5d44501a9
""" Regression tests for Model inheritance behavior. """ import datetime from operator import attrgetter from unittest import expectedFailure from django import forms from django.test import TestCase from .models import ( ArticleWithAuthor, BachelorParty, BirthdayParty, BusStation, Child, Congressman, Derived...
219168c037e3c8aef3b699672a0e7c5008a3803af90252b2c930ffe15826cd27
import datetime from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: ordering = ('name',) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models....
3c8f624afa5a58fa63ad1c51a9e274e0ab0eab88ddf4da1d378ce7be2717928a
import datetime from unittest import mock, skipIf from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( Avg, BooleanField, Case, F, Func, Max, Min, OuterRef, Q, RowRange, Subquery, Sum, Value, ValueRange, When, Window, WindowFrame, ) fr...
8950de2ebcc935f3f13bfc9401d3ed9aa31af8238f87d634eb9e73622c2c7d41
from django.db import models class Classification(models.Model): code = models.CharField(max_length=10) class Employee(models.Model): name = models.CharField(max_length=40, blank=False, null=False) salary = models.PositiveIntegerField() department = models.CharField(max_length=40, blank=False, null=...
0601f8fb0e59d5c47be44e5837f7729c0c0b58cd54b53e037b32f73c833c988f
""" Specifying ordering Specify default ordering for a model using the ``ordering`` attribute, which should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ...
bb074502543333ed05a5812787dbcfd44e5f6c2a99bb4488d4b7e03897ac44ed
""" Many-to-one relationships that can be null To define a many-to-one relationship that can have a null foreign key, use ``ForeignKey()`` with ``null=True`` . """ from django.db import models class Reporter(models.Model): name = models.CharField(max_length=30) class Article(models.Model): headline = mode...
c4056a175bd31313244a630a47f996f67bc0329c8d97e1199accc32a87dd175d
from django.contrib.sessions.middleware import SessionMiddleware from django.middleware.cache import ( CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware, ) from django.middleware.common import CommonMiddleware from django.middleware.security import SecurityMiddleware from django.test import SimpleTes...
2a87cbe7828f806028cc90ca47a265c88f37efccf4852d25abea4b14ef3dcff9
import base64 import hashlib import os import shutil import sys import tempfile as sys_tempfile import unittest from io import BytesIO, StringIO from urllib.parse import quote from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile from django.http.multipartparser i...
6b6b40abc1bac1cfcec840feea18a84077140fd93897460881d5e48d5488ef21
import hashlib import os from django.core.files.uploadedfile import UploadedFile from django.http import HttpResponse, HttpResponseServerError, JsonResponse from .models import FileModel from .tests import UNICODE_FILENAME, UPLOAD_TO from .uploadhandler import ErroringUploadHandler, QuotaUploadHandler def file_uplo...
b5616beedd60005330f9ec4c9cd1030aa61c8660b7f4d94942e8f57e9777ad2b
from django.contrib.flatpages.models import FlatPage from django.test import SimpleTestCase, override_settings from django.test.utils import override_script_prefix class FlatpageModelTests(SimpleTestCase): def setUp(self): self.page = FlatPage(title='Café!', url='/café/') def test_get_absolute_url_u...
9a7d8c15006b19d588a848475babd51f0bf3cab1f4cbaf757368ad89cf31cfc1
from django.contrib.flatpages import views from django.urls import path urlpatterns = [ path('flatpage/', views.flatpage, {'url': '/hardcoded/'}), ]
0664529e1dc6595bdd5b785c95763f6eb873fc3b48175f90d42a9bfe23281027
from django.urls import include, path urlpatterns = [ path('flatpage', include('django.contrib.flatpages.urls')), ]
c687fe7af11f30a26bafa9ef54e992c8085d96885deab515a323797706b3a49a
from django.contrib.flatpages.sitemaps import FlatPageSitemap from django.contrib.sitemaps import views from django.urls import include, path urlpatterns = [ path( 'flatpages/sitemap.xml', views.sitemap, {'sitemaps': {'flatpages': FlatPageSitemap}}, name='django.contrib.sitemaps.views.sitem...
1886e9df9eb905e50bf82da6bff46e3f35015d099f45b1ed01983a5a82f8b4fd
from django.apps import apps from django.contrib.sites.models import Site from django.test import TestCase from django.test.utils import modify_settings, override_settings @override_settings( ROOT_URLCONF='flatpages_tests.urls', SITE_ID=1, ) @modify_settings( INSTALLED_APPS={ 'append': ['django.co...
fa31ac8c110f9d935bf799d4b7c464fcc87c79c6dd73e6a6a62f66ba440baf76
""" Many-to-many relationships via an intermediary table For many-to-many relationships that need extra fields on the intermediary table, use an intermediary model. In this example, an ``Article`` can have multiple ``Reporter`` objects, and each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` f...
037ed93e0dbfd5996771792d8a287407b8311bf5f2de29d19d896cfe3f14b6fe
import datetime from django import forms from django.core.exceptions import ValidationError from django.forms.models import ModelChoiceIterator from django.forms.widgets import CheckboxSelectMultiple from django.template import Context, Template from django.test import TestCase from .models import Article, Author, Bo...
7432618d1acdb5684571f0f548c3af4d9431d2a5f8e8fdabd481302ba04c6fc0
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.db import connec...
6cc0a406c1337b3c7d630cf088e5fdf458505c27c92b98f5a8fb451cf1c77cf0
import datetime import os import tempfile import uuid from django.core import validators from django.core.exceptions import ValidationError from django.core.files.storage import FileSystemStorage from django.db import models temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) cl...
7587f38c6321616ba4062369134e2c8eba12986ae9f7bb5b127dfa856ef4a44d
""" This is a basic model to test saving and loading boolean and date-related types, which in the past were problematic for some database backends. """ from django.db import models class Donut(models.Model): name = models.CharField(max_length=100) is_frosted = models.BooleanField(default=False) has_sprin...
7e68bcc4560d5543a97c5c684f3e0eade2c342ffd84321ea6fb0b3a2451d01a9
import copy from django.contrib.gis.db.models import GeometryField from django.contrib.gis.db.models.sql import AreaField, DistanceField from django.test import SimpleTestCase class FieldsTests(SimpleTestCase): def test_area_field_deepcopy(self): field = AreaField(None) self.assertEqual(copy.dee...
88617e43ec925dc0afeddda43276b4ea4df3f9304708e2c6a2e8b4e1f71312c0
from django.db import connection, models from django.test import SimpleTestCase from .utils import FuncTestMixin def test_mutation(raises=True): def wrapper(mutation_func): def test(test_case_instance, *args, **kwargs): class TestFunc(models.Func): output_field = models.Intege...
3d59e89557bc89e2332dd09ea1e72a170fd79bc0e0fade525684669785a2307e
import copy import unittest from functools import wraps from unittest import mock from django.conf import settings from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Func def skipUnlessGISLookup(*gis_lookups): """ Skip a test unless a database supports all of gis_lookups. """...
8d19dec077592d9fcc928137b992ac87c2de64ffc7827e826f90b8a2b20bf9fb
import re from django.contrib.gis import forms from django.contrib.gis.forms import BaseGeometryWidget, OpenLayersWidget from django.contrib.gis.geos import GEOSGeometry from django.core.exceptions import ValidationError from django.test import SimpleTestCase, override_settings from django.utils.html import escape c...
663f56bff4165655a6de1f901bc5d66bd1e84d67fad0f431392e5ae14c12293f
import datetime import pytz from django.test import TestCase, override_settings from django.utils import timezone from .models import Article, Category, Comment class DateTimesTests(TestCase): def test_related_model_traverse(self): a1 = Article.objects.create( title="First one", ...
6cd4641a606d1ea58a879fc0ef335b0f348ec336649e4e37d3fca8d156f28249
from math import ceil from django.db import connection, models from django.db.models import ProtectedError, RestrictedError from django.db.models.deletion import Collector from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .mo...
1d5b842139ed17a5cc568dc7f3c53a90fe4119435d9de08f3ff6470335eca3b8
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class P(models.Model): pass class R(models.Model): is_default = models.BooleanField(default=False) p = models.ForeignKey(P, m...
3f4799157372fc66b6d07017c78c4f4b089fbc786aa6a7141afba5f4e3b5f01c
from unittest import mock from django.core.checks import Error, Warning as DjangoWarning from django.db import connection, models from django.test.testcases import SimpleTestCase from django.test.utils import isolate_apps, override_settings @isolate_apps('invalid_models_tests') class RelativeFieldTests(SimpleTestCas...
dbbc683ad55a962b7b5005356eb122d0707f0cbc1d455842449b4b1e92a2d799
from unittest import mock from django.core.checks import Error from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps def dummy_allow_migrate(db, app_label, **hints): # Prevent checks from being run on the 'other' database, which doesn't have ...
6c6594ba66a85abe621a0a0dc5fb02051d01a5b973d729d66cb34db3fb1e0e0a
import unittest from django.core.checks import Error, Warning from django.core.checks.model_checks import _check_lazy_references from django.db import connection, connections, models from django.db.models.functions import Lower from django.db.models.signals import post_init from django.test import SimpleTestCase, Test...
3c6c2a34590e51c169e8dc12b5589a3db50b28061f65f5c5e905dd15a92ffbde
from django.core import checks from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps('invalid_models_tests') class DeprecatedFieldsTests(SimpleTestCase): def test_IPAddressField_deprecated(self): class IPAddressModel(models.Model): ...
cd22f3ca1b4920852a0de99aee1db598015d7bffaad0a3c31fadb05e5e2cb2d4
import unittest import uuid from django.core.checks import Error, Warning as DjangoWarning from django.db import connection, models from django.test import ( SimpleTestCase, TestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import isolate_apps, override_settings from django.utils.functional ...
5db689da999484794cbf98601e092003b3c4e5613db2fb8036cd9870299cb692
import asyncore import base64 import mimetypes import os import shutil import smtpd import sys import tempfile import threading from email import charset, message_from_binary_file, message_from_bytes from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr from io import St...
5b071b58eb539b13284aeddb2ab5919ee5d6176006da929678a3a508941de804
import datetime from decimal import Decimal from django.db.models import ( AutoField, BinaryField, BooleanField, CharField, DateField, DateTimeField, DecimalField, EmailField, FileField, FilePathField, FloatField, GenericIPAddressField, ImageField, IntegerField, IPAddressField, NullBooleanField, Positi...
264ad88855f325bcecbd7dbfb8bc4174a19493878e1aea555519210ff57f5648
from decimal import Decimal from django.apps import apps from django.core import checks from django.core.exceptions import FieldError from django.db import models from django.test import TestCase, skipIfDBFeature from django.test.utils import isolate_apps from .models import Bar, FkToChar, Foo, PrimaryKeyCharModel ...
d3962b5e7e0f2e1f10ff865cf35d7e0ee4aa460ea320b1b9d543aaab8d6608a1
import pickle from django import forms from django.core.exceptions import ValidationError from django.db import models from django.test import SimpleTestCase, TestCase from django.utils.functional import lazy from .models import ( Bar, Choiceful, Foo, RenamedField, VerboseNameField, Whiz, WhizDelayed, WhizIte...
67a85e6ffb9710f2ffdaf4a128ffb64158eb377a384dd66490feb357345078e0
import operator import uuid from unittest import mock, skipIf, skipUnless from django import forms from django.core import serializers from django.core.exceptions import ValidationError from django.core.serializers.json import DjangoJSONEncoder from django.db import ( DataError, IntegrityError, NotSupportedError, ...
4966a79f42af4b5102d7a6ae0a632f62c298324f74061b3f6a29010db4c00e3f
import json import os import tempfile import uuid from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.core.files.storage import FileSystemStorage from django.core.serializers.json import DjangoJSONEncoder from...
e12926997b5676b0a19b98f9943027da533f05538f302fd11d704a844f708597
from django import test from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.db import models from .models import AllFieldsModel NON_CONCRETE_FIELDS = ( models.ForeignObject, GenericForeignKey, GenericRelation, ) NON_EDITABLE_FIELDS = ( models.BinaryF...
2e7470ff469a5ad54800772d8a8eb2cd5bd474c7b3fa3df6620e14f34a3915eb
import os import pickle import sys import tempfile import unittest from pathlib import Path from django.core.files import File, temp from django.core.files.base import ContentFile from django.core.files.uploadedfile import TemporaryUploadedFile from django.db import IntegrityError from django.test import TestCase, ove...
a5671f1de5b25d72a937347a4fdf3e9ab5861866b2ab62a1730217662eabc769
from unittest import mock from django.core.exceptions import ValidationError from django.db import IntegrityError, connection, models from django.db.models.constraints import BaseConstraint from django.db.transaction import atomic from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models impo...
50302be4cab9bfe9283262380102032372abbd9b199e60a86acab0031e49f294
from django.db import models class Product(models.Model): price = models.IntegerField(null=True) discounted_price = models.IntegerField(null=True) class Meta: required_db_features = { 'supports_table_check_constraints', } constraints = [ models.CheckConstra...
f82e944855097f3b688bd2284afaf3e1320d71b5024e2a7efd88838bb83a3dee
import datetime import pickle import unittest import uuid from copy import deepcopy from unittest import mock from django.core.exceptions import FieldError from django.db import DatabaseError, NotSupportedError, connection from django.db.models import ( Avg, BooleanField, Case, CharField, Count, DateField, DateTim...
17b082fedf8f7129d41e410de1dbdb9e8abb51401c45d05a62f8d4d196d46a1a
""" Tests for F() query expression syntax. """ import uuid from django.db import models class Manager(models.Model): name = models.CharField(max_length=50) class Employee(models.Model): firstname = models.CharField(max_length=50) lastname = models.CharField(max_length=50) salary = models.IntegerFie...
9081526237379698582b9d1afdcbdae56326736c9ce3936262e970554ba51250
from django.db.models import F, Sum from django.test import TestCase from .models import Company, Employee class ValuesExpressionsTests(TestCase): @classmethod def setUpTestData(cls): Company.objects.create( name='Example Inc.', num_employees=2300, num_chairs=5, ceo=Employee.o...
0c3b5fad55db85e86bdce922cbc3fd7c386878780ee95cc75996f056f832a749
import io from django.core.management import call_command from django.test import TestCase class CoreCommandsNoOutputTests(TestCase): available_apps = ['empty_models'] def test_sqlflush_no_tables(self): out = io.StringIO() err = io.StringIO() call_command('sqlflush', stdout=out, stde...
57196ee15974df6105b75dced95e918e3e04798e108a3655cc1c957162aeccc8
import datetime from operator import attrgetter from django.core.exceptions import FieldError from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from django.utils import translation from .models import ( Article, ArticleIde...
18b78c056f18f91781759f7e340e24fd5f3c901b6fd65e30c8c44ff7aac54ec1
import datetime import re import sys from contextlib import contextmanager from unittest import SkipTest, skipIf from xml.dom.minidom import parseString import pytz from django.contrib.auth.models import User from django.core import serializers from django.db import connection from django.db.models import F, Max, Min...
92382f46fb90da1da42897620377a85ec1849ba57167f433f9bd5f9c52a57947
from django.db import models from django.utils import timezone class Article(models.Model): title = models.CharField(max_length=100) pub_date = models.DateField() pub_datetime = models.DateTimeField(default=timezone.now) categories = models.ManyToManyField("Category", related_name="articles") class...
ac1a2583c5e7ba7ce31766010d9e820cb8dd03f285fd0a81e65548b512ad3d9e
from django.contrib.sites.managers import CurrentSiteManager from django.contrib.sites.models import Site from django.db import models class AbstractArticle(models.Model): title = models.CharField(max_length=50) objects = models.Manager() on_site = CurrentSiteManager() class Meta: abstract =...
263f28589e41d6dd679f868c3ee304d8b165746bf38d5bcadf658524adf50c92
from unittest import mock from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ObjectDoesNotExist from django.db import connection from django.db.models import Prefetch, QuerySet, prefetch_related_objects from django.db.models.query import get_prefetcher from django.db.models.s...