Example #1
0
def create_default_site(app, created_models, verbosity, **kwargs):
    if Site in created_models:
        if verbosity >= 2:
            print "Creating example.com Site object"
        s = Site(domain="example.com", name="example.com")
        s.save()
    Site.objects.clear_cache()
Example #2
0
    def test_index(self):
        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'pass')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()
        #Create the Post
        post = Post()
        post.title = 'My First post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
        post.slug = 'my-first-post'
        post.site = site
        post.author = author
        post.pub_date = timezone.now()
        post.save()

        # Check the new post saved
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)

        # Fetch the index
        response = self.client.get('/')
        self.assertEquals(response.status_code, 200)

        # check the post title is in the response
        self.assertTrue(post.title in response.content)

        # check whether the post text is in the response
        self.assertTrue(markdown.markdown(post.text) in response.content)

        self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
Example #3
0
    def test_all_post_feed(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the tag
        tag = Tag()
        tag.name = 'python'
        tag.description = 'The Python programming language'
        tag.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()
 
        # Create a post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is my first blog post'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.category = category

        # Save it
        post.save()

        # Add the tag
        post.tags.add(tag)
        post.save()

        # Check we can find it
        all_posts = Post.objects.all()
        self.assertEquals(len(all_posts), 1)
        only_post = all_posts[0]
        self.assertEquals(only_post, post)

        # Fetch the feed
        response = self.client.get('/feeds/posts/')
        self.assertEquals(response.status_code, 200)

        # Parse the feed
        feed = feedparser.parse(response.content)

        # Check length
        self.assertEquals(len(feed.entries), 1)

        # Check post retrieved is the correct one
        feed_post = feed.entries[0]
        self.assertEquals(feed_post.title, post.title)
        self.assertEquals(feed_post.description, post.text)
Example #4
0
    def test_sites_contrib(self):

        site_one = Site.objects.get(pk=1)
        site_two = Site(domain='some.com', name='some.com')
        site_two.save()

        site_two_code = Keycode(site=site_two, provider='google', keycode='222')
        site_two_code.save()

        self.assertIn('222', '%s' % site_two_code)

        tpl = '{% load sitemetrics %}{% sitemetrics %}'

        with override_settings(SITE_ID=1):
            self.assertEqual(render_string(tpl), '')  # Test none code for current site

            site_one_code = Keycode(site=site_one, provider='yandex', keycode='111', active=False)
            site_one_code.save()

            self.assertEqual(render_string(tpl), '')  # Test inactive

            site_one_code.active = True
            site_one_code.save()
            self.assertIn('111', render_string(tpl))  # Test active

            self.assertIn('111', render_string(tpl))  # Test cached hit

        with override_settings(SITE_ID=2):
            self.assertIn('222', render_string(tpl))
Example #5
0
def update_default_site(app, **kwargs):
    """Set the default site from settings.py.

    If your project uses the binalerts app, then it's going to want the domain
    and name in sites set to be whatever is in your settings. On migrations
    seems a good time to do this (We can't do it with a fixture, since it
    won't be the same in all cases, and I don't want the fixture to be an
    ugly file...)

    This function just grabs hold of the first site and changes it, so not very
    subtle!

    """
    if app != "binalerts":
        return

    domain = settings.DOMAIN_NAME
    name = settings.BINS_SITENAME

    s = Site.objects.all()
    if s:
        s = s[0]
        s.domain = domain
        s.name = name
    else:
        s = Site(domain=domain, name=name)
    s.save()
    Site.objects.clear_cache()
Example #6
0
    def test_index(self):
        # create author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # create a site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # create post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)',
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.save()
        all_post = Post.objects.all()
        self.assertEquals(len(all_post), 1)

        # fetch the index
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)

        # check the post title in response
        self.assertTrue(post.title in response.content)

        # check the post date year in response
        self.assertTrue(str(post.pub_date.year) in response.content)
        self.assertTrue(str(post.pub_date.day) in response.content)

        # check the link is markedup as properly
        self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
Example #7
0
def run():

    from django.contrib.auth.models import User

    auth_user_1 = User()
    auth_user_1.username = u"dmsadmin"
    auth_user_1.first_name = u""
    auth_user_1.last_name = u""
    auth_user_1.email = u""
    auth_user_1.set_password("dmsadmin")
    auth_user_1.is_staff = True
    auth_user_1.is_active = True
    auth_user_1.is_superuser = True
    auth_user_1.date_joined = datetime.datetime.now()
    auth_user_1.save()

    auth_user_2 = User()
    auth_user_2.username = u"dmsuser"
    auth_user_2.first_name = u""
    auth_user_2.last_name = u""
    auth_user_2.email = u""
    auth_user_1.set_password("dmsuser")
    auth_user_2.is_staff = False
    auth_user_2.is_active = True
    auth_user_2.is_superuser = False
    auth_user_2.date_joined = datetime.datetime.now()
    auth_user_2.save()

    from django.contrib.sites.models import Site

    django_site_1 = Site()
    django_site_1.domain = u"localhost:8000"
    django_site_1.name = u"Development Server"
    django_site_1.save()
Example #8
0
    def test_edit_post(self):
        # create author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # create site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # create post
        post = Post()
        post.title = 'My first post',
        post.text = 'This is a test post checking from the test.py',
        post.pub_date = timezone.now()
        post.slug = 'my-first-post'
        post.author = author
        post.site = site
        post.save()

        # login
        self.client.login(username='******', password='******')

        # edit the post
        new_post = {
            'title': 'My second post',
            'text': 'This is a test post checking the test.py',
            'pub_date': timezone.now(),
            'slug': 'my-second-post',
            'site': 1,
        }
        response = self.client.post('/admin/blogengine/post/1/', new_post, follow=True)
Example #9
0
 def test_sync_many(self):
     # Create Sites with Aliases
     Site.objects.create()
     site1 = Site.objects.create(domain='1.example.com')
     site2 = Site.objects.create(domain='2.example.com')
     # Create Site without triggering signals
     site3 = Site(domain='3.example.com')
     site3.save_base(raw=True)
     self.assertEqual(set(Alias.objects.values_list('domain', flat=True)),
                      set([site1.domain, site2.domain]))
     # Sync existing
     site1.domain = '1.example.org'
     site1.save_base(raw=True)
     site2.domain = '2.example.org'
     site2.save_base(raw=True)
     Alias.canonical.sync_many()
     self.assertEqual(set(Alias.objects.values_list('domain', flat=True)),
                      set([site1.domain, site2.domain]))
     # Sync with filter
     site1.domain = '1.example.net'
     site1.save_base(raw=True)
     site2.domain = '2.example.net'
     site2.save_base(raw=True)
     Alias.canonical.sync_many(site__domain=site1.domain)
     self.assertEqual(set(Alias.objects.values_list('domain', flat=True)),
                      set([site1.domain, '2.example.org']))
Example #10
0
    def test_sites_contrib(self, settings, template_render_tag):

        def render():
            return template_render_tag('sitemetrics', 'sitemetrics')

        site_one = Site.objects.get(pk=1)
        site_two = Site(domain='some.com', name='some.com')
        site_two.save()

        site_two_code = Keycode(site=site_two, provider='google', keycode='222')
        site_two_code.save()

        assert '222' in '%s' % site_two_code

        tpl = '{% load sitemetrics %}{% sitemetrics %}'

        settings.SITE_ID = 1

        assert render() == ''  # Test none code for current site

        site_one_code = Keycode(site=site_one, provider='yandex', keycode='111', active=False)
        site_one_code.save()

        assert render() == ''  # Test inactive

        site_one_code.active = True
        site_one_code.save()

        assert '111' in render()  # Test active
        assert '111' in render()  # Test cached hit

        settings.SITE_ID = 2

        assert '222' in render()
Example #11
0
    def test_create_post(self):
        # create a author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # create site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # create a post
        post = Post()
        post.title = 'First test post'
        post.text = 'Fists test post body'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site

        # save post
        post.save()
        all_post = Post.objects.all()
        self.assertEquals(len(all_post), 1)
        only_post = all_post[0]
        self.assertEquals(only_post, post)
        self.assertEqual(only_post.author.username, post.author.username)
        self.assertEquals(only_post.author.email, post.author.email)
Example #12
0
	def test_category_page(self):
		category = Category()
		category.name = 'python'
		category.description = 'The Python programming language'
		category.save()

		site = Site()
		site.name = 'example.com'
		site.domain = 'example.com'
		site.save()

		post = Post()
		post.title = 'My first post'
		post.text = 'This is my first blog post'
		post.pub_date = timezone.now()
		post.slug = 'my-first-post'
		post.site = site
		post.category = category
		post.save()

		all_posts = Post.objects.all()
		self.assertEquals(len(all_posts), 1)
		only_post = all_posts[0]
		self.assertEquals(only_post, post)

		category_url = post.category.get_absolute_url()

		# Fetch the category
		response = self.client.get(category_url)
		self.assertEquals(response.status_code, 200)

		self.assertTrue(post.category.name in response.content)
		self.assertTrue(post.title in response.content)
Example #13
0
def set_site():
  from django.contrib.sites.models import Site
  from django.conf import settings
  #old_SITE_ID = getattr(settings, 'SITE_ID', None)
  site = Site(domain="example.com", name="example.com")
  site.save()
  settings.SITE_ID = str(site.key())
Example #14
0
    def test_index(self):
        # Create the category
        category = Category()
        category.name = 'python'
        category.description = 'The Python programming language'
        category.save()

        # Create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # Create the site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # Create the post
        post = Post()
        post.title = 'My first post'
        post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
        post.slug = 'my-first-post'
        post.pub_date = timezone.now()
        post.author = author
        post.site = site
        post.category = category
        post.save()

        # Check new post saved
        all_posts = Post.objects.all()
        self.assertEqual(len(all_posts), 1)

        # Fetch the index
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
Example #15
0
    def process_request(self, request):
        # Ignore port if it's 80 or 443
        if ':' in request.get_host():
            domain, port = request.get_host().split(':')
            if int(port) not in (80, 443):
                domain = request.get_host()
        else:
            domain = request.get_host().split(':')[0]

        # Try exact domain and fall back to with/without 'www.'
        site = Site.all().filter('domain =', domain).get()
        if not site:
            if domain.startswith('www.'):
                fallback_domain = domain[4:]
            else:
                fallback_domain = 'www.' + domain
            site = Site.all().filter('domain =', fallback_domain).get()

        # Add site if it doesn't exist
        if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY', True):
            site = db_create(Site, domain=domain, name=domain)
            site.put()

        # Set SITE_ID for this thread/request
        if site:
            SITE_ID.value = str(site.key())
        else:
            SITE_ID.value = _default_site_id
Example #16
0
def create_secondary_site(app, created_models, verbosity, db, **kwargs):
    if Site in created_models:
        if verbosity >= 2:
            print "Creating registration Site object"
        s = Site(domain="example.com", name="registration")
        s.save(using=db)
    Site.objects.clear_cache()
Example #17
0
def _setup():
    site = Site.objects.get_current()

    print(site.name, " ", site.domain)

    site.domain = 'test.com'
    site.save()

    site = Site.objects.get_current()
    print(site)

    try:
        site2 = Site.objects.get(name="test2")
    except Site.DoesNotExist:
        site2 = Site()
    site2.name = "test2"
    site2.domain = "https://site2.name/"
    site2.save()

    print(site2.id, " ", site2.name, " ", site2.domain)

    global uk
    try:
        uk = portal_m.Lang.objects.get(code="UK")
    except portal_m.Lang.DoesNotExist:
        uk = portal_m.Lang.objects.create(code="UK", caption="Ukrainian", default=True)

    print("Default language: ", uk)

    return site, site2
Example #18
0
def add_site(name, domain):
    """ Add a site to database, create directory tree """

    # get latest SITE id
    sites = Site.objects.all()
    used_ids = [v[0] for v in sites.values_list()]
    site_id = max(used_ids) + 1

    # current settings is one of the sites
    project_dir = os.path.realpath(os.path.join(settings.SITE_ROOT, '../'))
    site_dir = os.path.join(project_dir, 'site%s' % site_id)
    site_template = os.path.join(os.path.dirname(__file__), 'site_template')
    shutil.copytree(site_template, site_dir)

    # update configuration and settings files
    change_dict = {
        '$SITE_ID': str(site_id),
        '$SITE_NAME': name,
        '$DOMAIN': domain,
        '$SITE_ROOT': site_dir,
        '$SERVE_PATH': settings.SERVE_PATH,
        '$PORTNUM': '8%s' % str(site_id).zfill(3),
    }
    sed(os.path.join(site_dir, 'conf/gunicorn'), change_dict)
    sed(os.path.join(site_dir, 'conf/nginx'), change_dict)
    sed(os.path.join(site_dir, 'settings.py'), change_dict)
    sed(os.path.join(site_dir, 'local_settings_template.py'), change_dict)

    # add site to database
    site = Site(id=site_id, name=name, domain=domain)
    site.save()
    dump_model(Site, os.path.join(project_dir, 'sites.json'))
Example #19
0
    def test_delete_post(self):
        # create the author
        author = User.objects.create_user('testuser', '*****@*****.**', 'password')
        author.save()

        # create a site
        site = Site()
        site.name = 'example.com'
        site.domain = 'example.com'
        site.save()

        # create post
        post = Post()
        post.title = 'Delete Test'
        post.content = 'Test post for delete test'
        post.author = author
        post.pub_date = timezone.now()
        post.slug = 'delete-test'
        post.site = site
        post.save()

        # check the post is saved
        all_post = Post.objects.all()
        self.assertEquals(len(all_post), 1)
        only_post = all_post[0]

        # login
        self.client.login(username='******', password='******')

        # delete post
        response = self.client.post('/admin/blogengine/post/1/delete/', dict(post='yes'), follow=True)
        self.assertEquals(response.status_code, 200)
        self.assertTrue('deleted successfully' in response.content)
        all_post = Post.objects.all()
        self.assertNotEquals(len(all_post), 1)
    def process_request(self, request):
        # Ignore port if it's 80 or 443
        if ':' in request.get_host():
            domain, port = request.get_host().split(':', 1)
        else:
            domain = request.get_host()

        # Domains are case insensitive
        domain = domain.lower()

        # We cache the SITE_ID
        cache_key = 'Site:domain:%s' % domain
        site = cache.get(cache_key)
        if site:
            SITE_ID.value = site
        else:
            site = _get_site(domain)

            # Add site if it doesn't exist
            if not site and getattr(settings, 'CREATE_SITES_AUTOMATICALLY',
                                    True):
                site = Site(domain=domain, name=domain)
                site.save()

            # Set SITE_ID for this thread/request
            if site:
                SITE_ID.value = site.pk
            else:
                SITE_ID.value = _default_site_id

            cache.set(cache_key, SITE_ID.value, 5 * 60)
Example #21
0
	def test_index(self):
		# Create the category
		category = Category()
		category.name = 'python'
		category.description = 'The Python programming language'
		category.save()

		# Tag
		tag = Tag()
		tag.name = 'perl'
		tag.description = 'the perl programming'
		tag.save()

		author = User.objects.create_user('testuser', '*****@*****.**', 'password')
		author.save()

		# Create the site
		site = Site()
		site.name = 'example.com'
		site.domain = 'example.com'
		site.save()

		# Create the post
		post = Post()
		post.title = 'My first post'
		post.text = 'This is [my first blog post](http://127.0.0.1:8000/)'
		post.slug = 'my-first-post'
		post.pub_date = timezone.now()
		post.author = author
		post.site = site
		post.category = category
		post.save()
		post.tags.add(tag)
		post.save()

		# Check new post saved
		all_posts = Post.objects.all()
		self.assertEquals(len(all_posts), 1)

		# Fetch the index
		response = self.client.get('/')
		self.assertEquals(response.status_code, 200)

		# Check post title in response
		self.assertTrue(post.title in response.content)

		self.assertTrue(markdown.markdown(post.text) in response.content)

		self.assertTrue(post.category.name in response.content)

		post_tag = all_posts[0].tags.all()[0]
		self.assertTrue(post_tag.name in response.content)

		self.assertTrue(str(post.pub_date.year) in response.content)
		self.assertTrue(post.pub_date.strftime('%b') in response.content)
		self.assertTrue(str(post.pub_date.day) in response.content)

		# Check the link is marked up properly
		self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
Example #22
0
	def test_create_post(self):
		category = Category()
		category.name = 'python'
		category.description = 'The Python programming language'
		category.save()

		tag = Tag()
		tag.name = 'python'
		tag.description = 'The Python programming language'
		tag.save()

		site = Site()
		site.name = 'example.com'
		site.domain = 'example.com'
		site.save()

		post = Post()

		post.title = 'My first post'
		post.text = 'This is my first blog post'
		post.pub_date = timezone.now()
		post.slug = 'my-first-post'
		post.site = site
		post.category = category

		post.save()

		# Add tags
		post.tags.add(tag)
		post.save()

		# Retrieve new post
		all_posts = Post.objects.all()
		self.assertEquals(len(all_posts), 1)
		only_post = all_posts[0]
		self.assertEquals(only_post, post)

		# Check attributes
		self.assertEquals(only_post.title, 'My first post')
		self.assertEquals(only_post.text, 'This is my first blog post')
		self.assertEquals(only_post.slug, 'my-first-post')
		self.assertEquals(only_post.site.name, 'example.com')
		self.assertEquals(only_post.site.domain, 'example.com')
		self.assertEquals(only_post.pub_date.day, post.pub_date.day)
		self.assertEquals(only_post.pub_date.month, post.pub_date.month)
		self.assertEquals(only_post.pub_date.year, post.pub_date.year)
		self.assertEquals(only_post.pub_date.hour, post.pub_date.hour)
		self.assertEquals(only_post.pub_date.minute, post.pub_date.minute)
		self.assertEquals(only_post.pub_date.second, post.pub_date.second)
		self.assertEquals(only_post.category.name, 'python')
		self.assertEquals(only_post.category.description, 'The Python programming language')

		# Check tags
		post_tags = only_post.tags.all()
		self.assertEquals(len(post_tags), 1)
		only_post_tag = post_tags[0]
		self.assertEquals(only_post_tag, tag)
		self.assertEquals(only_post_tag.name, 'python')
		self.assertEquals(only_post_tag.description, 'The Python programming language')
 def test_by_host(self):
     "Tests typical usage"
     site2 = Site(domain='www.example.org', name='www.example.org')
     site2.save()
     self.assertEqual(by_host('example.com').domain, 'example.com')
     self.assertEqual(by_host('www.example.com').domain, 'example.com')
     self.assertEqual(by_host('example.org').domain, 'www.example.org')
     self.assertEqual(by_host('www.example.org').domain, 'www.example.org')
Example #24
0
def auto_create_superuser(*args, **kwargs):

    site = Site(domain="http://example.com", name="Example Site")
    site.save()


    user = User.objects.create_superuser("DeploymentAdmin", "*****@*****.**", "kasashi")
    user.save()
Example #25
0
 def test_unauthed_num_queries(self):
     with SettingsOverride(POSER_PUBLIC_FOR='all'):
         request = self.get_request()
         site = Site()
         site.pk = 1
         page = create_page("test-public-for-all", "nav_playground.html")
         with self.assertNumQueries(0):
             page.has_view_permission(request)
Example #26
0
class LoginMixin(TestCase):
    def setUp(self):
        u = User(username="******", email="*****@*****.**", first_name="M", last_name="J", is_staff=True)
        u.set_password("password")
        u.save()
        self.client.login(username=u.username, password="******")
        self.site = Site(domain="http://google.com", name="foo")
        self.site.save()
Example #27
0
 def test_site_initial(self):
     site = Site(domain='x.com', name='x')
     site.full_clean()
     site.save()
     form_for_class = movenodeform_factory(model=MenuItem,
                                           form=MenuItemTreeForm)
     form = form_for_class(data=None, files=None)
     self.assertEqual(form.fields['site'].initial, 2)
def update_default_site(apps, schema_editor):
    try:
        current_site = Site.objects.get_current()
    except Site.DoesNotExist:
        current_site = Site()
    current_site.domain = 'environmentalfriction.com'
    current_site.name = 'Environmental Friction'
    current_site.save()
Example #29
0
 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)
Example #30
0
 def test_unauthed_no_access_num_queries(self):
     current_site = Site()
     current_site.pk = 1
     request = self.get_request()
     page = Page()
     page.pk = 1
     fake_tree_attrs(page)
     with self.assertNumQueries(1):
         page.has_view_permission(request)
Example #31
0
 def setUp(self):
     self.site = Site(domain="mydomain.com", name="mydomain")
     self.site.save()
Example #32
0
 def get_urls(self, site=None, **kwargs):
     site = Site(domain='autoelectronicselectra.com', name='autoelectronicselectra.com')
     return super(StaticSitemap, self).get_urls(site=site, **kwargs)
Example #33
0
 def test_it_returns_edit_link_for_obj(self):
     site = Site(pk=1)
     edit_link = make_edit_link("edit")
     assert (
         edit_link(None, site) == '<a class="button" href="/admin/sites/site/1/change/">edit</a>'
     )
Example #34
0
    'http://aboutfood.com/':                  'http://www.about-food.com/',
    'http://fruits.about-food.com/':          'http://fruit.about-food.com/',
    'http://fruits.about-food.net/':          'http://fruit.about-food.com/',
    'http://www.about-games.com/':            'http://about.gam.es/',
    'http://www.about-games.com/toast':       'http://about.gam.es/toast',
    'http://fruits.about-food.net/mapple':    'http://fruit.about-food.com/mapple',
    'http://diary.aboutfood.com/whole-milk':  'http://dairy.about-food.com/whole-milk',
}

"""
test sites
----------
"""
sites = [
    Site(domain='about-food.com',
         name='Site About Food',
         folder_name='about_food_com',
         subdomains=['www','fruit','meat','vegetables','dairy']),

    Site(domain='about.gam.es',
         name='About Games Site',
         folder_name='about_games'),

    Site(domain='corp-umbrella-site.com',
         name='Corporate Umbrella Site',
         folder_name='corp_site',
         subdomains=['www']),

    Site(domain='restaurants.about-food.com',
         name='About Food Subdomain Site',
         folder_name='about_food_restaurants'),
def create_default_site(app, created_models, verbosity):
    if Site in created_models:
        if verbosity >= 2:
            print "Creating example.com Site object"
        s = Site(domain="example.com", name="example.com")
        s.save()
 def setUp(self):
     self.site = Site()
     self.site.pk = 1
     super(ViewPermissionTests, self).setUp()
Example #37
0
 def test_site(self):
     site = Site(domain='www.codescale.net', name='CodeScale.net')
     abs_url = absurl(protocol='http', site=site, path='/')
     self.assertEqual(abs_url, 'http://www.codescale.net/')
Example #38
0
 def get_urls(self, site=None, **kwargs):
     site = Site(domain='mankivkacpmsd.us.to', name='mankivkacpmsd.us.to')
     return super(StaticViewSitemap, self).get_urls(site=site, **kwargs)
Example #39
0
 def setUp(self):
     super().setUp()
     Site(id=settings.SITE_ID, domain="example.com",
          name="example.com").save()
Example #40
0
 def create_site(self):
     site = Site(id=settings.SITE_ID,
                 domain=self.live_server_url,
                 name=self.live_server_url)
     site.save()
     return site
Example #41
0
    def test_seen_site(self, filter):
        user = User(username='******')
        site = Site()
        LastSeen.objects.when(user=user, site=site)

        filter.assert_called_with(user=user, site=site)
Example #42
0
 def test_it_returns_empty_string_when_given_obj_without_pk(self):
     site = Site()
     edit_link = make_edit_link("edit")
     assert edit_link(None, site) == ""
Example #43
0
 def get_urls(self, page=1, site=None, protocol=None):
     site = Site(domain=self.domain, name=self.domain)
     return super(SiteMapDomainMixin, self).get_urls(page,
                                                     site,
                                                     protocol=None)
Example #44
0
 def setUpTestData(cls):
     # don't use the manager because we want to ensure the site exists
     # with pk=1, regardless of whether or not it already exists.
     cls.site1 = Site(pk=1, domain='example.com', name='example.com')
     cls.site1.save()
Example #45
0
 def setUp(self):
     # Note that we're assigning non-existent values for country,
     # category, etc.
     site = Site(domain='tramcar.org', name='Tramcar')
     site.full_clean()
     site.save()
Example #46
0
 def get_urls(self, site=None, **kwargs):
     site = Site(domain='', name='')
     return super(SubSitemap, self).get_urls(site=site, **kwargs)
Example #47
0
class Enlaces(models.Model):
    descripcion = models.CharField(max_length=30,
                                   verbose_name=_(u'descripción'))
    url = models.URLField()
    ubicacion = models.BooleanField(verbose_name=_(u'ubicación'), choices=MB)

    def __unicode__(self):
        return unicode("%s" % self.descripcion)

    class Meta:
        verbose_name = _(u'Enlaces')
        verbose_name_plural = _(u'Enlaces')


Site.add_to_class('titulo',
                  models.CharField(max_length=20, verbose_name=_(u'título')))
Site.add_to_class(
    'subtitulo', models.CharField(max_length=20, verbose_name=_(u'subtítulo')))
Site.add_to_class('informacion',
                  models.TextField(verbose_name=_(u'información')))
Site.add_to_class(
    'logo',
    ImageWithThumbsField(upload_to='configuracion/files',
                         sizes=((120, 100), ),
                         verbose_name=_(u'logo')))
Site.add_to_class(
    'banner',
    ImageWithThumbsField(upload_to='configuracion/files',
                         sizes=((160, 600), ),
                         verbose_name=_(u'banner 160x600')))
Example #48
0
 def get_urls(self, site=None, **kwargs):
     site = Site(domain='www.designsafe-ci.org')
     return super(HomeSitemap, self).get_urls(site=site, **kwargs)
Example #49
0
 def test_save_another(self):
     # Regression for #17415
     # On some backends the sequence needs reset after save with explicit ID.
     # Test that there is no sequence collisions by saving another site.
     Site(domain="example2.com", name="example2.com").save()
Example #50
0
def course_wiki_redirect(request, course_id):  # pylint: disable=W0613
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(course_id)
    course_slug = course_wiki_slug(course)

    valid_slug = True
    if not course_slug:
        log.exception(
            "This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception(
            "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens."
        )
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    # The wiki needs a Site object created. We make sure it exists here
    try:
        Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        site_id = str(new_site.id)  # pylint: disable=E1101
        if site_id != str(settings.SITE_ID):
            raise ImproperlyConfigured(
                "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}"
                .format(site_id, settings.SITE_ID))

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        content = cgi.escape(
            # Translators: this string includes wiki markup.  Leave the ** and the _ alone.
            _("This is the wiki for **{organization}**'s _{course_name}_."
              ).format(
                  organization=course.display_org_with_default,
                  course_name=course.display_name_with_default,
              ))
        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content=content,
            user_message=_("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={
                'owner': None,
                'group': None,
                'group_read': True,
                'group_write': True,
                'other_read': True,
                'other_write': True,
            })

    return redirect("wiki:get", path=urlpath.path)
Example #51
0
    def handle(self, *args, **options):
        """
        :param args:
        :param options:
        :return:
        """
        if not get_user_model().objects.filter(is_superuser=True).exists():
            raise LookupError(
                "Before Run This command, make sure a superuser is already created."
            )
        domain = options['domain_name']
        while True:
            if not domain:
                domain = input(
                    'Please provide domain name for site. [localhost]')
                if not domain:
                    domain = 'localhost'
            else:
                break

        urlconf = options['urlconf_module']
        while True:
            if not urlconf:
                urlconf = input('Please provide root urlconf [%s]' %
                                settings.ROOT_URLCONF)
                if not urlconf:
                    urlconf = settings.ROOT_URLCONF
            else:
                break

        try:
            site = Site.objects.get(domain=domain)
        except Site.DoesNotExist:
            site = Site(domain=domain, name=domain)
            site.save()

        try:
            route = RoutingTable.objects.get_by_natural_key(
                options['route_name'])
        except RoutingTable.DoesNotExist:
            route = RoutingTable(
                name=options['route_name'],
                slug=options['route_name'],
                urls=[
                    {
                        "prefix": None,
                        "url_module": urlconf,
                        "namespace": None,
                        "children": []
                    },
                ],
                handlers={
                    "handler400": "hacs.views.errors.bad_request",
                    "handler403": "hacs.views.errors.permission_denied",
                    "handler404": "hacs.views.errors.page_not_found",
                    "handler500": "hacs.views.errors.server_error"
                },
                created_by=get_user_model().objects.filter(
                    is_superuser=True).first(),
            )
            route.save()

        SiteRoutingRules(name="%s-%s" % (site.domain, route.name),
                         slug="%s-%s" % (site.domain, route.name),
                         site=site,
                         route=route,
                         created_by=get_user_model().objects.filter(
                             is_superuser=True).first()).save()
        self.stdout.write(
            '>>> Django Hybrid Access Control System is initialized and ready to use! <<<'
        )
Example #52
0
 def __init__(self, domain, name):
     self.site = Site(domain=domain, name=name)
Example #53
0
    def handle(self, *args, **options):
        os.environ["DJANGO_COLORS"] = "nocolor"
        Site(id=4000, domain=settings.SITH_URL, name=settings.SITH_NAME).save()
        root_path = os.path.dirname(
            os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        Group(name="Root").save()
        Group(name="Public").save()
        Group(name="Subscribers").save()
        Group(name="Old subscribers").save()
        Group(name="Accounting admin").save()
        Group(name="Communication admin").save()
        Group(name="Counter admin").save()
        Group(name="Banned from buying alcohol").save()
        Group(name="Banned from counters").save()
        Group(name="Banned to subscribe").save()
        Group(name="SAS admin").save()
        Group(name="Forum admin").save()
        Group(name="Pedagogy admin").save()
        self.reset_index("core", "auth")
        root = User(
            id=0,
            username="******",
            last_name="",
            first_name="Bibou",
            email="*****@*****.**",
            date_of_birth="1942-06-12",
            is_superuser=True,
            is_staff=True,
        )
        root.set_password("plop")
        root.save()
        profiles_root = SithFile(parent=None,
                                 name="profiles",
                                 is_folder=True,
                                 owner=root)
        profiles_root.save()
        home_root = SithFile(parent=None,
                             name="users",
                             is_folder=True,
                             owner=root)
        home_root.save()

        # Page needed for club creation
        p = Page(name=settings.SITH_CLUB_ROOT_PAGE)
        p.set_lock(root)
        p.save()

        club_root = SithFile(parent=None,
                             name="clubs",
                             is_folder=True,
                             owner=root)
        club_root.save()
        SithFile(parent=None, name="SAS", is_folder=True, owner=root).save()
        main_club = Club(
            id=1,
            name=settings.SITH_MAIN_CLUB["name"],
            unix_name=settings.SITH_MAIN_CLUB["unix_name"],
            address=settings.SITH_MAIN_CLUB["address"],
        )
        main_club.save()
        bar_club = Club(
            id=2,
            name=settings.SITH_BAR_MANAGER["name"],
            unix_name=settings.SITH_BAR_MANAGER["unix_name"],
            address=settings.SITH_BAR_MANAGER["address"],
        )
        bar_club.save()
        launderette_club = Club(
            id=84,
            name=settings.SITH_LAUNDERETTE_MANAGER["name"],
            unix_name=settings.SITH_LAUNDERETTE_MANAGER["unix_name"],
            address=settings.SITH_LAUNDERETTE_MANAGER["address"],
        )

        launderette_club.save()
        self.reset_index("club")
        for b in settings.SITH_COUNTER_BARS:
            g = Group(name=b[1] + " admin")
            g.save()
            c = Counter(id=b[0], name=b[1], club=bar_club, type="BAR")
            c.save()
            g.editable_counters.add(c)
            g.save()
        self.reset_index("counter")
        Counter(name="Eboutic", club=main_club, type="EBOUTIC").save()
        Counter(name="AE", club=main_club, type="OFFICE").save()

        home_root.view_groups.set([
            Group.objects.filter(
                name=settings.SITH_MAIN_MEMBERS_GROUP).first()
        ])
        club_root.view_groups.set([
            Group.objects.filter(
                name=settings.SITH_MAIN_MEMBERS_GROUP).first()
        ])
        home_root.save()
        club_root.save()

        Sith(weekmail_destinations="[email protected] [email protected]").save()
        Weekmail().save()

        p = Page(name="Index")
        p.set_lock(root)
        p.save()
        p.view_groups.set([settings.SITH_GROUP_PUBLIC_ID])
        p.set_lock(root)
        p.save()
        PageRev(
            page=p,
            title="Wiki index",
            author=root,
            content="""
Welcome to the wiki page!
""",
        ).save()

        p = Page(name="services")
        p.set_lock(root)
        p.save()
        p.view_groups.set([settings.SITH_GROUP_PUBLIC_ID])
        p.set_lock(root)
        PageRev(
            page=p,
            title="Services",
            author=root,
            content="""
|   |   |   |
| :---: | :---: | :---: | :---: |
| [Eboutic](/eboutic) | [Laverie](/launderette) | Matmat | [Fichiers](/file) |
| SAS | Weekmail | Forum | |

""",
        ).save()

        p = Page(name="launderette")
        p.set_lock(root)
        p.save()
        p.set_lock(root)
        PageRev(page=p,
                title="Laverie",
                author=root,
                content="Fonctionnement de la laverie").save()

        # Here we add a lot of test datas, that are not necessary for the Sith, but that provide a basic development environment
        if not options["prod"]:
            # Adding user Skia
            skia = User(
                username="******",
                last_name="Kia",
                first_name="S'",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
            )
            skia.set_password("plop")
            skia.save()
            skia.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            skia.save()
            skia_profile_path = os.path.join(root_path,
                                             "core/fixtures/images/3.jpg")
            with open(skia_profile_path, "rb") as f:
                name = str(skia.id) + "_profile.jpg"
                skia_profile = SithFile(
                    parent=profiles_root,
                    name=name,
                    file=resize_image(Image.open(BytesIO(f.read())), 400,
                                      "JPEG"),
                    owner=skia,
                    is_folder=False,
                    mime_type="image/jpeg",
                    size=os.path.getsize(skia_profile_path),
                )
                skia_profile.file.name = name
                skia_profile.save()
                skia.profile_pict = skia_profile
                skia.save()

            # Adding user public
            public = User(
                username="******",
                last_name="Not subscribed",
                first_name="Public",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            public.set_password("plop")
            public.save()
            public.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            public.save()
            # Adding user Subscriber
            subscriber = User(
                username="******",
                last_name="User",
                first_name="Subscribed",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            subscriber.set_password("plop")
            subscriber.save()
            subscriber.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            subscriber.save()
            # Adding user old Subscriber
            old_subscriber = User(
                username="******",
                last_name="Subscriber",
                first_name="Old",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            old_subscriber.set_password("plop")
            old_subscriber.save()
            old_subscriber.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            old_subscriber.save()
            # Adding user Counter admin
            counter = User(
                username="******",
                last_name="Ter",
                first_name="Coun",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            counter.set_password("plop")
            counter.save()
            counter.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            counter.groups.set([
                Group.objects.filter(
                    id=settings.SITH_GROUP_COUNTER_ADMIN_ID).first().id
            ])
            counter.save()
            # Adding user Comptable
            comptable = User(
                username="******",
                last_name="Able",
                first_name="Compte",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            comptable.set_password("plop")
            comptable.save()
            comptable.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            comptable.groups.set([
                Group.objects.filter(
                    id=settings.SITH_GROUP_ACCOUNTING_ADMIN_ID).first().id
            ])
            comptable.save()
            # Adding user Guy
            u = User(
                username="******",
                last_name="Carlier",
                first_name="Guy",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
                is_superuser=False,
                is_staff=False,
            )
            u.set_password("plop")
            u.save()
            u.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            u.save()
            # Adding user Richard Batsbak
            r = User(
                username="******",
                last_name="Batsbak",
                first_name="Richard",
                email="*****@*****.**",
                date_of_birth="1982-06-12",
            )
            r.set_password("plop")
            r.save()
            r.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            r.save()
            # Adding syntax help page
            p = Page(name="Aide_sur_la_syntaxe")
            p.save(force_lock=True)
            with open(os.path.join(root_path) + "/doc/SYNTAX.md", "r") as rm:
                PageRev(page=p,
                        title="Aide sur la syntaxe",
                        author=skia,
                        content=rm.read()).save()
            p.view_groups.set([settings.SITH_GROUP_PUBLIC_ID])
            p.save(force_lock=True)
            p = Page(name="Services")
            p.save(force_lock=True)
            p.view_groups.set([settings.SITH_GROUP_PUBLIC_ID])
            p.save(force_lock=True)
            PageRev(
                page=p,
                title="Services",
                author=skia,
                content="""
|   |   |   |
| :---: | :---: | :---: |
| [Eboutic](/eboutic) | [Laverie](/launderette) | Matmat |
| SAS | Weekmail | Forum|

""",
            ).save()

            # Subscription
            default_subscription = "un-semestre"
            # Root
            s = Subscription(
                member=User.objects.filter(pk=root.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Skia
            s = Subscription(
                member=User.objects.filter(pk=skia.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Counter admin
            s = Subscription(
                member=User.objects.filter(pk=counter.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Comptable
            s = Subscription(
                member=User.objects.filter(pk=comptable.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Richard
            s = Subscription(
                member=User.objects.filter(pk=r.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # User
            s = Subscription(
                member=User.objects.filter(pk=subscriber.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Old subscriber
            s = Subscription(
                member=User.objects.filter(pk=old_subscriber.pk).first(),
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start(
                datetime(year=2012, month=9, day=4))
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()

            # Clubs
            Club(
                name="Bibo'UT",
                unix_name="bibout",
                address="46 de la Boustifaille",
                parent=main_club,
            ).save()
            guyut = Club(
                name="Guy'UT",
                unix_name="guyut",
                address="42 de la Boustifaille",
                parent=main_club,
            )
            guyut.save()
            Club(name="Woenzel'UT",
                 unix_name="woenzel",
                 address="Woenzel",
                 parent=guyut).save()
            Membership(user=skia, club=main_club, role=3,
                       description="").save()
            troll = Club(
                name="Troll Penché",
                unix_name="troll",
                address="Terre Du Milieu",
                parent=main_club,
            )
            troll.save()
            refound = Club(
                name="Carte AE",
                unix_name="carte_ae",
                address="Jamais imprimée",
                parent=main_club,
            )
            refound.save()

            # Counters
            Customer(user=skia, account_id="6568j", amount=0).save()
            Customer(user=r, account_id="4000k", amount=0).save()
            p = ProductType(name="Bières bouteilles")
            p.save()
            c = ProductType(name="Cotisations")
            c.save()
            r = ProductType(name="Rechargements")
            r.save()
            verre = ProductType(name="Verre")
            verre.save()
            cotis = Product(
                name="Cotis 1 semestre",
                code="1SCOTIZ",
                product_type=c,
                purchase_price="15",
                selling_price="15",
                special_selling_price="15",
                club=main_club,
            )
            cotis.save()
            cotis2 = Product(
                name="Cotis 2 semestres",
                code="2SCOTIZ",
                product_type=c,
                purchase_price="28",
                selling_price="28",
                special_selling_price="28",
                club=main_club,
            )
            cotis2.save()
            refill = Product(
                name="Rechargement 15 €",
                code="15REFILL",
                product_type=r,
                purchase_price="15",
                selling_price="15",
                special_selling_price="15",
                club=main_club,
            )
            refill.save()
            barb = Product(
                name="Barbar",
                code="BARB",
                product_type=p,
                purchase_price="1.50",
                selling_price="1.7",
                special_selling_price="1.6",
                club=main_club,
            )
            barb.save()
            cble = Product(
                name="Chimay Bleue",
                code="CBLE",
                product_type=p,
                purchase_price="1.50",
                selling_price="1.7",
                special_selling_price="1.6",
                club=main_club,
            )
            cble.save()
            cons = Product(
                name="Consigne Eco-cup",
                code="CONS",
                product_type=verre,
                purchase_price="1",
                selling_price="1",
                special_selling_price="1",
                club=main_club,
            )
            cons.id = 1152
            cons.save()
            dcons = Product(
                name="Déconsigne Eco-cup",
                code="DECO",
                product_type=verre,
                purchase_price="-1",
                selling_price="-1",
                special_selling_price="-1",
                club=main_club,
            )
            dcons.id = 1151
            dcons.save()
            Product(
                name="Corsendonk",
                code="CORS",
                product_type=p,
                purchase_price="1.50",
                selling_price="1.7",
                special_selling_price="1.6",
                club=main_club,
            ).save()
            Product(
                name="Carolus",
                code="CARO",
                product_type=p,
                purchase_price="1.50",
                selling_price="1.7",
                special_selling_price="1.6",
                club=main_club,
            ).save()
            mde = Counter.objects.filter(name="MDE").first()
            mde.products.add(barb)
            mde.products.add(cble)
            mde.products.add(cons)
            mde.products.add(dcons)
            mde.sellers.add(skia)
            mde.save()

            eboutic = Counter.objects.filter(name="Eboutic").first()
            eboutic.products.add(barb)
            eboutic.products.add(cotis)
            eboutic.products.add(cotis2)
            eboutic.products.add(refill)
            eboutic.save()

            refound_counter = Counter(name="Carte AE",
                                      club=refound,
                                      type="OFFICE")
            refound_counter.save()
            refound_product = Product(
                name="remboursement",
                code="REMBOURS",
                purchase_price="0",
                selling_price="0",
                special_selling_price="0",
                club=refound,
            )
            refound_product.save()

            # Accounting test values:
            BankAccount(name="AE TG", club=main_club).save()
            BankAccount(name="Carte AE", club=main_club).save()
            ba = BankAccount(name="AE TI", club=main_club)
            ba.save()
            ca = ClubAccount(name="Troll Penché", bank_account=ba, club=troll)
            ca.save()
            gj = GeneralJournal(name="A16",
                                start_date=date.today(),
                                club_account=ca)
            gj.save()
            credit = AccountingType(code="74",
                                    label="Subventions d'exploitation",
                                    movement_type="CREDIT")
            credit.save()
            debit = AccountingType(
                code="606",
                label="Achats non stockés de matières et fournitures(*1)",
                movement_type="DEBIT",
            )
            debit.save()
            debit2 = AccountingType(
                code="604",
                label="Achats d'études et prestations de services(*2)",
                movement_type="DEBIT",
            )
            debit2.save()
            buying = AccountingType(code="60",
                                    label="Achats (sauf 603)",
                                    movement_type="DEBIT")
            buying.save()
            comptes = AccountingType(code="6",
                                     label="Comptes de charge",
                                     movement_type="DEBIT")
            comptes.save()
            simple = SimplifiedAccountingType(label="Je fais du simple 6",
                                              accounting_type=comptes)
            simple.save()
            woenzco = Company(name="Woenzel & co")
            woenzco.save()

            operation_list = [
                (
                    27,
                    "J'avais trop de bière",
                    "CASH",
                    None,
                    buying,
                    "USER",
                    skia.id,
                    "",
                    None,
                ),
                (
                    4000,
                    "Ceci n'est pas une opération... en fait si mais non",
                    "CHECK",
                    None,
                    debit,
                    "COMPANY",
                    woenzco.id,
                    "",
                    23,
                ),
                (
                    22,
                    "C'est de l'argent ?",
                    "CARD",
                    None,
                    credit,
                    "CLUB",
                    troll.id,
                    "",
                    None,
                ),
                (
                    37,
                    "Je paye CASH",
                    "CASH",
                    None,
                    debit2,
                    "OTHER",
                    None,
                    "tous les étudiants <3",
                    None,
                ),
                (300, "Paiement Guy", "CASH", None, buying, "USER", skia.id,
                 "", None),
                (32.3, "Essence", "CASH", None, buying, "OTHER", None,
                 "station", None),
                (
                    46.42,
                    "Allumette",
                    "CHECK",
                    None,
                    credit,
                    "CLUB",
                    main_club.id,
                    "",
                    57,
                ),
                (
                    666.42,
                    "Subvention de far far away",
                    "CASH",
                    None,
                    comptes,
                    "CLUB",
                    main_club.id,
                    "",
                    None,
                ),
                (
                    496,
                    "Ça, c'est un 6",
                    "CARD",
                    simple,
                    None,
                    "USER",
                    skia.id,
                    "",
                    None,
                ),
                (
                    17,
                    "La Gargotte du Korrigan",
                    "CASH",
                    None,
                    debit2,
                    "CLUB",
                    bar_club.id,
                    "",
                    None,
                ),
            ]
            for op in operation_list:
                operation = Operation(
                    journal=gj,
                    date=date.today(),
                    amount=op[0],
                    remark=op[1],
                    mode=op[2],
                    done=True,
                    simpleaccounting_type=op[3],
                    accounting_type=op[4],
                    target_type=op[5],
                    target_id=op[6],
                    target_label=op[7],
                    cheque_number=op[8],
                )
                operation.clean()
                operation.save()

            # Adding user sli
            sli = User(
                username="******",
                last_name="Li",
                first_name="S",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
            )
            sli.set_password("plop")
            sli.save()
            sli.view_groups = [
                Group.objects.filter(
                    name=settings.SITH_MAIN_MEMBERS_GROUP).first().id
            ]
            sli.save()
            sli_profile_path = os.path.join(root_path,
                                            "core/fixtures/images/5.jpg")
            with open(sli_profile_path, "rb") as f:
                name = str(sli.id) + "_profile.jpg"
                sli_profile = SithFile(
                    parent=profiles_root,
                    name=name,
                    file=resize_image(Image.open(BytesIO(f.read())), 400,
                                      "JPEG"),
                    owner=sli,
                    is_folder=False,
                    mime_type="image/jpeg",
                    size=os.path.getsize(sli_profile_path),
                )
                sli_profile.file.name = name
                sli_profile.save()
                sli.profile_pict = sli_profile
                sli.save()
            # Adding user Krophil
            krophil = User(
                username="******",
                last_name="Phil'",
                first_name="Kro",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
            )
            krophil.set_password("plop")
            krophil.save()
            krophil_profile_path = os.path.join(root_path,
                                                "core/fixtures/images/6.jpg")
            with open(krophil_profile_path, "rb") as f:
                name = str(krophil.id) + "_profile.jpg"
                krophil_profile = SithFile(
                    parent=profiles_root,
                    name=name,
                    file=resize_image(Image.open(BytesIO(f.read())), 400,
                                      "JPEG"),
                    owner=krophil,
                    is_folder=False,
                    mime_type="image/jpeg",
                    size=os.path.getsize(krophil_profile_path),
                )
                krophil_profile.file.name = name
                krophil_profile.save()
                krophil.profile_pict = krophil_profile
                krophil.save()
            # Adding user Com Unity
            comunity = User(
                username="******",
                last_name="Unity",
                first_name="Com",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
            )
            comunity.set_password("plop")
            comunity.save()
            comunity.groups.set(
                [Group.objects.filter(name="Communication admin").first().id])
            comunity.save()
            Membership(
                user=comunity,
                club=bar_club,
                start_date=timezone.now(),
                role=settings.SITH_CLUB_ROLES_ID["Board member"],
            ).save()
            # Adding user tutu
            tutu = User(
                username="******",
                last_name="Tu",
                first_name="Tu",
                email="*****@*****.**",
                date_of_birth="1942-06-12",
            )
            tutu.set_password("plop")
            tutu.save()
            tutu.groups.set([settings.SITH_GROUP_PEDAGOGY_ADMIN_ID])
            tutu.save()

            # Adding subscription for sli
            s = Subscription(
                member=User.objects.filter(pk=sli.pk).first(),
                subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            StudentCard(uid="9A89B82018B0A0", customer=sli.customer).save()
            # Adding subscription for Krophil
            s = Subscription(
                member=User.objects.filter(pk=krophil.pk).first(),
                subscription_type=list(settings.SITH_SUBSCRIPTIONS.keys())[0],
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Com Unity
            s = Subscription(
                member=comunity,
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()
            # Tutu
            s = Subscription(
                member=tutu,
                subscription_type=default_subscription,
                payment_method=settings.SITH_SUBSCRIPTION_PAYMENT_METHOD[0][0],
            )
            s.subscription_start = s.compute_start()
            s.subscription_end = s.compute_end(
                duration=settings.SITH_SUBSCRIPTIONS[s.subscription_type]
                ["duration"],
                start=s.subscription_start,
            )
            s.save()

            Selling(
                label=dcons.name,
                product=dcons,
                counter=mde,
                unit_price=dcons.selling_price,
                club=main_club,
                quantity=settings.SITH_ECOCUP_LIMIT + 3,
                seller=skia,
                customer=krophil.customer,
            ).save()

            # Add barman to counter
            c = Counter.objects.get(id=2)
            c.sellers.add(User.objects.get(pk=krophil.pk))
            c.save()

            # Create an election
            public_group = Group.objects.get(id=settings.SITH_GROUP_PUBLIC_ID)
            subscriber_group = Group.objects.get(
                name=settings.SITH_MAIN_MEMBERS_GROUP)
            ae_board_group = Group.objects.get(
                name=settings.SITH_MAIN_BOARD_GROUP)
            el = Election(
                title="Élection 2017",
                description="La roue tourne",
                start_candidature="1942-06-12 10:28:45+01",
                end_candidature="2042-06-12 10:28:45+01",
                start_date="1942-06-12 10:28:45+01",
                end_date="7942-06-12 10:28:45+01",
            )
            el.save()
            el.view_groups.add(public_group)
            el.edit_groups.add(ae_board_group)
            el.candidature_groups.add(subscriber_group)
            el.vote_groups.add(subscriber_group)
            el.save()
            liste = ElectionList(title="Candidature Libre", election=el)
            liste.save()
            listeT = ElectionList(title="Troll", election=el)
            listeT.save()
            pres = Role(election=el,
                        title="Président AE",
                        description="Roi de l'AE")
            pres.save()
            resp = Role(election=el,
                        title="Co Respo Info",
                        max_choice=2,
                        description="Ghetto++")
            resp.save()
            cand = Candidature(role=resp,
                               user=skia,
                               election_list=liste,
                               program="Refesons le site AE")
            cand.save()
            cand = Candidature(
                role=resp,
                user=sli,
                election_list=liste,
                program="Vasy je deviens mon propre adjoint",
            )
            cand.save()
            cand = Candidature(role=resp,
                               user=krophil,
                               election_list=listeT,
                               program="Le Pôle Troll !")
            cand.save()
            cand = Candidature(
                role=pres,
                user=sli,
                election_list=listeT,
                program="En fait j'aime pas l'info, je voulais faire GMC",
            )
            cand.save()

            # Forum
            room = Forum(
                name="Salon de discussions",
                description="Pour causer de tout",
                is_category=True,
            )
            room.save()
            Forum(name="AE", description="Réservé au bureau AE",
                  parent=room).save()
            Forum(name="BdF", description="Réservé au bureau BdF",
                  parent=room).save()
            hall = Forum(
                name="Hall de discussions",
                description="Pour toutes les discussions",
                parent=room,
            )
            hall.save()
            various = Forum(name="Divers",
                            description="Pour causer de rien",
                            is_category=True)
            various.save()
            Forum(name="Promos",
                  description="Réservé aux Promos",
                  parent=various).save()
            ForumTopic(forum=hall)

            # News
            friday = timezone.now()
            while friday.weekday() != 4:
                friday += timedelta(hours=6)
            friday.replace(hour=20, minute=0, second=0)
            # Event
            n = News(
                title="Apero barman",
                summary="Viens boire un coup avec les barmans",
                content="Glou glou glou glou glou glou glou",
                type="EVENT",
                club=bar_club,
                author=subscriber,
                is_moderated=True,
                moderator=skia,
            )
            n.save()
            NewsDate(
                news=n,
                start_date=timezone.now() + timedelta(hours=70),
                end_date=timezone.now() + timedelta(hours=72),
            ).save()
            n = News(
                title="Repas barman",
                summary="Enjoy la fin du semestre!",
                content="Viens donc t'enjailler avec les autres barmans aux "
                "frais du BdF! \o/",
                type="EVENT",
                club=bar_club,
                author=subscriber,
                is_moderated=True,
                moderator=skia,
            )
            n.save()
            NewsDate(
                news=n,
                start_date=timezone.now() + timedelta(hours=72),
                end_date=timezone.now() + timedelta(hours=84),
            ).save()
            n = News(
                title="Repas fromager",
                summary="Wien manger du l'bon fromeug'",
                content="Fô viendre mangey d'la bonne fondue!",
                type="EVENT",
                club=bar_club,
                author=subscriber,
                is_moderated=True,
                moderator=skia,
            )
            n.save()
            NewsDate(
                news=n,
                start_date=timezone.now() + timedelta(hours=96),
                end_date=timezone.now() + timedelta(hours=100),
            ).save()
            n = News(
                title="SdF",
                summary="Enjoy la fin des finaux!",
                content="Viens faire la fête avec tout plein de gens!",
                type="EVENT",
                club=bar_club,
                author=subscriber,
                is_moderated=True,
                moderator=skia,
            )
            n.save()
            NewsDate(
                news=n,
                start_date=friday + timedelta(hours=24 * 7 + 1),
                end_date=timezone.now() + timedelta(hours=24 * 7 + 9),
            ).save()
            # Weekly
            n = News(
                title="Jeux sans faim",
                summary="Viens jouer!",
                content="Rejoins la fine équipe du Troll Penché et viens "
                "d'amuser le Vendredi soir!",
                type="WEEKLY",
                club=troll,
                author=subscriber,
                is_moderated=True,
                moderator=skia,
            )
            n.save()
            for i in range(10):
                NewsDate(
                    news=n,
                    start_date=friday + timedelta(hours=24 * 7 * i),
                    end_date=friday + timedelta(hours=24 * 7 * i + 8),
                ).save()

            # Create som data for pedagogy

            UV(
                code="PA00",
                author=User.objects.get(id=0),
                credit_type=settings.SITH_PEDAGOGY_UV_TYPE[3][0],
                manager="Laurent HEYBERGER",
                semester=settings.SITH_PEDAGOGY_UV_SEMESTER[3][0],
                language=settings.SITH_PEDAGOGY_UV_LANGUAGE[0][0],
                department=settings.SITH_PROFILE_DEPARTMENTS[-2][0],
                credits=5,
                title="Participation dans une association étudiante",
                objectives=
                "* Permettre aux étudiants de réaliser, pendant un semestre, un projet culturel ou associatif et de le valoriser.",
                program=
                """* Semestre précédent proposition d'un projet et d'un cahier des charges
* Evaluation par un jury de six membres
* Si accord réalisation dans le cadre de l'UV
* Compte-rendu de l'expérience
* Présentation""",
                skills=
                """* Gérer un projet associatif ou une action éducative en autonomie:
* en produisant un cahier des charges qui -définit clairement le contexte du projet personnel -pose les jalons de ce projet -estime de manière réaliste les moyens et objectifs du projet -définit exactement les livrables attendus
    * en étant capable de respecter ce cahier des charges ou, le cas échéant, de réviser le cahier des charges de manière argumentée.
* Relater son expérience dans un rapport:
* qui permettra à d'autres étudiants de poursuivre les actions engagées
* qui montre la capacité à s'auto-évaluer et à adopter une distance critique sur son action.""",
                key_concepts="""* Autonomie
* Responsabilité
* Cahier des charges
* Gestion de projet""",
                hours_THE=121,
                hours_TE=4,
            ).save()
Example #54
0
def crearTienda(request):
    datos = {}
    if request.is_ajax():
        if request.POST:
            from clientes.models import Cliente, ClientesTiendas, Contrato, Privilegios
            import re

            if re.match('^[(a-z0-9\_\-\.)]+@[(a-z0-9\_\-\.)]+\.[(a-z)]{2,4}$',
                        request.POST['mail'].lower()) and re.match(
                            '|^[a-zA-Z]*$|',
                            request.POST['subdominio'].lower()):
                try:
                    site = Site.objects.get(domain=request.POST['subdominio'] +
                                            '.mindoncloud.com')
                    datos['Error'] = True
                    datos[
                        'letras'] = 'La tienda ya existe intena con otro Nombre'
                except ObjectDoesNotExist:
                    try:
                        cliente = Cliente.objects.get(
                            mail__exact=request.POST['mail'])
                        print('test')
                        datos['Error'] = True
                        datos['letras'] = 'Correo no válido1'
                    except ObjectDoesNotExist:
                        try:
                            Tienda.objects.get(
                                nombre=request.POST['nombreTienda'], activo=1)
                            datos['Error'] = True
                            datos['letras'] = 'Nombre de tienda en uso'
                        except ObjectDoesNotExist:
                            try:
                                Site.objects.get(
                                    domain=request.POST['subdominio'] +
                                    '.wido.mx')
                                datos['Error'] = True
                                datos['letras'] = 'Direccion de tienda en uso'
                            except ObjectDoesNotExist:
                                datos['Error'] = False

                    if datos['Error'] == False:
                        from datetime import date, timedelta

                        url = urllib.urlopen(
                            "https://api.digitalocean.com/v1/domains/new?client_id=30c316cd106ea8d3aec887283db8dd24&api_key=972292751ed197d894365b2df49c771e&name="
                            + request.POST['subdominio'] +
                            ".wido.com.mx&ip_address=104.236.24.225")

                        url = urllib.urlopen(
                            "https://api.digitalocean.com/v1/domains/new?client_id=30c316cd106ea8d3aec887283db8dd24&api_key=972292751ed197d894365b2df49c771e&name=www."
                            + request.POST['subdominio'] +
                            ".wido.com.mx&ip_address=104.236.24.225")

                        site = Site()
                        site.domain = request.POST[
                            'subdominio'] + '.wido.com.mx'
                        site.name = request.POST['subdominio']
                        site.save()

                        cliente = Cliente()
                        cliente.nombre = request.POST['nombreCliente']
                        cliente.telefono = 'Desconocido'
                        cliente.mail = request.POST['mail']
                        cliente.sexo = 'N'
                        cliente.fecha = date.today()
                        cliente.usuario = 0
                        cliente.activo = 1
                        cliente.save()

                        admin = Administrador()
                        admin.nombre = request.POST['nombreCliente']
                        admin.login = request.POST['subdominio'] + str(
                            uuid.uuid4().hex)[:3]
                        admin.password = str(uuid.uuid4().hex)[:8]
                        admin.cliente = str(cliente.idclientes)
                        admin.activo = 1
                        admin.save()

                        tienda = Tienda()
                        tienda.nombre = request.POST['nombreTienda']
                        tienda.rfc = 'RFC Desconocido'
                        tienda.logo = 'Subir logo'
                        tienda.ubicacion = 'Domicilio Desconocido'
                        tienda.direccion = 'Domicilio Desconocido'
                        tienda.mail = 'mail Desconocido'
                        tienda.telefono = 'telefono desconocido'
                        tienda.descripcion = 'Desconocido'
                        tienda.activo = 0
                        tienda.administrador = admin
                        tienda.site_id = int(site.id)
                        tienda.save()

                        parametros = {
                            'mailreceptor':
                            request.POST['mail'],
                            'mailemisor':
                            '*****@*****.**',
                            'asunto':
                            'Bienvenido a WIDO',
                            'texto':
                            '<h1>Nuevo cliente</h1> <p>Nuevo Cliente con plan simple</p><p>Nombre '
                            + str(cliente.nombre) +
                            '<br>Datos de acceso:<br> usuario:' + admin.login +
                            '<br>clave: ' + admin.password
                        }

                        setMensaje(parametros)

                        stock = Stock()
                        stock.fecha = date.today()
                        stock.descripcion = 'Stock de la tienda ' + request.POST[
                            'nombreTienda']
                        stock.tienda = tienda
                        stock.save()

                        tp = Tipocliente()
                        tp.nombre = 'Casual'
                        tp.descripcion = 'Cliente Casual de tienda ' + unicode(
                            request.POST['subdominio'])
                        tp.prioridad = 1
                        tp.stock_idstock = stock
                        tp.save()

                        contrato = Contrato()
                        contrato.inicio = date.today()
                        current_date = date.today()
                        """new_month=divmod(current_date.month-1+1, 12)
						new_month+=1
						current_date=current_date.replace(year=current_date.year+carry, month=new_month)"""

                        contrato.fin = date.today() + timedelta(days=7)
                        contrato.fecha = date.today()
                        contrato.tienda = str(tienda.idtienda)
                        contrato.clientes_idclientes = cliente
                        contrato.activo = 1
                        contrato.save()

                        privilegio = Privilegios()
                        #privilegio.nivel=request.POST['planes']
                        privilegio.nivel = 'Bronce'
                        privilegio.descripcion = 'Conocida'
                        privilegio.activo = 1
                        privilegio.contrato = contrato
                        privilegio.save()

                        ct = ClientesTiendas()
                        ct.clientes = cliente
                        ct.tiendas = str(tienda.idtienda)
                        ct.activo = 1
                        ct.save()

                        conjunto = Conjunto()
                        conjunto.tienda = int(tienda.idtienda)
                        conjunto.fecha = date.today()
                        conjunto.activo = 1
                        conjunto.cms = Cms.objects.get(idcms=1)
                        conjunto.save()

                        secciones = Secciones()
                        secciones.nombre = 'Pie'
                        secciones.titulo = 'Pie de Pagina'
                        secciones.contenido = 'plantilla1/footer.html'
                        secciones.activo = 1
                        secciones.conjunto = conjunto
                        secciones.save()

                        secciones = Secciones()
                        secciones.nombre = 'Cabecera'
                        secciones.titulo = 'Cabecera de Pagina'
                        secciones.contenido = 'plantilla1/header.html'
                        secciones.activo = 1
                        secciones.conjunto = conjunto
                        secciones.save()

                        secciones = Secciones()
                        secciones.nombre = 'Cuerpo'
                        secciones.titulo = 'Cuerpo de Pagina'
                        secciones.contenido = 'Conocido'
                        secciones.activo = 1
                        secciones.conjunto = conjunto
                        secciones.save()

                        os.mkdir(
                            '/opt/wido/Plataforma/storeapp/static/imagenes/tiendas/'
                            + unicode(request.POST['nombreTienda']).replace(
                                ' ', '-'))

                        #parametros={
                        #    'mailreceptor':'*****@*****.**',
                        #    'mailemisor':request.POST['mail'],
                        #    'asunto':'Nuevo Cliente',
                        #    'texto':'<h1>Nuevo cliente</h1> <p>Nuevo Cliente con plan simple</p><p>Nombre '+str(cliente.nombre)+'</p><p>Referencia '+str(cliente.idclientes)+'</p>',
                        #    }
                        #setMensaje(parametros)
                        #plan=request.POST['planes']
                        #total=0
                        #if plan == 'Bronce':
                        #	total=200
                        #elif plan=='Plata':
                        #	total=300
                        #else:
                        #	total=400

                        #parametros={
                        #        'mailreceptor':request.POST['mail'],
                        #        'mailemisor':'*****@*****.**',
                        #        'asunto':'Nuevo Cliente',
                        #        'texto':'<!DOCTYPE html> <html lang="es"> <style type="text/css"> h1 {font-size: 2.7em; margin: 0; } h2 {font-size: 2em; } ul {list-style: none; width: 80%; margin-left: 25px; } #todo {padding: 40px; width: 800px; } #logo {width: 25%; height: 300px; display: inline-block; margin-right: 32px; } #logo img {width: 100%; } #derecha {width: 70%; height: auto; display: inline-block; vertical-align: top; } #derecha img {width: 60%; } #total {font-size:2em; font-weight: bold; } #nota {font-size: 18px; } #contenedor-total {margin-left: 40px; margin-bottom: 30px; margin-top: 20px; } .etiqueta {font-size: 18px; } </style> <head> <meta charset="utf-8" /> <title>Pago bancario</title> </head> <body> <header> </header> <div id="todo"> <div id="logo"> <img src="http://subdominios.wido.mx/wido.png"> </div> <div id="derecha"> <h1>Agradecemos tu preferencia</h1> <h2>Informaci&oacute;n de pago</h2> <img src="http://proyectopuente.com.mx/Content/images/posts/banamex.gif"> <ul> <li> <label class="etiqueta" >Beneficiario: Juan Perez</label> </li> <li> <label class="etiqueta" >Sucursal: 0706</label> </li> <li> <label class="etiqueta" >Cuenta: 2331512</label> </li> <li> <label class="etiqueta" >Clabe Interbancaria: 002357070623315125</label> </li> <li> <label class="etiqueta" >Referencia: '+str(cliente.idclientes)+'</label> </li> </ul> </div> <div id="contenedor-total"> <label id="total">Total a pagar: $'+str(total)+'.00</label> </div> <p id="nota"> Nota: Para poder identificar tu pago es importante coloques el numero de referencia a tu deposito. <br> Los pagos salvo buen cobro demoran 72 horas h&aacute;biles. </p> </div> <footer> </footer> </body> </html>',
                        #        }

                        #setMensaje(parametros)"""

                        #params = urllib.urlencode({'user':'******','clave':'30UmjCz90m','subdominio':request.POST['subdominio']})
                        #url=urllib.urlopen("http://subdominios.wido.mx/crear.php",params)

            else:
                datos['Error'] = True
                datos['letras'] = 'Correo inválido'

            return HttpResponse(json.dumps(datos),
                                content_type='application/json;charset=utf8')
    else:
        raise Http404
Example #55
0
 def test_get_site_id_from_site(self):
     site = Site()
     site.id = 10
     self.assertEqual(10, get_site_id(site))
Example #56
0
 def test_user_seen_no_default(self, seen):
     user = User(username='******', pk=1)
     site = Site(pk=2)
     user_seen(user, module="test", site=site)
     seen.assert_called_with(user, module="test", site=site)
Example #57
0
class SitesFrameworkTests(TestCase):
    multi_db = True

    def setUp(self):
        self.site = Site(
            id=settings.SITE_ID,
            domain="example.com",
            name="example.com",
        )
        self.site.save()

    def test_site_manager(self):
        # Make sure that get_current() does not return a deleted Site object.
        s = Site.objects.get_current()
        self.assertIsInstance(s, Site)
        s.delete()
        self.assertRaises(ObjectDoesNotExist, Site.objects.get_current)

    def test_site_cache(self):
        # After updating a Site object (e.g. via the admin), we shouldn't return a
        # bogus value from the SITE_CACHE.
        site = Site.objects.get_current()
        self.assertEqual("example.com", site.name)
        s2 = Site.objects.get(id=settings.SITE_ID)
        s2.name = "Example site"
        s2.save()
        site = Site.objects.get_current()
        self.assertEqual("Example site", site.name)

    def test_delete_all_sites_clears_cache(self):
        # When all site objects are deleted the cache should also
        # be cleared and get_current() should raise a DoesNotExist.
        self.assertIsInstance(Site.objects.get_current(), Site)
        Site.objects.all().delete()
        self.assertRaises(Site.DoesNotExist, Site.objects.get_current)

    @override_settings(ALLOWED_HOSTS=['example.com'])
    def test_get_current_site(self):
        # Test that the correct Site object is returned
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example.com",
            "SERVER_PORT": "80",
        }
        site = get_current_site(request)
        self.assertIsInstance(site, Site)
        self.assertEqual(site.id, settings.SITE_ID)

        # Test that an exception is raised if the sites framework is installed
        # but there is no matching Site
        site.delete()
        self.assertRaises(ObjectDoesNotExist, get_current_site, request)

        # A RequestSite is returned if the sites framework is not installed
        with self.modify_settings(
                INSTALLED_APPS={'remove': 'django.contrib.sites'}):
            site = get_current_site(request)
            self.assertIsInstance(site, RequestSite)
            self.assertEqual(site.name, "example.com")

    @override_settings(SITE_ID='', ALLOWED_HOSTS=['example.com'])
    def test_get_current_site_no_site_id(self):
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example.com",
            "SERVER_PORT": "80",
        }
        del settings.SITE_ID
        site = get_current_site(request)
        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)

    def test_clear_site_cache(self):
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example.com",
            "SERVER_PORT": "80",
        }
        self.assertEqual(models.SITE_CACHE, {})
        get_current_site(request)
        expected_cache = {self.site.id: self.site}
        self.assertEqual(models.SITE_CACHE, expected_cache)

        with self.settings(SITE_ID=''):
            get_current_site(request)

        expected_cache.update({self.site.domain: self.site})
        self.assertEqual(models.SITE_CACHE, expected_cache)

        clear_site_cache(Site, instance=self.site, using='default')
        self.assertEqual(models.SITE_CACHE, {})

    @override_settings(SITE_ID='')
    def test_clear_site_cache_domain(self):
        site = Site.objects.create(name='example2.com', domain='example2.com')
        request = HttpRequest()
        request.META = {
            "SERVER_NAME": "example2.com",
            "SERVER_PORT": "80",
        }
        get_current_site(request)  # prime the models.SITE_CACHE
        expected_cache = {site.domain: site}
        self.assertEqual(models.SITE_CACHE, expected_cache)

        # Site exists in 'default' database so using='other' shouldn't clear.
        clear_site_cache(Site, instance=site, using='other')
        self.assertEqual(models.SITE_CACHE, expected_cache)
        # using='default' should clear.
        clear_site_cache(Site, instance=site, using='default')
        self.assertEqual(models.SITE_CACHE, {})
Example #58
0
 def setUp(self):
     Site(id=settings.SITE_ID, domain="example.com",
          name="example.com").save()
     self.old_Site_meta_installed = Site._meta.installed
     Site._meta.installed = True
Example #59
0
 def create_site(self, form):
     site = Site(name=form.cleaned_data["name"],
                 domain=form.cleaned_data["domain"])
     site.save()
     return site
Example #60
0
 def setUp(self):
     self.patcher = patch.object(Site.objects, 'get_current')
     self.mock = self.patcher.start()
     self.mock.return_value = Site(domain='badge.mo.com', name='test')