def test_category_page(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the site site = Site() site.name = 'example.com' site.domain = 'example.com' site.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.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the category URL category_url = post.category.get_absolute_url() # Fetch the category response = self.client.get(category_url) self.assertEquals(response.status_code, 200) # Check the category name is in the response self.assertTrue(post.category.name in response.content) # Check the post text is in the response self.assertTrue(markdown2.markdown(post.text) in response.content) # Check the post date is in the response 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)
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_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_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)
def test_tag_page(self): # 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 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.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Get the tag URL tag_url = post.tags.all()[0].get_absolute_url() # Fetch the tag response = self.client.get(tag_url) self.assertEquals(response.status_code, 200) # Check the tag name is in the response self.assertTrue(post.tags.all()[0].name.encode() in response.content) # Check the post text is in the response self.assertTrue( markdown.markdown(post.text).encode() in response.content) # Check the post date is in the response self.assertTrue(str(post.pub_date.year) in response.content) self.assertTrue( _date(post.pub_date, "F").encode('utf-8') 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)
def create_default_site(sender, verbosity, created_models, **kwargs): """ Create the default site upon 'syncdb' of 'django.contrib.sites'. Uses options from settings.py: SITE_ID, SITE_DOMAIN, SITE_NAME. """ if Site in created_models: # delete Site objects just created by default by django.contrib.sites Site.objects.all().delete() # read options from settings.py identifier = getattr(settings, 'SITE_ID', 1) domain = getattr(settings, 'SITE_DOMAIN', 'example.com') name = getattr(settings, 'SITE_NAME', 'example.com') # create new default Site default_site = Site() default_site.domain = domain default_site.name = name default_site.pk = identifier default_site.save() if verbosity >= 2: print "Creating default Site '%s'" % (default_site.domain) Site.objects.clear_cache()
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)
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 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()
def handle(self, *args, **options): from corehq.apps.users.models import WebUser from corehq.apps.domain.shortcuts import create_domain if len(args) != 3: raise CommandError( 'Usage: manage.py bootstrap <domain> <email> <password>') domain_name, username, passwd = args domain = create_domain(domain_name) couch_user = WebUser.create(domain_name, username, passwd) couch_user.add_domain_membership(domain_name, is_admin=True) couch_user.is_superuser = True couch_user.is_staff = True couch_user.save() print "user %s created and added to domain %s" % (couch_user.username, domain) try: site = Site.objects.get(pk=1) except ObjectDoesNotExist: site = Site() site.save() site.name = 'localhost:8000' site.domain = 'localhost:8000' site.save()
def run(): Site.objects.all().delete() site = Site() site.id = settings.SITE_ID site.name = settings.SITE_NAME if settings.DEBUG: site.domain = '127.0.0.1:8000' else: site.domain = 'www.' + settings.SITE_DOMAIN site.save() for name, email in settings.ADMINS: user = User.objects.create_superuser(email.split('@')[0], email, 'temp123') user.first_name, user.last_name = name.split() user.save()
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)
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)
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)
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()
def check_sites(self): print "Checking URL configuration...", try: site = Site.objects.get_current() except Site.DoesNotExist: try: sid = settings.SITE_ID except AttributeError: from django.core.exceptions import ImproperlyConfigured raise ImproperlyConfigured( "You're using the Django \"sites framework\" without having set the SITE_ID " "setting. Create a site in your database and rerun this command to fix this error." ) else: print( "none set.\n" "Please enter the domain where Mumble-Django is reachable." ) dom = raw_input("> ").strip() site = Site(id=sid, name=dom, domain=dom) site.save() if site.domain == 'example.com': print( "still the default.\n" "The domain is configured as example.com, which is the default but does not make sense. " "Please enter the domain where Mumble-Django is reachable.") site.domain = raw_input("> ").strip() site.save() print site.domain, "[ OK ]"
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)
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)
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)
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
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)
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 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()
def run(): Site.objects.all().delete() site = Site() site.id = settings.SITE_ID site.name = settings.SITE_NAME if settings.DEBUG: site.domain = '127.0.0.1:8000' else: site.domain = 'www.' + settings.SITE_DOMAIN site.save() for name, email in settings.ADMINS: user = User.objects.create_superuser( email.split('@')[0], email, 'temp123') user.first_name, user.last_name = name.split() user.save()
def handle(self, *args, **options): try: site = Site.objects.get() except Site.DoesNotExist: site = Site() site.name = 'Healersource' site.domain = 'www.healersource.com' site.save()
def test_delete_post(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 site site = Site() site.name = 'example.com' site.domain = 'example.com' site.save() # Create the author author = User.objects.create_user( 'testuser', '*****@*****.**', 'password') author.save() # Create the 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.category = category post.site = site post.save() post.tags.add(tag) post.save() # Check new post saved all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) # Log in self.client.login(username='******', password="******") id_ = Post.objects.all()[0].id # Delete the post response = self.client.post( '/admin/blogengine/post/{0}/delete/'.format(id_), { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue('deleted successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def configure_site_object(sender, created_models, **kwargs): if Site in created_models: try: current_site = Site.objects.get(id=settings.SITE_ID) except Site.DoesNotExist: current_site = Site(id=settings.SITE_ID) current_site.domain = settings.SITE_DOMAIN current_site.name = settings.SITE_NAME current_site.save()
def handle(self, *args, **options): site_url = os.getenv("SITE_URL", "http://0.0.0.0:80") domain = site_url.split('://')[-1] site = Site.objects.first() if not site: # The site site = Site() site.domain = domain site.save() logger.info('Site domain successfully set to %s', domain)
def test_delete_post(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 the 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.site = site post.author = author 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) # Log in self.client.login(username='******', password="******") # Delete the post response = self.client.post('/admin/blogengine/post/1/delete/', { 'post': 'yes' }, follow=True) self.assertEquals(response.status_code, 200) # Check deleted successfully self.assertTrue('deleted successfully' in response.content) # Check post deleted all_posts = Post.objects.all() self.assertEquals(len(all_posts), 0)
def test_edit_post(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 category category = Category() category.name = 'Python' category.description = 'Python is a rad language' category.save() # Create the post post = Post() post.title = 'My First Post' post.text = 'This is my first blog post' post.slug = 'my-first-post' post.site = site post.pub_date = timezone.now() post.author = author post.category = category post.save() # Log in self.client.login(username='******', password='******') # Edit the Post response = self.client.post('/admin/blogengine/post/1/', { 'title': 'My second post', 'text': 'This is my second blog post', 'pub_date_0': '2014-05-06', 'pub_date_1': '22:00:04', 'slug': 'my-second-post', 'site': 1, 'author': 1, 'category': 1 }, follow=True) self.assertEquals(response.status_code, 200) # check changed successfully self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'My second post') self.assertEquals(only_post.text, 'This is my second blog post')
def test_edit_post(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" post.slug = "my-first-post" post.pub_date = timezone.now() post.author = author post.site = site post.save() # Log in self.client.login(username="******", password="******") # Edit the post response = self.client.post( "/admin/blogengine/post/1/", { "title": "My second post", "text": "This is my second blog post", "pub_date_0": "2013-12-28", "pub_date_1": "22:00:04", "slug": "my-second-post", "site": "1", "category": "1", }, follow=True, ) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue("changed successfully" in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, "My second post") self.assertEquals(only_post.text, "This is my second blog post")
def handle(self, *args, **options): domain = options['domain'] try: site = Site.objects.get(id=settings.SITE_ID) except Site.DoesNotExist: site = Site(id=settings.SITE_ID) site.domain = domain site.name = 'Primary domain' site.full_clean() site.save() self.stdout.write('Primary domain successfully setup.')
def test_create_post(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() # Set the attributes 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() # 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) # 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.author.username, "testuser") self.assertEquals(only_post.author.email, "*****@*****.**") self.assertEquals(only_post.category.name, "python") self.assertEquals(only_post.category.description, "The Python programming language")
def install_sites(signal, sender, app, created_models, **kwargs): # only run when our model got created print 'post_syncdb signal: Installing sites...' for k,v in SITE_DICT.items(): try: s = Site.objects.get(id=v['id']) except Site.DoesNotExist: s = Site(id=v['id']) s.domain=k s.name=v['name'] s.save() print u'post_syncdb signal: - Installed ' + unicode(v['name'] + '.')
def create_site(self): # SITE if Site.objects.all(): site = Site.objects.all()[0] else: site = Site() site.domain = "localhost:8000" site.name = "CyclopeCMS demo" site.save() # CONTACT FORM ContactFormSettings.objects.create(subject="Contact mail") return site
def test_create_post(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() # Set the attributes 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() # Check we can find it all_posts = Post.objects.all() self.assertEqual(len(all_posts), 1) only_post = all_posts[0] self.assertEqual(only_post, post) # Check attributes self.assertEqual(only_post.title, 'My first post') self.assertEqual(only_post.text, 'This is my first blog post') self.assertEqual(only_post.slug, 'my-first-post') self.assertEqual(only_post.pub_date.day, post.pub_date.day) self.assertEqual(only_post.pub_date.month, post.pub_date.month) self.assertEqual(only_post.pub_date.year, post.pub_date.year) self.assertEqual(only_post.pub_date.hour, post.pub_date.hour) self.assertEqual(only_post.pub_date.minute, post.pub_date.minute) self.assertEqual(only_post.pub_date.second, post.pub_date.second) self.assertEqual(only_post.author.username, 'testuser') self.assertEqual(only_post.author.email, '*****@*****.**') self.assertEqual(only_post.category.name, 'python') self.assertEqual(only_post.category.description, 'The Python programming language')
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.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 the post text is in the response self.assertTrue(markdown.markdown(post.text) in response.content) # Check the post category is in the response self.assertTrue(post.category.name in response.content) # Check the post date is in the response 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)
def test_sync(self): # Create Site without triggering signals site = Site(domain='example.com') site.save_base(raw=True) # Insert Alias self.assertFalse(Alias.objects.filter(site=site).exists()) Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Idempotent sync_alias Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Duplicate force_insert self.assertRaises(ValidationError, Alias.sync, site=site, force_insert=True) # Update Alias site.domain = 'example.org' Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Clear domain site.domain = '' Alias.sync(site=site) self.assertFalse(Alias.objects.filter(site=site).exists())
def test_sync(self): # Create Site without triggering signals site = Site(domain='example.com') site.save_base(raw=True) # Insert Alias self.assertFalse(Alias.objects.filter(site=site).exists()) Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Idempotent sync_alias Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Duplicate force_insert self.assertRaises(ValidationError, Alias.sync, site=site, force_insert=True) # Update Alias site.domain = 'example.org' Alias.sync(site=site) self.assertEqual(Alias.objects.get(site=site).domain, site.domain) # Clear domain site.domain = '' Alias.sync(site=site) self.assertFalse(Alias.objects.filter(site=site).exists())
def send_mail(self, template_prefix, email, context): account_confirm_email = '/User/'+str(context['user'].pk)+'/activate/' context['activate_url'] = ( str('http://127.0.0.1:3000') + account_confirm_email ) print(template_prefix) s = Site() s.domain = 'EventHub' s.name = 'EventHub' context['current_site'] = ( s ) msg = self.render_mail(template_prefix, email, context) print(msg.send())
def test_edit_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.save() post.tags.add(tag) post.save() self.client.login(username='******', password="******") # Edit post response = self.client.post('/admin/blogengine/post/1/', { 'title': 'My second post', 'text': 'This is my second blog post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-second-post', 'site': '1', 'category': '1', 'tags': '1', }, follow=True ) self.assertEquals(response.status_code, 200) self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'My second post') self.assertEquals(only_post.text, 'This is my second blog post')
def test_individual_post(self): category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() tag = Tag() tag.name = 'java' tag.description = 'The Java 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](http://127.0.0.1:8000/)' post.pub_date = timezone.now() post.slug = 'my-first-post' post.site = site post.category = category post.save() post.tags.add(tag) post.save() all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) post_url = only_post.get_absolute_url() response = self.client.get(post_url) self.assertEquals(response.status_code, 200) 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) self.assertTrue('<a href="http://127.0.0.1:8000/">my first blog post</a>' in response.content)
def site(request): """ Set up the site. """ # TODO: Support a form to set this... try: site = Site.objects.get(pk=1) except: site = Site() site.id = 1 site.name = "Holloway" site.domain = "http://localhost" site.save() return redirect('wizard_social') return render(request, "wizard/site.html")
def site(request): """ Set up the site. """ # TODO: Support a form to set this... try: site = Site.objects.get(pk=1) except: site = Site() site.id = 1 site.name = "Holloway" site.domain = "http://localhost" site.save() return redirect('wizard_social') return render(request, "wizard/site.html")
def create_site(self): domain = "127.0.0.1:8000" if settings.DEBUG else gethostname() if self.interactive: entered = input("\nA site record is required.\nPlease " "enter the domain and optional port in " "the format 'domain:port'.\nFor example " "'localhost:8000' or 'www.example.com'. " "\nHit enter to use the default (%s): " % domain) if entered: domain = entered.strip("': ") if self.verbosity >= 1: print("\nCreating default site record: %s ...\n" % domain) try: site = Site.objects.get() except Site.DoesNotExist: site = Site() site.name = "Default" site.domain = domain site.save()
def teste_create_post(self): # Create the tag tag = Tag() tag.name = 'python' tag.description = 'The Python programming language' tag.save() # 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() # cria o post post = Post() post.title = 'Meu primeiro post' post.text = 'Este é meu primeiro post do blog' post.slug = "my-first-post" post.pub_date = timezone.now() post.author = author post.site = site post.category = category # salva o post no banco de dados post.save() # Add the tag post.tags.add(tag) post.save() # verifica se conseguimos encontrá-lo all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEqual(only_post, post) # verifica os atributos self.assertEqual(only_post.title, 'Meu primeiro post') self.assertEqual(only_post.text, u'Este é meu primeiro post do blog') self.assertEqual(only_post.slug, 'my-first-post') self.assertEquals(only_post.site.name, 'example.com') self.assertEquals(only_post.site.domain, 'example.com') self.assertEqual(only_post.pub_date.day, post.pub_date.day) self.assertEqual(only_post.pub_date.month, post.pub_date.month) self.assertEqual(only_post.pub_date.year, post.pub_date.year) self.assertEqual(only_post.pub_date.hour, post.pub_date.hour) self.assertEqual(only_post.pub_date.minute, post.pub_date.minute) self.assertEqual(only_post.pub_date.second, post.pub_date.second) self.assertEquals(only_post.author.username, 'testuser') self.assertEquals(only_post.author.email, '*****@*****.**') 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_index(self): # Create the category category = Category() category.name = 'python' category.description = 'The Python programming language' category.save() # Create the tag tag = Tag() tag.name = 'perl' tag.description = 'The Perl 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 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) # 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 the post title is in the response self.assertTrue(post.title in response.content) # Check the post text is in the response self.assertTrue(markdown.markdown(post.text) in response.content) # Check the post category is in the response self.assertTrue(post.category.name in response.content) # Check the post tag is in the response post_tag = all_posts[0].tags.all()[0] self.assertTrue(post_tag.name in response.content) # Check the post date is in the response 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)
def test_edit_post(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 the 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.save() post.tags.add(tag) post.save() # Log in self.client.login(username='******', password="******") # Edit the post response = self.client.post('/admin/blogengine/post/1/', { 'title': 'My second post', 'text': 'This is my second blog post', 'pub_date_0': '2013-12-28', 'pub_date_1': '22:00:04', 'slug': 'my-second-post', 'site': '1', 'category': '1', 'tags': '1' }, follow=True ) self.assertEquals(response.status_code, 200) # Check changed successfully self.assertTrue('changed successfully' in response.content) # Check post amended all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post.title, 'My second post') self.assertEquals(only_post.text, 'This is my second blog post')
def course_wiki_redirect(request, course_id): # pylint: disable=unused-argument """ 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( SlashSeparatedCourseKey.from_deprecated_string(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) if site_id != str(settings.SITE_ID): msg = "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}".format( site_id, settings.SITE_ID) raise ImproperlyConfigured(msg) 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_escaped, )) 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)
def run(): from django.contrib.sites.models import Site django_site_1 = Site() django_site_1.domain = u'localhost' django_site_1.name = u'localhost' django_site_1.save() from corehq.apps.domain.models import Domain domain_domain_1 = Domain() domain_domain_1.name = u'test' domain_domain_1.is_active = True domain_domain_1.save() from corehq.apps.domain.models import Membership domain_membership_1 = Membership() domain_membership_1.domain = domain_domain_1 domain_membership_1.member_type = ContentType.objects.get(app_label="auth", model="user") domain_membership_1.member_id = 2 domain_membership_1.is_active = True domain_membership_1.save() from django_granular_permissions.models import Permission django_granular_permissions_permission_1 = Permission() django_granular_permissions_permission_1.name = u'admin' django_granular_permissions_permission_1.content_type = ContentType.objects.get( app_label="domain", model="domain") django_granular_permissions_permission_1.object_id = 1 django_granular_permissions_permission_1.group = None django_granular_permissions_permission_1.save() from django.contrib.auth.models import User auth_user_1 = User() auth_user_1.username = u'testadmin' auth_user_1.first_name = u'' auth_user_1.last_name = u'' auth_user_1.email = u'*****@*****.**' auth_user_1.password = u'sha1$f8d4b$b6d2f6431c423687c227ad261caa46faaf16917d' auth_user_1.is_staff = True auth_user_1.is_active = True auth_user_1.is_superuser = True auth_user_1.last_login = datetime.datetime(2010, 9, 10, 14, 40, 30, 501416) auth_user_1.date_joined = datetime.datetime(2010, 9, 10, 14, 37, 22, 677987) auth_user_1.save() auth_user_2 = User() auth_user_2.username = u'test' auth_user_2.first_name = u'test' auth_user_2.last_name = u'test' auth_user_2.email = u'*****@*****.**' auth_user_2.password = u'sha1$f09cf$551ac80804020ad3e1d9943a583ee1ea52284797' auth_user_2.is_staff = False auth_user_2.is_active = True auth_user_2.is_superuser = False auth_user_2.last_login = datetime.datetime(2010, 9, 10, 14, 40, 53, 818764) auth_user_2.date_joined = datetime.datetime(2010, 9, 10, 19, 40, 6, 159442) auth_user_2.save() auth_user_2.domain_membership.add(domain_membership_1) from corehq.apps.domain.models import RegistrationRequest domain_registration_request_1 = RegistrationRequest() domain_registration_request_1.tos_confirmed = True domain_registration_request_1.request_time = datetime.datetime( 2010, 9, 10, 19, 40, 6, 159442) domain_registration_request_1.request_ip = '127.0.0.1' domain_registration_request_1.activation_guid = u'368ce6b8bd1311df932c5cff350164a3' domain_registration_request_1.confirm_time = datetime.datetime( 2010, 9, 10, 14, 40, 25, 219783) domain_registration_request_1.confirm_ip = '127.0.0.1' domain_registration_request_1.domain = domain_domain_1 domain_registration_request_1.new_user = auth_user_2 domain_registration_request_1.requesting_user = None domain_registration_request_1.save() django_granular_permissions_permission_1.user = auth_user_2 django_granular_permissions_permission_1.save()
#Error: Site matching query does not exist. #Solved: http://stackoverflow.com/a/16068551/3445802 #settinsg.py SITE_ID = 1 INSTALLED_APPS = ( .... 'django.contrib.sites', ) $> ./manage.py shell >>> from django.contrib.sites.models import Site >>> site = Site() >>> site.domain = 'example.com' >>> site.name = 'example.com' >>> site.save()
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ó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á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
def handle(self, *args, **options): logger.info('start initial setup: ' + str(datetime.datetime.now())) logger.info('sites...') ind = 1 for st in lugati_sites: try: new_site = Site.objects.get(pk=ind) except: new_site = Site() new_site.id = ind new_site.domain = st[0] new_site.name = st[1] new_site.save() ind += 1 #deleting cur_ind = ind - 1 while True: cur_site = None try: cur_site = Site.objects.get(pk=ind) except: break if cur_site: cur_site.delete() cur_ind += 1 logger.info('order states...') ind = 1 for state in ORDER_STATES: try: cur_state = OrderState.objects.get(pk=ind) except: cur_state = OrderState() cur_state.custom_id = state[0] cur_state.name = state[1] cur_state.class_name = state[2] cur_state.save() ind += 1 logger.info('galeries...') for site in Site.objects.all(): if not GalleryItem.objects.filter(site=site).filter( title='default').exists(): gallery = GalleryItem() gallery.title = 'default' gallery.site = site gallery.save() logger.info('profiles...') for user in User.objects.all(): if not LugatiUserProfile.objects.filter(user=user).exists(): prof = LugatiUserProfile() prof.user = user prof.save() # self.install_fonts() logger.info('currencies...') currencies = [['RUR', 2, 'fa fa-rub', 'rub'], ['USD', 2, 'fa fa-usd', 'usd'], ['EUR', 2, 'fa fa-eur', 'eur'], ['BTC', 8, 'fa fa-btc', 'usd'], ['THB', 2, 'lugati-thb-icon', 'thb']] for currency in currencies: try: new_cur = LugatiCurrency.objects.get(name=currency[0]) except: new_cur = LugatiCurrency() new_cur.name = currency[0] new_cur.decimal_fields = currency[1] new_cur.icon_class_name = currency[2] new_cur.stripe_str = currency[3] new_cur.save() resp = requests.get('https://www.bitstamp.net/api/ticker/') btc_rate = json.loads(resp.text)['last'] for currency in LugatiCurrency.objects.all(): currency.btc_rate = float(btc_rate) currency.save() from lugati.lugati_payment import payment_procs payment_procs.update_curreynce_exchange_rates() if (User.objects.filter(username='******').count() == 0): user = User.objects.create_user('sola_postman', '*****@*****.**', 'Ai5eiy7i') user.save() if (LugatiRole.objects.filter(name='postman').count() == 0): role = LugatiRole() role.name = 'postman' role.save() else: role = LugatiRole.objects.get(name='postman') prof = lugati_procs.get_user_profile(user) prof.roles.add(role) logger.info('companies...') for prof in LugatiUserProfile.objects.all(): if not prof.company: new_company = LugatiCompany() new_company.default_currency = LugatiCurrency.objects.get( name='USD') new_company.name = 'new company' new_company.save() prof.company = new_company prof.save() if (LugatiRole.objects.filter(name='waiter').count() == 0): role = LugatiRole() role.name = 'waiter' role.save() self.intall_tooltips() self.delete_tooltips_notifications() self.init_ordering()
def handle_noargs(self, **options): from satchmo.contact.models import Contact, AddressBook, PhoneNumber from satchmo.product.models import ( Product, Price, ConfigurableProduct, ProductVariation, Category, OptionGroup, Option, ProductImage, ) # , DownloadableProduct from satchmo.shop.models import Config from django.conf import settings from satchmo.l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User # idempotency test print("Checking for existing sample data.") try: p = Product.objects.get(slug="dj-rocks") print( "It looks like you already have loaded the sample store data, quitting." ) import sys sys.exit(1) except Product.DoesNotExist: pass print("Loading sample store data.") # Load basic configuration information print("Creating site...") try: site = Site.objects.get(id=settings.SITE_ID) print(("Using existing site #%i" % settings.SITE_ID)) except Site.DoesNotExist: print("Creating Example Store Site") site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() store_country = Country.objects.get(iso3_code="USA") config = Config( site=site, store_name=settings.SITE_NAME, no_stock_checkout=True, country=store_country, sales_country=store_country, ) config.save() config.shipping_countries.add(store_country) config.save() print("Creating Customers...") # Import some customers c1 = Contact( first_name="Chris", last_name="Smith", email="*****@*****.**", role="Customer", notes="Really cool stuff", ) c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True) p1.save() c2 = Contact( first_name="John", last_name="Smith", email="*****@*****.**", role="Customer", notes="Second user", ) c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code="US") a1 = AddressBook( description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1, ) a1.save() a2 = AddressBook( description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2, ) a2.save() print("Creating Categories...") # Create some categories cat1 = Category(name="Shirts", slug="shirts", description="Women's Shirts") cat1.save() cat2 = Category( name="Short Sleeve", slug="shortsleeve", description="Short sleeve shirts", parent=cat1, ) cat2.save() cat3 = Category(name="Books", slug="book", description="Books") cat3.save() cat4 = Category( name="Fiction", slug="fiction", description="Fiction Books", parent=cat3 ) cat4.save() cat5 = Category( name="Science Fiction", slug="scifi", description="Science Fiction", parent=cat4, ) cat5.save() cat6 = Category( name="Non Fiction", slug="nonfiction", description="Non Fiction", parent=cat3, ) cat6.save() cat7 = Category(name="Software", slug="software") cat7.save() print("Creating products...") # Create some items i1 = Product( name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True, ) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product( name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True, ) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save() i3 = Product( name="A really neat book", slug="neat-book", description="A neat book. You should buy it.", active=True, featured=True, ) i3.save() p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat4) i3.save() i4 = Product( name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True, ) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() # Create an attribute set optSet1 = OptionGroup(name="sizes", sort_order=1) optSet2 = OptionGroup(name="colors", sort_order=2) optSet1.save() optSet2.save() optSet3 = OptionGroup(name="Book type", sort_order=1) optSet3.save() optSet4 = OptionGroup(name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option( name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1, ) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option( name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2, ) optItem2c.save() optItem3a = Option( name="Hard cover", value="hard", sort_order=1, option_group=optSet3 ) optItem3a.save() optItem3b = Option( name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3, ) optItem3b.save() optItem3c = Option( name="On tape", value="tape", sort_order=3, option_group=optSet3 ) optItem3c.save() optItem4a = Option( name="Full Version", value="full", option_group=optSet4, sort_order=1 ) optItem4a.save() optItem4b = Option( name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2 ) optItem4b.save() # Add the option group to our items pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save() pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save() # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print("Creating product variations...") # Create the required sub_items pg1.create_all_variations() pg3.create_all_variations() pg4.create_all_variations() # pg5.create_all_variations() # set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity=50).save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print("Create a test user...") # First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user( "csmith", "*****@*****.**", "test" ) test_user.save() c1.user = test_user c1.save()
from shop.models import Product from cms import api from django.utils.html import strip_tags from django.template.defaultfilters import slugify from decimal import Decimal import random User.objects.create_superuser('%(db_user)s', '%(db_user)s@%(servername)s', '%(db_password)s') try: site = Site.objects.get(pk=1) except Site.DoesNotExist: site = Site() site.domain = '%(servername)s' site.name = '%(project_name)s' site.save() user = User.objects.get(pk=1) home_page = api.create_page('Home', 'base_templates/front.html', 'en', menu_title='Home', created_by=user, in_navigation=False, published=True) api.create_title('nb', 'Hjem', home_page, menu_title='Hjem') search_page = api.create_page('Search', 'base_templates/default.html', 'en',
def test_create_post(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 the post post = Post() # Set the attributes 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) # 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.author.username, 'testuser') self.assertEquals(only_post.author.email, '*****@*****.**') 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 add_site(self, domain: str) -> Site: site = Site() site.domain = domain site.name = "Test " + domain site.save() return site
def handle_noargs(self, **options): from satchmo_store.contact.models import ( AddressBook, Contact, ContactOrganization, ContactOrganizationRole, ContactRole, Organization, PhoneNumber, ) from product.models import ( Category, OptionGroup, Option, Price, Product, ) from product.modules.configurable.models import ConfigurableProduct from satchmo_store.shop.models import Config from django.conf import settings from l10n.models import Country from django.contrib.sites.models import Site from django.contrib.auth.models import User #idempotency test print "Checking for existing sample data." try: p = Product.objects.get(slug="dj-rocks") print "It looks like you already have loaded the sample store data, quitting." import sys sys.exit(1) except Product.DoesNotExist: pass print "Loading sample store data." #Load basic configuration information print "Creating site..." try: site = Site.objects.get(id=settings.SITE_ID) print "Using existing site #%i" % settings.SITE_ID except Site.DoesNotExist: print "Creating Example Store Site" site = Site(domain="localhost", name="Sample Store") site.domain = settings.SITE_DOMAIN site.name = settings.SITE_NAME site.save() try: store_country = Country.objects.get(iso3_code='USA') except Country.DoesNotExist: print "\nError: Country data should be first loaded by: python manage.py satchmo_load_l10n" import sys sys.exit(1) config = Config(site=site, store_name=settings.SITE_NAME, country=store_country, sales_country=store_country) config.save() config.shipping_countries.add(store_country) config.save() print "Creating Customers..." # Import some customers customer = ContactRole.objects.get(pk='Customer') c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role=customer, notes="Really cool stuff") c1.save() p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True) p1.save() c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role=customer, notes="Second user") c2.save() p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True) p2.save() # Import some addresses for these customers us = Country.objects.get(iso2_code='US') a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN", postal_code="38138", country=us, is_default_shipping=True, contact=c1) a1.save() a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN", postal_code="55082", country=us, is_default_shipping=True, contact=c2) a2.save() print "Creating Suppliers..." #Import some suppliers supplier = ContactOrganizationRole.objects.get(pk='Supplier') company = ContactOrganization.objects.get(pk='Company') contactsupplier = ContactRole.objects.get(pk='Supplier') org1 = Organization(name="Rhinestone Ronny", type=company, role=supplier) org1.save() c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role=contactsupplier, organization=org1) c4.save() p4 = PhoneNumber(contact=c4, phone="800-188-7611", type="Work", primary=True) p4.save() p5 = PhoneNumber(contact=c4, phone="755-555-1111", type="Fax") p5.save() a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill", state="NJ", country=us, postal_code="19010") a3.save() #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200", # city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**", # notes="My main supplier") #s1.save() #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", # city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**", # notes="Shirt Supplier") #s2.save() print "Creating Categories..." #Create some categories cat1 = Category(site=site, name="Shirts", slug="shirts", description="Women's Shirts") cat1.save() cat2 = Category(site=site, name="Short Sleeve", slug="shortsleeve", description="Short sleeve shirts", parent=cat1) cat2.save() cat3 = Category(site=site, name="Books", slug="book", description="Books") cat3.save() cat4 = Category(site=site, name="Fiction", slug="fiction", description="Fiction Books", parent=cat3) cat4.save() cat5 = Category(site=site, name="Science Fiction", slug="scifi", description="Science Fiction", parent=cat4) cat5.save() cat6 = Category(site=site, name="Non Fiction", slug="nonfiction", description="Non Fiction", parent=cat3) cat6.save() cat7 = Category(site=site, name="Software", slug="software") cat7.save() print "Creating products..." #Create some items i1 = Product(site=site, name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt", active=True, featured=True) i1.save() p1 = Price(price="20.00", product=i1) p1.save() i1.category.add(cat1) i1.save() i2 = Product( site=site, name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", active=True, featured=True) i2.save() p2 = Price(price="19.50", product=i2) p2.save() i2.category.add(cat2) i2.save() i3 = Product(site=site, name="A really neat book", slug="neat-book", description="A neat book. You should buy it.", active=True, featured=True) i3.save() p3 = Price(price="5.00", product=i3) p3.save() i3.category.add(cat4) i3.save() i4 = Product(site=site, name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", active=True, featured=True) i4.save() p4 = Price(price="7.99", product=i4) p4.save() i4.category.add(cat5) i4.save() # i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True) # i5.save() # i5.category.add(cat7) # i5.save() #Create an attribute set optSet1 = OptionGroup(site=site, name="sizes", sort_order=1) optSet2 = OptionGroup(site=site, name="colors", sort_order=2) optSet1.save() optSet2.save() optSet3 = OptionGroup(site=site, name="Book type", sort_order=1) optSet3.save() optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5) optSet4.save() optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1) optItem1a.save() optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1) optItem1b.save() optItem1c = Option(name="Large", value="L", sort_order=3, price_change="1.00", option_group=optSet1) optItem1c.save() optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2) optItem2a.save() optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2) optItem2b.save() optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change="2.00", option_group=optSet2) optItem2c.save() optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3) optItem3a.save() optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change="1.00", option_group=optSet3) optItem3b.save() optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3) optItem3c.save() optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1) optItem4a.save() optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2) optItem4b.save() #Add the option group to our items pg1 = ConfigurableProduct(product=i1) pg1.save() pg1.option_group.add(optSet1) pg1.save() pg1.option_group.add(optSet2) pg1.save() pg3 = ConfigurableProduct(product=i3) pg3.save() pg3.option_group.add(optSet3) pg3.save() pg4 = ConfigurableProduct(product=i4) pg4.save() pg4.option_group.add(optSet3) pg4.save() # pg5 = ConfigurableProduct(product=i5) # pg5.option_group.add(optSet4) # pg5.save() print "Creating product variations..." #Create the required sub_items pg1.create_all_variations() pg3.create_all_variations() pg4.create_all_variations() #pg5.create_all_variations() #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required. # pv1 = pg5.get_product_from_options([optItem4a]) # Price(product=pv1, price='5.00').save() # Price(product=pv1, price='2.00', quantity='50.00').save() # DownloadableProduct(product=pv1).save() # pv2 = pg5.get_product_from_options([optItem4b]) # Price(product=pv2, price='1.00').save() # DownloadableProduct(product=pv2).save() print "Create a test user..." #First see if our test user is still there, then use or create that user try: test_user = User.objects.get(username="******") except: test_user = User.objects.create_user('csmith', '*****@*****.**', 'test') test_user.save() c1.user = test_user c1.save()
def course_wiki_redirect(request, course_id): """ 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 # cdodge: fix for cases where self.location.course can be interpreted as an number rather than # a string. We're seeing in Studio created courses that people often will enter in a stright number # for 'course' (e.g. 201). This Wiki library expects a string to "do the right thing". We haven't noticed this before # because - to now - 'course' has always had non-numeric characters in them try: float(course_slug) # if the float() doesn't throw an exception, that means it's a number course_slug = course_slug + "_" except: pass 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 = Site.objects.get_current() except Site.DoesNotExist: new_site = Site() new_site.domain = settings.SITE_NAME new_site.name = "edX" new_site.save() if str(new_site.id) != str(settings.SITE_ID): raise ImproperlyConfigured( "No site object was created and the SITE_ID doesn't match the newly created one. " + str(new_site.id) + "!=" + str(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() urlpath = URLPath.create_article( root, course_slug, title=course_slug, content="This is the wiki for **{0}**'s _{1}_.".format( course.org, course.display_name_with_default), 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)