def _add_avatar(post_data, files, profile): form = AvatarForm(post_data, files) if form.is_valid(): image = form.cleaned_data['image'] image_url = form.cleaned_data['image_url'] if image: photo = Photo.objects.create(profile=profile, image=image) else: result = urllib.request.urlretrieve(image_url) photo = Photo(profile=profile) photo.image.save( 'random.jpg', File(open(result[0], 'rb')) ) photo.save() os.remove(result[0]) photo.add_thumbnail(form.cleaned_data['rel_top'], form.cleaned_data['rel_left'], form.cleaned_data['rel_width'], form.cleaned_data['rel_height']) photo.add_small_thumbnail() photo.save() profile.avatar = photo profile.save() Post.create_photo_post(photo) dispatch('ADD_AVATAR', profile) return photo return None
def answer_question(req, id): """ View for accepting answers """ profile = ( DP.objects .prefetch_related('answers') .prefetch_related('answers__question') .get(user=req.user) ) question = get_object_or_404(Question, pk=id) try: answer = profile.answers.get(question__id=id) except ObjectDoesNotExist: answer = Answer(question=question, profile=profile) form = AnswerForm(req.POST, instance=answer) if form.is_valid(): answer = form.save(commit=True) Post.create_answer_post(answer) dispatch('ANSWER_QUESTION', profile, question=question) return HttpResponse('ok') return HttpResponse(str(form.errors), status=400)
def sitemap(request, sitemapname): if sitemapname == Landingpage.get_sitemap_info(domain).get('name', ''): return render(request, 'sitemap/sitemap.xml', {'sitemap': Landingpage.get_sitemap(domain, 1)}, content_type='text/xml') if sitemapname == Post.get_sitemap_info(domain).get('name', ''): return render(request, 'sitemap/sitemap.xml', {'sitemap': Post.get_sitemap(domain, 0.8)}, content_type='text/xml') if sitemapname == Page.get_sitemap_info(domain).get('name', ''): return render(request, 'sitemap/sitemap.xml', {'sitemap': Page.get_sitemap(domain, 0.8)}, content_type='text/xml') if sitemapname == Testimonial.get_sitemap_info(domain).get('name', ''): return render(request, 'sitemap/sitemap.xml', {'sitemap': Testimonial.get_sitemap(domain, 0.8)}, content_type='text/xml') return render(request, 'sitemap/sitemap.xml', { 'sitemap': [{ 'loc': 1 }, { 'loc': 2 }], 'priority': '0.1', }, content_type='text/xml')
def news_update(request, id): if request.method=="GET": post = get_object_or_404(Post, id=id) post_form = PostForm(instance=post) update = {'edit':True} return render_to_response('news_form.html', {'form': post_form, 'update':update}, context_instance=RequestContext(request)) #Manage POST requests. else: post_form = PostForm(request.POST) if post_form.is_valid(): pf = post_form.save(commit=False) if pf.post or pf.url : post = Post(id=id) post.name, post.url, post.post = pf.name, pf.url, pf.post post.save() return HttpResponseRedirect("/news/"+ str(id)+"/") else: form_errors = {"Empty Fields - You at least need to have filled the URL or Post Field."} return render_to_response('news_form.html', {'form': post_form,'form_errors': form_errors}, context_instance=RequestContext(request)) else: return render_to_response('news_form.html', {'form': post_form,'form_errors': post_form.errors}, context_instance=RequestContext(request))
def seed_from_fake(): "This seeds a DB with fake text, using the faker" # create a fake factory fake = Factory.create() # print is as sanity check print(fake.text()) # open or make text file text_file = open("Output.txt", "w") # 50 times for i in range(50): # make some fake text fake_text = fake.text() # this just gives stupid text # # print fake text # print(fake_text[:49]) # # print seperator # print("_____________") # make new post # split the text up to make a title and post title = fake_text[:49] text = fake_text post = Post(title=fake_text, text=text) post.save()
def test_was_published_recently_with_old_news(self): ''' was_published_recently() should return False for news older than one week ''' old_news = Post(pub_date=timezone.now() - datetime.timedelta(days=30)) self.assertEqual(old_news.was_published_recently(), False)
def test_was_published_recently_with_future_news(self): ''' was_published_recently() should return False for news published in future ''' future_news = Post(pub_date=timezone.now() + datetime.timedelta(days=30)) self.assertEqual(future_news.was_published_recently(), False)
def new_post(text): graph = access_page() o = graph.put_object(parent_object='me', connection_name='feed', message=text) p = Post(fbid=o['id'], text=text) p.save() return p
def new_post(text): graph = access_page() o = graph.put_object( parent_object='me', connection_name='feed', message=text) p = Post(fbid=o['id'], text=text) p.save() return p
def save(self, commit=True): author = self.initial.get('author') is_approved = False if author.has_perm('news.post_no_premoderation'): is_approved = True post = Post(author=author, title=self.cleaned_data.get('title'), text=self.cleaned_data.get('text'), is_approved=is_approved) post.save() return post
def handle(self, *args, **options): self.stdout.write(self.style.SUCCESS('Start parsing ycombinator.com')) news = ycombinator() objs = [Post(**data) for data in news] Post.objects.bulk_create(objs, ignore_conflicts=True) self.stdout.write( self.style.SUCCESS('Get {} objects\nFinished!!!'.format( len(news))))
def seed_from_file(): "This seeds the db from a tab seperated file without using csv reader" # open text file for reading with open("posts/Output.txt", "r") as seed_file: # iterate across each line for line in seed_file: # split on tab split = line.split(" ") # first part is title title = split[0].strip(' \n') # second part is text text = split[1].strip(' \n') # make post object with text and title post = Post(title=title, text=text) # save to db post.save()
def test_published_posts_exclude_unpublished_posts(self): # Count the number of posts in db postsCount = len(Post.objects.all()) self.assertEqual(len(Post.published_posts()), postsCount - 1) # unpublish a post, should result in 1 published and 2 unpublished p2 = Post.objects.get(title="test post 2") p2.unpublish() self.assertEqual(len(Post.published_posts()), postsCount - 2) # publish a post, should go back to 2 published and 1 unpublished p3 = Post.objects.get(title="test post 3") p3.publish() self.assertEqual(len(Post.published_posts()), postsCount - 1)
def index_from_year(request, year): """ Shows the posts from the year specified in the year parameter. """ posts = Post.published_posts_by_year(year) # Render paginated page return paginated_news_index(request, posts)
def post(self, request, *args, **kwargs): appointment = Post( headline=request.POST['headline'], text=request.POST['text'], ) appointment.save() send_mail( subject=f'{appointment.headline}', # имя клиента и дата записи будут в теме для удобства message=appointment.text, # сообщение с кратким описанием проблемы from_email= '*****@*****.**', # здесь указываете почту, с которой будете отправлять (об этом попозже) recipient_list=[ '*****@*****.**' ] # здесь список получателей. Например, секретарь, сам врач и т. д. ) return redirect('')
def test_can_create_a_news_post(self): user = get_user_model().objects.create(username='******') post = Post( author=user, title="Test", sub_title='test', slug='slug', preview_text="preview", content="content", featured=False, ) post.save() self.assertEqual(post.author, user) self.assertEqual(post.title, 'Test') self.assertEqual(post.sub_title, 'test') self.assertEqual(post.slug, 'slug') self.assertEqual(post.preview_text, 'preview') self.assertEqual(post.content, 'content') self.assertEqual(post.featured, False)
def post(self, request): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user all_groups = CustomGroup.objects.all() for group in all_groups: pre_moderation = getattr(group, 'pre_moderation') if post.author.groups.filter(name=group).exists() and \ pre_moderation is False: post.status = Post.ACCEPTED else: post.status = Post.IN_MODERATION post.save() return redirect('all_my_posts') else: post = Post() post.title = request.POST['title'] post.description = request.POST['description'] return render(request, 'news/create_post.html', {'form': form})
def post(self, request, *args, **kwargs): appointment = Post( text_title=request.POST['text_title'], text_news=request.POST['text_news'], ) appointment.save() send_mail( subject=f'{appointment.text_title}', # имя клиента и дата записи будут в теме для удобства message=appointment. text_news, # сообщение с кратким описанием проблемы from_email= '*****@*****.**', # здесь указываете почту, с которой будете отправлять (об этом попозже) recipient_list=[ '*****@*****.**' ] # здесь список получателей. Например, секретарь, сам врач и т. д. ) return redirect('')
def index(request): """ Index function, this is called by the / pattern from news.urls This means that this function is called on the url http://APP_URL/posts. TODO: Use a template to presents the posts """ posts = Post.published_posts().order_by('-pub_date') # Render paginated page return paginated_news_index(request, posts)
def latest(request): """ Retrieves the latest published post and prints it First we filter out the unpublished posts and then we get the last element. If there is no latest post (for instance if there are no published news) we print out 'No posts yet!' TODO: Use a template to display the latest post """ try: latest_post = Post.published_posts().latest('pub_date') return HttpResponse("%s <br> %s" % (latest_post.title, latest_post.content)) except Post.DoesNotExist: return HttpResponse("No posts yet!")
def import_article(self, filename, overwrite=False): with open(filename, 'r') as f: section = 0 metadata = {} sections = [[], []] for line in f: line = line.strip() if line == '---' and section < 2: section += 1 continue if section == 0: # Metadata section try: key, value = [x.strip() for x in line.split(':', 1)] except ValueError: raise CommandError( "Invalid metadata key:value pair: " + line) metadata[key.lower()] = value else: # Intro and readmore sections sections[section - 1].append(line) try: post = Post( slug=metadata['slug'], publish=metadata.get('publish', timezone.now()), is_visible=metadata.get('visible', 'true').lower() == 'true', title=metadata['title'], intro='\n'.join(sections[0]), readmore='\n'.join(sections[1]), ) except KeyError as ke: raise CommandError("Metadata field " + ke.args[0] + " is required.") try: post.save() except IntegrityError: if not overwrite: raise CommandError( "Article exists. Use --overwrite to update.") post.id = Post.objects.filter(slug=post.slug).values_list( 'id', flat=True)[0] post.save()
def item(request, post_id): """ Displays a single post with id post_id. Is called by the pattern /$post_id from news.url First we need to filter out the unpublished posts in case the requested post is not yet published and then we try to get that post. If it does not exist we just print 'No such post' as of now. TODO: Use a template to present the post """ try: post = Post.published_posts().get(id=post_id) content = "Posts article: %s<br> %s" return HttpResponse(content % (post_id,post.content)) except Post.DoesNotExist: return HttpResponse("No such post")
def sitemapindex(request): return render( request, 'sitemap/sitemapindex.xml', { 'sitemaps': ([ #GalleryCategory.get_sitemap_info(domain), Post.get_sitemap_info(domain), #PriceCategory.get_sitemap_info(domain), #Person.get_sitemap_info(domain), Page.get_sitemap_info(domain), Landingpage.get_sitemap_info(domain), Testimonial.get_sitemap_info(domain), ]), 'domain': 'http://anis-clinic.ru/' }, content_type='text/xml')
def test_was_published_recently_with_recent_news(self): ''' was_published_recently() should return True for recent news ''' old_news = Post(pub_date=timezone.now() - datetime.timedelta(hours=1)) self.assertEqual(old_news.was_published_recently(), True)
def test_url_max_length(self): news = Post(pk=1) max_length = news._meta.get_field('url').max_length self.assertEquals(max_length, 200)
def test_url_label(self): news = Post(pk=1) field_label = news._meta.get_field('url').verbose_name self.assertEquals(field_label, 'Url News')
def rss(request): """ Retrieves all posts and renders them in a rss xml fashion. """ posts = Post.published_posts().order_by('-pub_date') return render(request, 'news/feed.dtl', { 'items' : posts })
def test_name_max_length(self): catalog = Post(pk=1) max_length = catalog._meta.get_field('title').max_length self.assertEquals(max_length, 512)
def index_from_date(request, year, month): """ Shows the posts from a specific day. """ published_posts = Post.by_month(year, month) return render(request, 'news/index.dtl', { 'items' : published_posts })
def test_title_label(self): news = Post(pk=1) field_label = news._meta.get_field('title').verbose_name self.assertEquals(field_label, 'Title News')
SELECT ?title ?content WHERE { ?post a sioc:Post ; dcterms:title ?title ; sioc:content ?content . } """ query = Parse(query) posts = [] for row in graph.query(query): posts.append((row[0], row[1])) return posts posts = getPosts(graph) ################## from news.models import Post print Post.objects.all() for post in posts: p = Post(title=post[0], content=post[1]) p.save() print Post.objects.all()
def get_latest_8_posts(self): return Post.get_latest_posts(8)
fivelinesummary = ''.join(fivelinesummary) tenlinesummary = ''.join(tenlinesummary) sum_basic = ''.join(sum_basic) LSA = ''.join(LSA) textrank = ''.join(textrank) lexrank = ''.join(lexrank) featured_lexrank = ''.join(featured_lexrank) try: post = Post(category=category, pub_date=pub_date, location=location, title=title, content=content, photo=photo, link=link, fivelinesummary=fivelinesummary, tenlinesummary=tenlinesummary, sum_basic=sum_basic, LSA=LSA, textrank=textrank, lexrank=lexrank, featured_lexrank=featured_lexrank) post.save() except ValidationError as e: pub_date = datetime.datetime.now() post = Post(category=category, pub_date=pub_date, location=location, title=title, content=content, photo=photo,
def handle(self, *args, **options): faker = Faker() # Create categories if Category.objects.all().count() == 0: Category.objects.bulk_create([ Category(name='Politics', slug='politics', seo_title='Politics - read online on Blog-News', seo_description='Last news of Politics ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Finance', slug='finance', seo_title='Finance - read online on Blog-News', seo_description='Last news of Finance ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Economics', slug='economics', seo_title='Economics - read online on Blog-News', seo_description='Last news of Economics ' 'from all world. ' 'Read online on Blog-News.'), Category(name='Sports', slug='sports', seo_title='Sports - read online on Blog-News', seo_description='Last news of Sports ' 'from all world. ' 'Read online on Blog-News.') ]) all_categories = Category.objects.all() list_category_name = [category.name for category in all_categories] all_users_is_staff = User.objects.all() list_all_users_is_staff = [ user.username for user in all_users_is_staff if user.is_staff ] for new_post in range(options['len']): post = Post() post.title = faker.sentence(nb_words=5, variable_nb_words=False).replace( '.', '') post.slug = f'{post.title}'.lower().replace(' ', '-').replace( '.', '') # noqa post.article = faker.text() # random Category post.category = Category.objects.get( name=choice(list_category_name)) # random user is_staff post.author = User.objects.get( username=choice(list_all_users_is_staff)) post.seo_title = f'{post.title} | ' \ f'Read online | Blog news'.replace('.', '') post.seo_description = f'{post.title} | Blog news.' post.save() # list for random posts all_posts = Post.objects.all() list_post_name = [post.id for post in all_posts] # create comments comment = Comment() comment.text = faker.text() # random Post comment.for_post = Post.objects.get(id=choice(list_post_name)) # random user is_staff comment.author = User.objects.get( username=choice(list_all_users_is_staff)) comment.save()
def set_up(): post = Post(heading='Apply for membership', body="It's worth it" ) post.save()
def test_filter_on_date_range_works_as_expected(self): posts = Post.published_posts_by_year(2016) self.assertEqual(len(posts), 2)