From c7294614795a3c0b3a872707bbea93733ef2077d Mon Sep 17 00:00:00 2001 From: Horst Gutmann Date: Sun, 24 Feb 2013 15:54:09 +0100 Subject: [PATCH] Fixed #17320 -- Added whitespace validation to the Site.domain field --- django/contrib/sites/models.py | 19 ++++++++++++++++++- django/contrib/sites/tests.py | 12 +++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py index 88a7c4115b..1ce9bf3185 100644 --- a/django/contrib/sites/models.py +++ b/django/contrib/sites/models.py @@ -1,12 +1,28 @@ +import string + from django.db import models from django.db.models.signals import pre_save, pre_delete from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible +from django.core.exceptions import ValidationError SITE_CACHE = {} +def _simple_domain_name_validator(value): + """ + Validates that the given value contains no whitespaces to prevent common + typos. + """ + if not value: + return + checks = ((s in value) for s in string.whitespace) + if any(checks): + raise ValidationError( + _(u"The domain name cannot contain any spaces or tabs.")) + + class SiteManager(models.Manager): def get_current(self): @@ -37,7 +53,8 @@ class SiteManager(models.Manager): @python_2_unicode_compatible class Site(models.Model): - domain = models.CharField(_('domain name'), max_length=100) + domain = models.CharField(_('domain name'), max_length=100, + validators=[_simple_domain_name_validator]) name = models.CharField(_('display name'), max_length=50) objects = SiteManager() diff --git a/django/contrib/sites/tests.py b/django/contrib/sites/tests.py index ee6224bc7a..6bfbfd7cf2 100644 --- a/django/contrib/sites/tests.py +++ b/django/contrib/sites/tests.py @@ -2,7 +2,7 @@ from __future__ import unicode_literals from django.conf import settings from django.contrib.sites.models import Site, RequestSite, get_current_site -from django.core.exceptions import ObjectDoesNotExist +from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.http import HttpRequest from django.test import TestCase from django.test.utils import override_settings @@ -71,3 +71,13 @@ class SitesFrameworkTests(TestCase): site = get_current_site(request) self.assertTrue(isinstance(site, RequestSite)) self.assertEqual(site.name, "example.com") + + def test_domain_name_with_whitespaces(self): + # Regression for #17320 + # Domain names are not allowed contain whitespace characters + site = Site(name="test name", domain="test test") + self.assertRaises(ValidationError, site.full_clean) + site.domain = "test\ttest" + self.assertRaises(ValidationError, site.full_clean) + site.domain = "test\ntest" + self.assertRaises(ValidationError, site.full_clean)