hash
stringlengths
64
64
content
stringlengths
0
1.51M
92cd488ca8d6f7b783ddc6fddeedb0a44aafb450ef3568dd71aa8aafe7ced4d8
import unittest from django.core.exceptions import ValidationError class TestValidationError(unittest.TestCase): def test_messages_concatenates_error_dict_values(self): message_dict = {} exception = ValidationError(message_dict) self.assertEqual(sorted(exception.messages), []) mes...
7f37c418bc07c8711746e99cacca98be9c9fd6e2d8f2760f1e4fcd094c90f472
from datetime import datetime from django.contrib.sitemaps import GenericSitemap from django.test import override_settings from .base import SitemapTestsBase from .models import TestModel @override_settings(ABSOLUTE_URL_OVERRIDES={}) class GenericViewsSitemapTests(SitemapTestsBase): def test_generic_sitemap_at...
a4163dbfe4a12e71196daeda3f6e49311a53132445d5f82165ffc8c8d35a352f
from unittest import mock from urllib.parse import urlencode from django.contrib.sitemaps import ( SitemapNotFound, _get_sitemap_full_url, ping_google, ) from django.core.exceptions import ImproperlyConfigured from django.test import modify_settings, override_settings from .base import SitemapTestsBase class Pi...
d3a4313a6878ab4241470633d928af1357336d8397e57311491ab5baaa250384
from datetime import date from django.test import override_settings from .base import SitemapTestsBase @override_settings(ROOT_URLCONF='sitemaps_tests.urls.https') class HTTPSSitemapTests(SitemapTestsBase): protocol = 'https' def test_secure_sitemap_index(self): "A secure sitemap index can be rende...
61c71caf091d861f29dbc1e2b288d4fe5f23d677d85f0c1ed77700763407ec9d
from django.db import models from django.urls import reverse class TestModel(models.Model): name = models.CharField(max_length=100) lastmod = models.DateTimeField(null=True) def get_absolute_url(self): return '/testmodel/%s/' % self.id class I18nTestModel(models.Model): name = models.CharFi...
f917257c27c680700bf685cf2374f195a3f3a4cf90cf51b940c2f81b5144bf6c
from unittest import mock from django.core.management import call_command from .base import SitemapTestsBase @mock.patch('django.contrib.sitemaps.management.commands.ping_google.ping_google') class PingGoogleTests(SitemapTestsBase): def test_default(self, ping_google_func): call_command('ping_google') ...
21b6c08ea888e181f9f30211d56707983206f50c6c0fef2de3babaf8ebb8c08a
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={'append': 'django.contrib.sitemaps'}) @override_settings(ROO...
c98bdbc59a4e0382843df07901c614f3482455e870d4cfa60e5b5342c616f555
import os from datetime import date from unittest import skipUnless from django.apps import apps from django.conf import settings from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.test import modify_settings, ove...
e17b99e3f0f1f01f23c4b33ed9700b8cc2b7a9c0122ce006c1e40238cb229a55
from django.core.exceptions import FieldError from django.test import TestCase from .models import Choice, Inner, OuterA, OuterB, Poll class NullQueriesTests(TestCase): def test_none_as_null(self): """ Regression test for the use of None as a query value. None is interpreted as an SQL N...
9ea3196eeea591f534bfcc87c4ce02e7f4e86260fa33a8ae96d50bbfda9890e7
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) def __str__(self): return "Q: %s " % self.question class Choice(models.Model): poll = models.ForeignKey(Poll, models.CASCADE) choice = models.CharField(max_length=200) def __str__(self): ...
ffe059f46369fe8ece1f7bacba07db3aec5cf35994f7cb7aaab70776e42d056e
"""Tests for django.db.utils.""" import unittest from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS, connection from django.db.utils import ConnectionHandler, ProgrammingError, load_backend from django.test import SimpleTestCase, TestCase class ConnectionHandlerTests(Simpl...
1e27918b743123a01c9aaf66b5b5c58cb2bd4f0f7488a922512a9cd160a8c242
from django.http import Http404 from django.shortcuts import get_list_or_404, get_object_or_404 from django.test import TestCase from .models import Article, Author class GetObjectOr404Tests(TestCase): def test_get_object_or_404(self): a1 = Author.objects.create(name="Brave Sir Robin") a2 = Autho...
addcc2612b850526dc781649385d46805703a7a646da0b725e60b4049154ac8c
""" 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...
01a4e21d8ec31e81713608e8b58abf4b5f6fbfdcd63239c51d3ff0b9d343c1ad
import datetime from django.db import models from django.test import TestCase from django.test.utils import isolate_apps from .models import InternationalArticle class SimpleTests(TestCase): def test_international(self): a = InternationalArticle.objects.create( headline='Girl wins €12.500 i...
46e1c1a4d14d7dc4b94026d2c0b3b6a11209f1155998e87509516f03bb8455bd
""" Adding __str__() to models Although it's not a strict requirement, each model should have a ``_str__()`` method to return a "human-readable" representation of the object. Do this not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Dja...
3f50795f2b089b5aeb1a1249d200addd17e5b69ce5ce150b7ee1cb5a41cf7b91
import datetime from django.db import connection, models, transaction from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import ( Award, AwardNote, Book, Child, Contact, Eaten, Email, File, Food, FooFile, FooFileProxy, FooImage, FooPhoto, House, Image, Item, Location, Logi...
b0a7b67aa36a50c3b757a666318c868fdd173153c13f9df677208c6f4edc97c3
from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = mode...
b8c78ad03297afba5743cd99d850e80de5535fc56bb1f87b84c87d06eb2bb3f1
from django.contrib.auth.backends import ModelBackend class TestClientBackend(ModelBackend): pass class BackendWithoutGetUserMethod: pass
23bc1081f422947eb5dca3f7be197f3ddfe5f9af22536a97e5f8ed46c92c7f99
""" 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...
7832b1c57d9f1fa6ac44a246d0a8f799e4eedd79fb68f77daadf01865432cd82
import gzip from django.http import HttpRequest, HttpResponse, StreamingHttpResponse from django.test import SimpleTestCase from django.test.client import conditional_content_removal class ConditionalContentTests(SimpleTestCase): def test_conditional_content_removal(self): """ Content is removed...
a17c43a8e004c96c3b6a36b9671e947917940db6a1680ccef5f29962314beb04
from django.conf.urls import url from django.contrib.auth import views as auth_views from django.views.generic import RedirectView from . import views urlpatterns = [ url(r'^upload_view/$', views.upload_view, name='upload_view'), url(r'^get_view/$', views.get_view, name='get_view'), url(r'^post_view/$', v...
0d4b55dc3f0a613b547c45d44e44f374d94da3377c2d7bb345b425f7ee7577ca
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.forms import fields from django.forms.forms import Form, ValidationError from django.forms.formsets import BaseF...
de74b9bb42684a6957434b1771d33ea8962b48585a2d9f8549d5c41d8c702148
from django.conf.urls import url from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.test import SimpleTestCase, modify_settings, override_settings class MiddlewareAccessingContent: def __init__(self, get_response): self.get_response = get_...
390b87a7ef0a490ed0a74c167c7c3b1563a0c4883cdd33058baf7ad417772651
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, ...
dab9bfd217a98f43f6c1c41bcae1a50206c8bc56b4adb15bff9dc1190b4714ba
from django.core.handlers.wsgi import WSGIHandler from django.test import SimpleTestCase, override_settings from django.test.client import FakePayload class ExceptionHandlerTests(SimpleTestCase): def get_suspicious_environ(self): payload = FakePayload('a=1&a=2;a=3\r\n') return { 'REQU...
29cc0bc28c9ee54ca335fa33ea24b634666e340a3af19d1f32107ce9ea9641aa
from django.conf.urls import url from . import views urlpatterns = [ url(r'^regular/$', views.regular), url(r'^streaming/$', views.streaming), url(r'^in_transaction/$', views.in_transaction), url(r'^not_in_transaction/$', views.not_in_transaction), url(r'^suspicious/$', views.suspicious), url(...
cf814ca10945e424481867232d1ef1fdb5c9e9d02a4573adcc376f7f9caf76f3
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 content") def str...
05fcae709b23df0fecb9121c21596410dd1f31cd78e17e3ed370e985ec74ae32
from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections from django.test import SimpleTestCase, override_se...
dd7dafa5eedb4949272c51df854fcb09ab8a2d84dc8be9280f59ea8c3f9e3e6d
# This is just to test finding, it doesn't have to be a real WSGI callable application = object()
888befea6ed7973fb6a86e1eb383164320569f229fd6d3e817183abb4be9f7e7
from django.conf.urls import url from django.http import FileResponse, HttpResponse def helloworld(request): return HttpResponse("Hello World!") urlpatterns = [ url("^$", helloworld), url(r'^file/$', lambda x: FileResponse(open(__file__, 'rb'))), ]
41e66ced9ce11fda83eb5336918194967ebea6cc46da10522bc33f732d61c6fb
from django.db.backends.ddl_references import ( Columns, ForeignKeyName, IndexName, Statement, Table, ) from django.test import SimpleTestCase class TableTests(SimpleTestCase): def setUp(self): self.reference = Table('table', lambda table: table.upper()) def test_references_table(self): s...
302b77e0ed7d0128ce4ff0e0036533ca889832e8dcdaaa1901b0436f5edd46dc
"""Tests for django.db.backends.utils""" from decimal import Decimal, Rounded from django.db import connection from django.db.backends.utils import ( format_number, split_identifier, truncate_name, ) from django.db.utils import NotSupportedError from django.test import ( SimpleTestCase, TransactionTestCase, sk...
9f5b05c9ce50e174a3d8b7a378e40ecd4a698149f93aed17004f214b932dc6d3
"""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,...
b9ef8d1e7e71c1899979a19cddded1727e070d3d9c6b8f427cfb961b06863f2b
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...
8820f4503b36f372acdcf5662d6a7c344c337f86652bab4085e6a1d8ada1cb47
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return ( self.__class__.__name__, [], {} ) @property def reversible(self): return True d...
c2f70440821fbea73851e15372cbd1d310b92f6f78f54da6885d16a965e3ccc8
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return ( self.__class__.__name__, [], {} ) @property def reversible(self): return True d...
86d9491c2c29b03368ea48c2c22980baff84828fed59cfd87517e0ff29862a7c
from django.db import models from django.template import Context, Template from django.test import TestCase, override_settings from django.test.utils import isolate_apps from .models import ( AbstractBase1, AbstractBase2, AbstractBase3, Child1, Child2, Child3, Child4, Child5, Child6, Child7, RelatedModel, Rela...
5ef172070ee4b8529c14765db8c58cec21f1896db303f3af6ffb30a51ac67585
""" Various edge-cases for model managers. """ from django.contrib.contenttypes.fields import ( GenericForeignKey, GenericRelation, ) from django.contrib.contenttypes.models import ContentType from django.db import models class OnlyFred(models.Manager): def get_queryset(self): return super().get_quer...
9067b5f22f01f35554b8d33b18389c0b6853992ce5d796265cf79eab4d782131
import datetime import itertools import unittest from copy import copy from unittest import mock from django.db import ( DatabaseError, IntegrityError, OperationalError, connection, ) from django.db.models import Model from django.db.models.deletion import CASCADE, PROTECT from django.db.models.fields import ( ...
bd7c4e2091b6bb87ced543e286686edd864c5f4fd0ce5b66fea1048358e44712
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...
64f7b1fb53cdfb3f1e0ede403581040372720579c389c6ce29210de974dd6cbb
from django.db import connection from django.test import TestCase class SchemaLoggerTests(TestCase): def test_extra_args(self): editor = connection.schema_editor(collect_sql=True) sql = 'SELECT * FROM foo WHERE id in (%s, %s)' params = [42, 1337] with self.assertLogs('django.db.ba...
522f20f4f6ec6f2bfedd0a7a82973e39a6e8b5c6cbc8fd984b48d53102eb24e2
from functools import partial from django.db import models from django.db.models.fields.related import ( RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor, ManyToManyField, ManyToManyRel, RelatedField, create_many_to_many_intermediary_model, ) class CustomManyToManyField(RelatedField): """ Ticket...
797cf796271f2856911a15695c457210a8b3b0b4a4a373ad4c777d1bb028c2d5
from django.test import TestCase from .models import Organiser, Pool, PoolStyle, Tournament class ExistingRelatedInstancesTests(TestCase): @classmethod def setUpTestData(cls): cls.t1 = Tournament.objects.create(name='Tourney 1') cls.t2 = Tournament.objects.create(name='Tourney 2') cl...
5f22eec1bc669426856a403963ecc1e3bf3bfac2b82aa860a0151c85447a6ceb
""" Existing related object instance caching. Queries are not redone when going back through known relations. """ from django.db import models class Tournament(models.Model): name = models.CharField(max_length=30) class Organiser(models.Model): name = models.CharField(max_length=30) class Pool(models.Mo...
7f5cf3860e3d4ecdc378a66f8d44698176e8755c8b220414b6ce9d3f671f1d10
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...
025052219f3960e37f80eb61fbabe55bf2a24cb6c133f28bf33c730de1180fdb
""" 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...
bdbfb26063df1ecc9a2379075df14655db872b2c83d769af52d35c6e1708d69a
from django import forms from django.contrib import admin from django.db import models from .models import ( Author, BinaryTree, CapoFamiglia, Chapter, ChildModel1, ChildModel2, Consigliere, EditablePKBook, ExtraTerrestrial, Fashionista, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stack...
e3832563d4f8e0729c640bf447719a43f447885f63ec1acc4c24a83ded3f34ff
from django.conf.urls import url from . import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ]
5d3e27c0a73eedabbd5c47f45a415e35e7601b59beb9387ee5e73d42880dfb66
import json from django.template.loader import render_to_string from django.test import SimpleTestCase class TestTemplates(SimpleTestCase): def test_javascript_escaping(self): context = { 'inline_admin_formset': { 'inline_formset_data': json.dumps({ 'formse...
bcb721b8c2b19f689954e7dae6a38a2b889cc99c3807700295502a9cab644aa4
from datetime import date from django.test import TestCase from .models import Article class MethodsTests(TestCase): def test_custom_methods(self): a = Article.objects.create( headline="Parrot programs in Python", pub_date=date(2005, 7, 27) ) b = Article.objects.create( ...
5c2ce9938f0b2e194f098eecde72e8a78d1b485573624fba40d0fe82b9d1b373
""" Giving models custom methods Any method you add to a model will be available to instances. """ import datetime from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __str__(self): return self.headline de...
f9a6d3af254191063b85cd922efe216da6ee8def81e1b7945766ee6e26806252
from django.db import connection from django.db.models import Max from django.test import TestCase from .models import Cash, CashModel class FromDBValueTest(TestCase): def setUp(self): CashModel.objects.create(cash='12.50') def test_simple_load(self): instance = CashModel.objects.get() ...
2d97dfd29c5c58b94429ae25e44eff6c2cb5f26b68cfa81e57fc3b4d5d12fea3
from django.test import TestCase from django.utils.deprecation import RemovedInDjango30Warning from .models import Cash, CashModelDeprecated class FromDBValueDeprecationTests(TestCase): def test_deprecation(self): msg = ( 'Remove the context parameter from CashFieldDeprecated.from_db_value()...
43580b9519367a1a9a0547f8b210c4106813667ff9d6dd9caeb432d9fe31c4f7
import decimal from django.db import models class Cash(decimal.Decimal): currency = 'USD' def __str__(self): s = super().__str__(self) return '%s %s' % (s, self.currency) class CashField(models.DecimalField): def __init__(self, **kwargs): kwargs['max_digits'] = 20 kwarg...
1f64c0be009a74c8e077577613fa63b055ce6c68a14ca3fac1310e221bbbcf98
from django.apps import apps from django.test import SimpleTestCase class NoModelTests(SimpleTestCase): def test_no_models(self): """It's possible to load an app with no models.py file.""" app_config = apps.get_app_config('no_models') self.assertIsNone(app_config.models_module)
98c226d553e03113a24d6992cd2a5afae3558d3cf907b2ff57a9bf6766e6340d
from django.core.checks.caches import E001 from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCacheSettingsAppDirsTest(SimpleTestCase): VALID_CACHES_CONFIGURATION = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', ...
78fb4802e05493e63768e11538343e889b4bd9f7380a320e3da8bbd49c24cfc0
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...
e70b1b2052ed0a328a67bf87617e5b3a86849c3298ec23ddd365ae71c564c0ca
from django.core.checks import register from django.db import models class SimpleModel(models.Model): field = models.IntegerField() manager = models.manager.Manager() @register('tests') def my_check(app_configs, **kwargs): my_check.did_run = True return [] my_check.did_run = False
f52a35fb8f15f6a63c3f7e762b9d0a845188d7dbce80a6388ce772d855f6b561
from django.core import checks from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps('check_framework') class TestDeprecatedField(SimpleTestCase): def test_default_details(self): class MyField(models.Field): system_check_de...
287204b618c4c49e3f0b8b620224acca6ffd74fb064ecc558e473ee3896aa34c
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): @property def func(self): from django.core.checks.security.sessions i...
c8fb4cf8135bf3f348143879195d62428c1a4ac137349bf6dbdbfec99e4fb797
from unittest import mock from django.db import connections, models from django.test import TestCase 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_label, mod...
714aea5469af0b608c8bc644ea2c0f97e193a9e33c180fa8636692510c297f58
from django.conf import settings from django.core.checks.messages import 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_setting...
a2f0d3035ae7d083c02c49fe3463f3dbae7e18ed9eea73d22493e47f3d0a0f5c
from copy import copy, deepcopy from django.core.checks.templates import E001, E002 from django.test import SimpleTestCase from django.test.utils import override_settings class CheckTemplateSettingsAppDirsTest(SimpleTestCase): TEMPLATES_APP_DIRS_AND_LOADERS = [ { 'BACKEND': 'django.template.b...
b33ad4dd79bd6c29d5a5dc76a36f6d1ff21f5eefa43804e13737d8b7153f1d17
import unittest from unittest import mock from django.core.checks import Tags, run_checks from django.core.checks.registry import CheckRegistry from django.db import connection from django.test import TestCase class DatabaseCheckTests(TestCase): multi_db = True @property def func(self): from dja...
5bfc79262585b03e02d784e5799abe58bf2c153892544718f1a92aeaa9e1a886
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...
27ae938a14c7069127ffe6a69656f1107182fa1ca7c768f258eae1b95196990a
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...
82a2cb8f07a26ee6444937cde435e98cfee222aedfebf4e822bb663edc9f1a45
import datetime from collections import OrderedDict from django.contrib.auth.models import User from django.test import TestCase from .models import Order, RevisionableModel, TestObject class ExtraRegressTests(TestCase): def setUp(self): self.u = User.objects.create_user( username="fred", ...
74658d7e6dc6fa8076bbaa4a691f663d05adcb940974742db65846c2a6a9319b
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...
87b7aeca2bd6faf0916254e1ed11448c0aaf90fff71e4f4ec3dd82fcf50c8875
from django.contrib.admin.utils import quote from django.contrib.auth.models import User from django.template.response import TemplateResponse from django.test import TestCase, override_settings from django.urls import reverse from .models import Action, Car, Person @override_settings(ROOT_URLCONF='admin_custom_urls...
9681e496e78c6bbd434041dc809cb6c3b0172709745f6f069f05af3350c79bdc
from functools import update_wrapper from django.contrib import admin from django.db import models from django.http import HttpResponseRedirect from django.urls import reverse class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) ...
c43bdaeb9454f1429db3c6a56075f63893aadccffee1e15d78f8df46d4fefc9f
from django.conf.urls import url from .models import site urlpatterns = [ url(r'^admin/', site.urls), ]
c5a8e9fed0983182b2ab1d6a9eb4c4d2fcab1b556aaf79858de9f2bed177f05e
import os import shutil import tempfile from django import conf from django.test import TestCase from django.test.utils import extend_sys_path class TestStartProjectSettings(TestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup) te...
5188593bde3ec30dacf291726100beef9a911305c93e42a30cefc694d8a394be
from django.conf.urls import url from . import views urlpatterns = [ url(r'^empty/$', views.empty_view), ]
de0aa746e7b9fc5556731c60f2ccc88eecc9d83369d54bdb95b692729309f178
from datetime import datetime from django.test import SimpleTestCase, override_settings FULL_RESPONSE = 'Test conditional get response' LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47) LAST_MODIFIED_STR = 'Sun, 21 Oct 2007 23:21:47 GMT' LAST_MODIFIED_NEWER_STR = 'Mon, 18 Oct 2010 16:56:23 GMT' LAST_MODIFIED_INVALID...
ecb713c67b458953c5efd0df8db6ff02a70d56fbe73e8ad63cd2a66917f880ed
from django.conf.urls import url from . import views urlpatterns = [ url('^condition/$', views.index), url('^condition/last_modified/$', views.last_modified_view1), url('^condition/last_modified2/$', views.last_modified_view2), url('^condition/etag/$', views.etag_view1), url('^condition/etag2/$', ...
fc1ac1513d571765d7393da26637b90ce6f7dcfc0c588f02ea2a8958131050a3
from django.http import HttpResponse from django.views.decorators.http import condition, etag, last_modified from .tests import ETAG, FULL_RESPONSE, LAST_MODIFIED, WEAK_ETAG @condition(lambda r: ETAG, lambda r: LAST_MODIFIED) def index(request): return HttpResponse(FULL_RESPONSE) @condition(last_modified_func=...
5f670d919d8a2fef795cf5234e0a02f8fff58f6b2f048e8b5aa662b0eed3572a
from datetime import datetime from django.test import TestCase from .models import Article class DefaultTests(TestCase): def test_field_defaults(self): a = Article() now = datetime.now() a.save() self.assertIsInstance(a.id, int) self.assertEqual(a.headline, "Default head...
218e2b50ffa8b0d2b36eef15c9fe8448ae62021b804023a3b98e9e5b08b6142a
""" Callable defaults You can pass callable objects as the ``default`` parameter to a field. When the object is created without an explicit value passed in, Django will call the method to determine the default value. This example uses ``datetime.datetime.now`` as the default for the ``pub_date`` field. """ from date...
b18553ba17faeba2d4501f35d584aec3bdee532a997fcb41e9fd60e4dd2b700f
from django.db import models from django.test import TestCase from .models import ( Book, Car, CustomManager, CustomQuerySet, DeconstructibleCustomManager, FastCarAsBase, FastCarAsDefault, FunPerson, OneToOneRestrictedModel, Person, PersonFromAbstract, PersonManager, PublishedBookManager, RelatedModel,...
6251120e3ca0b6417054867ce68a03013b3645260cdbcd086da437370c9ff3b5
""" 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...
69be967dbfcf582ef7c2ebcfdd263e9ec5245a5fa1d348eba3d5bbfc44647ac8
""" 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 codecs import os import re import shutil import socket import subprocess import sys import tempfile import unitte...
ed817f34207e6b3a100539f0982600dcc8d155c9b4b24789952bf39955033b84
import os from django.conf.urls import url from django.views.static import serve here = os.path.dirname(__file__) urlpatterns = [ url(r'^custom_templates/(?P<path>.*)$', serve, { 'document_root': os.path.join(here, 'custom_templates')}), ]
156e1b176f3476f1768878bddebdbeed47ddadf0bdcf1cfbf1890b96bb65306d
import datetime from django.test import TestCase from .models import Thing class ReservedNameTests(TestCase): def generate(self): day1 = datetime.date(2005, 1, 1) Thing.objects.create( when='a', join='b', like='c', drop='d', alter='e', having='f', where=day1, has_hyphen='...
aec346d91c8aea561ebb9fe48949f5b45fbbdc8c82b5206881baf8d013c84b86
""" Using SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name usage. """ from django.db import models class Thing(mo...
b2061a20d1688357cb928058195efd634cf005b29903157a4bdd00a19013f88e
from unittest import TestCase from django.contrib import admin class AdminAutoDiscoverTests(TestCase): """ 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): # The...
364e4cfba318bd4293663eebbe508547e7e741a154dea4643959392502967f6e
from django.db import models class Story(models.Model): title = models.CharField(max_length=10)
7e4baa64abcdc84c3e0e1ad711b8b1c99cd47c8acafea9df146e7e35f064a13d
from django.contrib import admin from .models import Story admin.site.register(Story) raise Exception("Bad admin module")
43a0043ae6d27e9dfbc2cb2d2c04a668a1dfbde47721489d4683c5f691ab26f2
from django.conf import settings from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.redirects.models import Redirect from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseForbidden, HttpRespons...
8a57b0f7bdd0d3ebbf36ce9ee2b3e26c22c8090a635e5d30eb6657ca0ae18f53
from django.conf.urls import url from django.http import HttpResponse urlpatterns = [ url(r'^$', lambda req: HttpResponse('OK')), ]
a754c321ae079ec24206f67a98974617fb0d2d05dba4a857d9d2385ff68967af
from operator import attrgetter from django.db import 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 .models import ( Country, NoFields, NullableFields, Pi...
b1e9b5f8cd46eef9779ce0502ff96316a7631aafbc7192242aa2629cb5ee588c
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) ...
8a985950d218e795603a321429abb0cdd441d90d7a092e45d04b14ebf4576fe5
""" 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, DerivedM, InternalCe...
1c5d9ebbb078ce74a3392ab8e1d1b0bafc49bfc74bdfdff1e7c6c9c88d4598db
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',) def __str__(self): return "%s the place" % self.name class Restaurant(Place): serves_hot_do...
dee8e2f571bf915898587fd251706456697123b8e4f95500d2c4111dfdd1ed60
import datetime from unittest import skipIf, skipUnless from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( F, RowRange, Value, ValueRange, Window, WindowFrame, ) from django.db.models.aggregates import Avg, Max, Min, Sum from django.db.m...
2417b9b100faaf47b0e4f2ddb7f2819be2910fda81d3f5947a10bb4ff62e971f
from django.db import models 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=False) hire_date = models.DateField(blank=False, null=False) def __str__...
3f89d2874100e009a90482c9e7aed52aa21d90a4dd22ddf212dbbae8f71172a9
from datetime import datetime from operator import attrgetter from django.db.models import DateTimeField, F, Max, OuterRef, Subquery from django.db.models.functions import Upper from django.test import TestCase from .models import Article, Author, OrderedByFArticle, Reference class OrderingTests(TestCase): @cl...
172d43b80f4ff0ae379fcf03551554fc2bd96e1038ffb41d1597f1f1b0d815c4
""" 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 ...
efca6d6ce8f452b7fc59acf64d4d569d9cdad4a0d75f2fe8661829d6dd76d971
from django.test import TestCase from .models import Article, Car, Driver, Reporter class ManyToOneNullTests(TestCase): def setUp(self): # Create a Reporter. self.r = Reporter(name='John Smith') self.r.save() # Create an Article. self.a = Article(headline="First", reporter...
fe72160434cc927bf347cca0b72f0f01f1c4943aafb960a247b3ee2e7751265d
""" 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) def __str__(self): return self.name ...
e57f6061230aa8b050af28fcc03af90fb59d838495abf24e02d9f74db7bac136
import warnings from django.test import SimpleTestCase from django.utils.deprecation import ( DeprecationInstanceCheck, RemovedInNextVersionWarning, RenameMethodsBase, ) class RenameManagerMethods(RenameMethodsBase): renamed_methods = ( ('old', 'new', DeprecationWarning), ) class RenameMethodsT...