Example #1
0
    def generate_data(apps, schema_editor):
        from Post.models import Post

        users_list = [
            User.objects.create_user('Shoval', '*****@*****.**',
                                     'password777'),
            User.objects.create_user('Daniel', '*****@*****.**',
                                     'password777'),
        ]

        Post_list = [
            Post(
                nameOfLocation='Eilat',
                photoURL=
                "https://israel.travel/wp-content/uploads/2019/02/eilatnewinside-min.jpg",
                Description=
                'This is my favorite place! chill vibes and beautiful sea.',
            ),
            Post(
                nameOfLocation='Dead Sea',
                photoURL=
                "https://velvetescape.com/wp-content/uploads/2011/11/IMG_2370-3-1280x920.jpg",
                Description='Beautiful place.',
            ),
        ]

        test_data = list(zip(users_list, Post_list))

        with transaction.atomic():

            for user, post in test_data:
                user.save()
                post.user = user
                post.save()
Example #2
0
 def create(self, validated_data):
     p = Post(**validated_data)
     p.save()
     filelist = self.context['request'].FILES.getlist('file')
     for file in filelist:
         f = Files.objects.create(file=file, file_user=p)
         f.save()
     return p
Example #3
0
    def generate_data(apps, schema_editor):
        from commenting_system.models import Comment

        users_list = [
            User.objects.create_user("Ma'ayan", "Ma'*****@*****.**",
                                     'password777'),
            User.objects.create_user('Nadav', '*****@*****.**',
                                     'password222'),
        ]
        profile_picture_list = [
            'profile_pics/profile_picture.jpg',
            'profile_pics/profile_avatar.png',
        ]

        body_comments_list = [
            ("Gorgeous views and calm waters. We took a short cruise here, complete with praise music"
             "and refreshments. This made for a refreshing stop made perfect by the warm sun and cool breeze."
             "Check beforehand to insure against inclement weather."),
            ("Very nice chilling pool, but can be pretty much crowded on sunny days, "
             "as it is just a few hundred meters from parking - easy access."),
        ]

        Post_list = [
            Post(
                user=users_list[1],
                nameOfLocation='Sea of Galilee',
                photoURL=
                "https://www.shappo.co.il/Resize_Image.aspx?maxsize=400&img=/pictures/cards/big/36630.jpg",
                Description=
                'It is the lowest freshwater lake on Earth and the second-lowest lake in the world',
            ),
            Post(
                user=users_list[0],
                nameOfLocation="`En Yorqe`am",
                photoURL=
                "https://cdn1.sipurderech.co.il/1200x800_fit_90/1403218722_121.jpeg",
                Description='Beautiful spot with cool water',
            ),
        ]

        test_data = list(
            zip(users_list, body_comments_list, Post_list,
                profile_picture_list))

        with transaction.atomic():

            for user, body, post, image in test_data:
                user.profile.image = image
                user.profile.save()
                post.save()
                Comment(user=user, body=body, post=post,
                        label="Crowded").save()
Example #4
0
def test_post_comments():
    posts = Post.all_posts()

    for post in posts:
        assert isinstance(post.comments.all(), QuerySet)
        assert all(
            isinstance(comment, Comment) for comment in post.comments.all())
Example #5
0
 def _create_post(**kwards):
     new_post = Post(
         user=kwards["user"],
         nameOfLocation=kwards["nameOfLocation"],
         photoURL=kwards["photoURL"],
         Description=kwards["Description"],
     )
     return new_post
Example #6
0
def post_list(user_list, place_choices):
    return [
        Post(
            user=user_list[i],
            nameOfLocation=place_choices[i],
            photoURL=f'www.test_{i + 1}.com',
            Description=
            f'This is my #{i + 1} favorite place! chill vibes and beautiful view.',
        ) for i in range(0, 6)
    ]
Example #7
0
def test_all_posts():

    posts = Post.all_posts()

    assert isinstance(posts, QuerySet)
    assert all(isinstance(post, Post) for post in posts)
    assert all(post is not None for post in posts)
    assert all(len(post.Description) > 0 for post in posts)
    assert all(len(post.nameOfLocation) > 0 for post in posts)
    assert all(isinstance(post.user, User) for post in posts)
    assert all(len(post.photoURL) > 0 for post in posts)
Example #8
0
def post():
    new_user = User.objects.create_user(
        username='******', email='*****@*****.**', password='******'
    )
    new_user.save()

    return Post(
        user=new_user,
        nameOfLocation='The Dead Sea',
        photoURL='www.testPost.com',
        Description='beautiful place',
    )
Example #9
0
def new_post(request):
    if request.method == 'POST':
        new_post = Post()
        new_post.body = request.POST['body']
        new_post.user = request.user
        new_post.save()
        return redirect('/')
    return render(request, 'new_post.html')
Example #10
0
    def test_post_creation(self):
        Post.objects.create(title="test_title_1", body="test_body_1")
        Post(title="test title", body="test body").save()

        posts = Post.objects.all()

        self.assertEqual(posts.count(), 2)

        post = Post.objects.get(title="test title")
        self.assertTrue(post)

        self.assertEqual(post.title, "test title")
        self.assertEqual(post.body, "test body")
        self.assertEqual(post.status, "draft")
Example #11
0
    def generate_data(apps, schema_editor):
        from commenting_system.models import Comment

        users_list = [
            User.objects.create_user('Test-user-comments1', '*****@*****.**',
                                     'password777'),
            User.objects.create_user('Test-user-comments2', '*****@*****.**',
                                     'password222'),
        ]

        body_comments_list = [('First comment test'), ('Second comment test')]

        Post_list = [
            Post(
                nameOfLocation='Sea of Galilee',
                photoURL=
                "https://www.shappo.co.il/Resize_Image.aspx?maxsize=400&img=/pictures/cards/big/36630.jpg",
                Description='Perfect!',
            ),
            Post(
                nameOfLocation="`En Yorqe`am",
                photoURL=
                "https://cdn1.sipurderech.co.il/1200x800_fit_90/1403218722_121.jpeg",
                Description='Really nice place',
            ),
        ]

        test_data = list(zip(users_list, body_comments_list, Post_list))

        with transaction.atomic():

            for user, body, post in test_data:
                user.save()
                post.user = user
                post.save()
                Comment(user=user, body=body, post=post,
                        label="Recommended").save()
Example #12
0
def make_databse(request):
    with open('SiteAdmin/database.json', 'r') as db:
        database = json.load(db)
    for d in database:
        Post(
            id=database[d]['id'],
            title=database[d]['title'],
            author=database[d]['author'],
            author_profile_link=database[d]['author_profile_link'],
            description=database[d]['description'],
            manifest_url=database[d]['manifest_url'],
            tags=database[d]['tags'],
            date_uploaded=datetime.strptime(
                database[d]['date_uploaded'],
                '%d %b, %Y %I:%M:%S %p').astimezone(IST),
            date_last_modified=datetime.strptime(
                database[d]['date_last_modified'],
                '%d %b, %Y %I:%M:%S %p').astimezone(IST),
            dir_name=database[d]['dir_name'],
        ).save()
    return JsonResponse({'Status': 'Done'})
Example #13
0
    def generate_data(apps, schema_editor):
        from Post.models import Post

        users_list = [
            User.objects.create_user('Shoval', '*****@*****.**',
                                     'password777'),
            User.objects.create_user('Leead', '*****@*****.**',
                                     'password777'),
        ]
        profile_picture_list = [
            'profile_pics/profile_female.png',
            'profile_pics/avatar.jpg',
        ]
        users_profiles = list(zip(users_list, profile_picture_list))
        for user, image in users_profiles:
            user.profile.image = image
            user.profile.save()

        users_list.append(users_list[0])
        users_list.append(users_list[1])

        post_Description_list = [
            ('This is my favorite place! chill vibes and beautiful sea.'),
            ("Great sunsets and sunrises with views of the West Bank"
             "and the mountain range of the East Bank and Oaisis on the mountains slopes"
             "... breathtaking views and a very high level of Oxygen too. Beautiful place."
             ),
            ("En Gedi is the biggest oasis in Israel. It has springs and waterfalls, "
             "and flowing brooks at the foot of the cliffs, home to ibexes and rock hyraxes."
             ),
            ("Ramon Crater is the largest natural crater in the world, "
             "it is 40 km (25 miles) long, 10 km (6.2 miles) wide and 500 meters (1640 ft) deep, "
             "and is shaped like an elongated heart. In the picture is the Bereshit"
             "Hotel, set on a cliff at the edge of the Ramon Crater in the Negev Desert."
             ),
        ]
        photoURL_List = [
            ("https://israel.travel/wp-content/uploads/2019/02/eilatnewinside-min.jpg"
             ),
            ("https://velvetescape.com/wp-content/uploads/2011/11/IMG_2370-3-1280x920.jpg"
             ),
            ("https://images.unsplash.com/photo-1464980704090-17359156b2f6?ixid="
             "MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"
             ),
            ("https://israelforever.org/interact/blog/8.-Beresheet-Hotel-Mitzpe-Ramon-Israel-7-e1431897591414.jpg"
             ),
        ]
        nameOfLocation_List = ['Eilat', 'Dead Sea', 'En gedi', 'Ramon Crater']

        post_data = list(
            zip(nameOfLocation_List, photoURL_List, post_Description_list))
        Post_list = []
        for nameOfLocation, URL, description in post_data:
            Post_list.append(
                Post(nameOfLocation=nameOfLocation,
                     photoURL=URL,
                     Description=description))

        test_data = list(zip(users_list, Post_list))

        with transaction.atomic():
            for user, post in test_data:
                post.user = user
                post.save()
Example #14
0
def renew_post(request, pk):
    username = request.user.username
    channel_id = pk
    channel_url = request.GET.get('channel_url')

    success = True

    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--blink-settings=imagesEnabled=false')
    options.add_argument('--window-size=1366x768')
    options.add_argument('--disable-gpu')
    options.add_argument('--lang=ko_KR')
    options.add_argument('--no-sandbox')
    options.add_argument(
        "--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36"
    )
    chrome_driver = webdriver.Chrome(chrome_options=options)
    chrome_driver_wait = WebDriverWait(chrome_driver, 30)

    try:
        chrome_driver.get("https://accounts.kakao.com")

        s3_client = boto3.client(
            's3',
            region_name='ap-northeast-2',
            aws_access_key_id=config('AWS_ACCESS_KEY_ID'),
            aws_secret_access_key=config('AWS_SECRET_ACCESS_KEY'))
        s3_response = s3_client.get_object(
            Bucket=config('AWS_STORAGE_BUCKET_NAME'),
            Key='uploads/cookies/' + username.replace('@', '') + '.pkl')
        get_cookies = s3_response['Body'].read()

        for cookie in c_pickle.loads(get_cookies):
            chrome_driver.add_cookie(cookie)

        chrome_driver.get(channel_url)

        sleep(2)

        for i in range(1):
            chrome_driver.execute_script(
                "window.scrollTo(0, document.body.scrollHeight);")
            sleep(5)

        post_post_list = chrome_driver_wait.until(
            EC.presence_of_all_elements_located(
                (By.CSS_SELECTOR, ".story_channel")))

        for item in post_post_list:
            post_title = item.find_element_by_css_selector(".tit_story").text
            get_register_date = item.find_element_by_css_selector(
                ".link_date").text
            get_register_date = get_register_date.split(" ")
            get_month = get_register_date[0].replace("월", "")
            get_day = get_register_date[1].replace("일", "")
            get_hour = get_register_date[3].split(":")[0]
            get_hour = get_hour if (get_register_date[2]
                                    == "오전") else str(int(get_hour) + 12)
            get_minute = get_register_date[3].split(":")[1]
            now = datetime.now()
            naive = datetime.strptime(
                str(now.year) + "-" + get_month + "-" + get_day + " " +
                get_hour + ":" + get_minute + ":00", "%Y-%m-%d %H:%M:%S")
            local = pytz.timezone(settings.TIME_ZONE)
            local_dt = local.localize(naive, is_dst=None)
            # datetimefield를 직접 넣으면 파싱한 시간 그대로 들어가져버려 tz이 꼬인다. 그래서 직접 utc로 바꿨다.
            post_register_date = local_dt.astimezone(pytz.utc)
            post_url = item.find_element_by_css_selector(
                ".link_title").get_attribute("href")

            try:
                # update
                check_post = Post.objects.get(channel_id=channel_id,
                                              post_title=post_title)
                check_post.post_register_date = post_register_date
                check_post.post_url = post_url
                check_post.save()
            except ObjectDoesNotExist:
                # create
                post = Post(post_title=post_title,
                            post_register_date=post_register_date,
                            post_url=post_url,
                            channel_id=channel_id)
                post.save()

    except Exception as e:
        logger.info(e)
        success = False
    finally:
        chrome_driver.close()
    return HttpResponse(json.dumps(success), content_type="application/json")
Example #15
0
def create_post(request):
    if request.method == 'POST' and request.user.is_authenticated:
        form = PostForm(request.POST)
        if form.is_valid():
            post = Post()
            post.post_speciality_number = form.cleaned_data[
                'post_speciality_number']
            post.post_short_description = form.cleaned_data[
                'post_short_description']
            post.post_text = form.cleaned_data['post_text']
            post.post_title = form.cleaned_data['post_title']
            post.post_author = request.user
            post.save()
            tags = form.cleaned_data['tags']
            for tag in tags:
                post.tag_set.add(tag)
                tag.post_set.add(post)
            if request.POST['tag'] != '':
                new_tag, _ = Tag.objects.get_or_create(
                    tag_name=request.POST['tag'])
                new_tag.save()
                post.tag_set.add(new_tag)
                new_tag.post_set.add(post)
            post.save()
            return HttpResponseRedirect('/MyProfile/')
    else:
        form = PostForm()
    d = {
        'form': form,
    }
    try:
        d['theme'] = request.session['theme']
    except KeyError:
        pass
    return render(request, 'home/EditPost.html', d)
Example #16
0
def checkArticle(request):
    form = ArticleForm()
    if request.method == "POST":
        print('inside post')
        form = ArticleForm(request.POST)
        if form.is_valid():
            print('form is valid')
            # try:
            title = form.cleaned_data["title"]
            link = form.cleaned_data["link"]
            body = form.cleaned_data["body"]
            posted = form.cleaned_data["posted"]

            data = {
                'url': link,
                'title': title,
                'content': body,
            }
            #idhar se karna replace
            if request.user.is_authenticated:
                article = Article(title=title,
                                  link=link,
                                  body=body,
                                  user=request.user)
            else:
                article = Article(title=title, link=link, body=body)
            #yahan tak karna h change
            #article.save()
            response = requests.post(url='http://localhost:8080/fakebox/check',
                                     data=data)
            temp = json.loads(response.text)
            result = {}

            #prediction driver code
            u = np.array([[0.68244157, 0.68253419]])
            var = np.array([[0.01124549, 0.02151113]])
            # print(f'mean: {u} and sigma: {var}')

            #res = result(np.array([0.889, 0.908]), u, sigma2)
            res = resultFunc(
                np.array([temp['content']['score'], temp['title']['score']]),
                u, var)
            print(f'the result is {res}')

            if (res > 0.33):
                article.fake = False
                print(f'True')
                result['status'] = 'Real'
                result['article'] = article
                result['score'] = temp['title']['score'] + temp['content'][
                    'score']
                result['resp'] = temp
            else:
                article.fake = True
                print(f'False')
                result['status'] = 'Fake'
                result['article'] = article
                result['score'] = temp['title']['score'] + temp['content'][
                    'score']
                result['resp'] = temp

            print(f"The news is {result['status']}")
            article.save()

            if posted is True:
                print('posted if was true')
                p = Post(article=article)
                p.save()
            return render(request, "evaluated.html", {'result': result})

            # except:
            #     print('in exception')
        else:
            print('form is invalid')

    return render(request, "checkarticle.html", {'form': form})