示例#1
0
def showweibo(request, id, weiboid):
    iname = request.session["username"]
    iuser = User.objects.get(username=iname)
    iid = iuser.pk
    weibo = Weibo.objects.get(pk=weiboid)
    list_review = weibo.review_set.all()

    if request.method == "POST":
        form = reviewWeibo(request.POST)
        if form.is_valid():
            review = form.cleaned_data['review']
            user = User.objects.get(username=request.session['username'])
            r = Review(review=review, weibo=weibo, user=user)
            r.save()
            return render(request,
                          'weibo/showweibo.html',
                          context={
                              "weibo": weibo,
                              'list_review': list_review,
                              'form': form,
                              'iid': iid
                          })
    else:
        form = reviewWeibo()
    return render(request,
                  'weibo/showweibo.html',
                  context={
                      "weibo": weibo,
                      'list_review': list_review,
                      'form': form,
                      'iid': iid
                  })
示例#2
0
 def setUp(self):
   self.client = Client()
   self.user = User.objects.create_user('test_foo', '*****@*****.**','bqz_qux')
   self.user.save()
   self.user_two = User.objects.create_user('test_bar', '*****@*****.**', 'bqz_qux')
   self.user_two.save()
   self.toilet = Toilet(date = datetime.datetime.now() ,
                         creator = self.user, name = "test_toilet")
   self.toilet.save()
   self.toilet_second = Toilet(date = datetime.datetime.now(),
                        creator = self.user, name = "test_toilet2")
   self.toilet_second.save()
   self.review_one_one = Review(user=self.user, date = datetime.datetime.now(),
                            toilet = self.toilet, content = "foo bar", rank = 5,
                            up_down_rank = 1)
   self.review_one_one.save() 
   self.review_one_two = Review(user=self.user, date = datetime.datetime.now(),
                            toilet = self.toilet_second, content = "foo bar", rank = 5,
                            up_down_rank = 1)
   self.review_one_two.save()
   self.review_two_one =  Review(user=self.user_two, date = datetime.datetime.now(),
                            toilet = self.toilet, content = "foo bar", rank = 5,
                            up_down_rank = 1)
   self.review_two_one.save()
   self.review_two_two =  Review(user=self.user_two, date = datetime.datetime.now(),
                            toilet = self.toilet_second, content = "foo bar", rank = 5,
                            up_down_rank = 1)
   self.review_two_two.save()
示例#3
0
def addReview(request, book_id):
    book = get_object_or_404(Book, pk=book_id)
    userReview = request.user.adult.reviews.filter(book=book)
    if request.method == "GET":
        if (len(userReview) > 0):
            return render(request, "review/addReview.html", {
                "form": ReviewForm(instance=userReview[0]),
                "book_id": book_id
            })
        else:
            return render(request, "review/addReview.html", {
                "form": ReviewForm(),
                "book_id": book_id
            })
    elif request.method == "POST":
        if (len(userReview) > 0):
            Review.delete(userReview[0])
        form = ReviewForm(request.POST)
        if form.is_valid():
            newReview = form.save(commit=False)
            newReview.save()
            newReview.book.add(book)
            request.user.adult.reviews.add(newReview)
            return redirect("book_card", book_id)
        else:
            return render(request, "review/addReview.html", {
                "form": ReviewForm(),
                "book_id": book_id,
                "error": "bad data"
            })
示例#4
0
    def save(self):
        try:
            title = self.validated_data['title']
            body = self.validated_data['body']
            rating = self.validated_data['rating']
            comic = self.validated_data['comic']

            # Create new review unless one already exists for this comic by this user
            try:
                previously_reviewed = Review.objects.get(
                    author__id=self.context['request'].user.id,
                    comic__id=comic.id)
                if previously_reviewed:
                    raise serializers.ValidationError({
                        "response":
                        "You've already rated/reviewed this.",
                        "review":
                        ReviewSerializer(previously_reviewed).data
                    })
            except Review.DoesNotExist:
                review = Review(title=title,
                                body=body,
                                rating=rating,
                                author=self.context['request'].user,
                                comic=comic)
                review.save()
                return review

        except KeyError as e:
            raise serializers.ValidationError(
                {"response": "Please include all required fields"})
示例#5
0
文件: views.py 项目: S0Imyr/Projet9
def create_review(request, id_ticket=None):
    review = None
    context = {}
    if id_ticket is not None:
        ticket = get_object_or_404(Ticket, pk=id_ticket)
        context = {'post': {'content': ticket}}
        review = Review(ticket=ticket,
                        rating=None,
                        headline=None,
                        body=None,
                        user=request.user,
                        time_created=None)
    else:
        review = Review(ticket=None,
                        rating=None,
                        headline=None,
                        body=None,
                        user=request.user,
                        time_created=None)
    if request.method == 'GET':
        form = ReviewForm(instance=review)
        context['form'] = form
        return render(request, 'review/addreview.html', context)
    elif request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            form.save()
            ticket.save()
            return redirect('flux')
        else:
            return render(request, 'review/addreview.html', context)
示例#6
0
def create_review(questions):
    review = Review()
    review.save()
    for q in questions:
        q.review = review
        q.save()
    return review
示例#7
0
文件: views.py 项目: telbohtimy/Vygit
def authorPage(request, id):
    try:
        authorPage=Profile.objects.get(pk=id)
        if authorPage.image:
            scale=scaleImage(400, authorPage.image.height)
            width=scale*authorPage.image.width
            height=scale*authorPage.image.height
        else:
            width=0
            height=0
        ReviewList = Review.objects.filter(Q(reviewed=authorPage)).order_by('-date')
        reviewed=authorPage
        flag=''
        if request.user.is_authenticated():
            reviewer=Profile.objects.get(user=request.user)
            if Review.objects.filter(reviewer = reviewer).filter(reviewed=reviewed).exists():
                flag='flag'
        if request.method=='POST':
            if reviewer==reviewed:
                return HttpResponseRedirect('/profiles/'+str(id)+'/')
            reviewForm=ReviewForm(data=request.POST)
            if reviewForm.is_valid():
                body=reviewForm.cleaned_data['body']
                rating=reviewForm.cleaned_data['ratings']
                date=timezone.now()
                newReview=Review(reviewer=reviewer,reviewed=reviewed,body=body,ratings=rating,date=date)
                newReview.save()
        else:
            reviewForm=ReviewForm()
    except Profile.DoesNotExist:
        raise Http404("This profile does not exist")
    return render(request,"author.html",{"authorPage":authorPage,'reviewForm': reviewForm, 'ReviewList':ReviewList,'width':width,'height':height,'flag':flag})
def reviews(request):
    if ('author' in request.GET and 'comment' in request.GET
            and request.GET['author'] != '' and request.GET['comment'] != ''):
        review = Review(author=request.GET['author'], text=request.GET['comment'])
        review.save()

    all_reviews = reversed(Review.objects.all())
    return render(request, 'reviews.html', {'reviews': all_reviews})
示例#9
0
 def setUp(self):
     self.instructor = Instructor(name="Teacher")
     self.instructor.save()
     self.review = Review(
         section=get_or_create_course_and_section("CIS-120-001", TEST_SEMESTER)[1],
         instructor=self.instructor,
     )
     self.review.save()
示例#10
0
class ReviewView(APIView):  # noqa
    queryset = Review.objects.all()

    def _get_data(self, request, goal_slug, suggestion_slug):
        self.member = Member.lookup(request.user, goal_slug)
        if self.member:
            self.suggestion = get_object_or_404(
                Suggestion,
                slug=suggestion_slug,
                goal__slug=goal_slug
            )

            self.review = Review.objects.filter(
                revision__suggestion=self.suggestion,
                owner=self.member.global_user
            ).first()

    def _create_review(self):
        self.review = Review()
        self.review.owner = self.member.global_user
        self.review.revision = self.suggestion.get_current_revision()
        self.review.save()

    def get(self, request, goal_slug, suggestion_slug):  # noqa
        self._get_data(request, goal_slug, suggestion_slug)
        if not self.review:
            self._create_review()
        serializer = ReviewSerializer(self.review)
        return Response(serializer.data)

    def post(self, request, goal_slug, suggestion_slug):  # noqa
        self._get_data(request, goal_slug, suggestion_slug)
        if not self.review:
            self._create_review()

        data = ReviewSerializer(self.review).data
        data.update(request.data)

        serializer = ReviewSerializer(instance=self.review, data=data)
        if serializer.is_valid():
            self.review = serializer.save(is_draft=False)
            update_rating_and_save(self.review.revision.suggestion)
            self.review.comments.filter(is_draft=False).delete()
            notification = Notification.create_for_review(self.review)
            if notification.owner != self.review.owner:
                notification.save()
            return Response(
                {'success': 1},
                status=status.HTTP_200_OK
            )
        else:
            return Response(
                {
                    'success': 0,
                    'errors': serializer.errors
                },
                status=status.HTTP_200_OK
            )
示例#11
0
文件: views.py 项目: pythexcel/fab
 def post(self, request, pk=None):
     rating = request.data.get("rating")
     user_one = self.request.user
     user_two = User.objects.get(id=pk)
     reviewed = Review.objects.filter(user_id=user_one.id,
                                      rated_user_id=user_two.id).delete()
     review = Review(user_id=user_one.id,
                     rated_user_id=user_two.id,
                     rating=rating)
     review.save()
     return Response({"Message": "Rating submitted"})
示例#12
0
def review_create(request):

    # Получение данных из формы в переменную
    form = ReviewForm(request.POST)
    dbl.log("Форма" + str(form))

    # global list_crumb_for_software
    list_crumb_for_software = [['Главная', 'main:index'],
                               ['Отзывы', 'review:list_review']]
    #  Получение данных из формы и сохранение в бд
    if request.method == "POST":
        try:

            # Проверка принадлежности запрашиваемого заказа к текущему пользователю
            # Получения пользователя
            user = CustomUser.get_user(request)

            # Здесь автоматически проверяются все поля формы методами clean_...
            if form.is_valid():

                new_review = Review()
                new_review.kind = 'com'
                if user:
                    new_review.client = user

                new_review.content = form.cleaned_data['content']
                new_review.star = form.cleaned_data['star']
                new_review.name = form.cleaned_data['name']
                new_review.email_phone = form.cleaned_data['email_phone']
                new_review.save()

                addition_file = request.FILES.getlist('file')

                # Сохранение приложений файлов к отзыву (происходит тогда, когда все поля валидны)
                for file in addition_file:
                    dbl.log("777")
                    new_addition = Review_Addition()

                    new_addition.review = new_review
                    new_addition.photo = file
                    new_addition.save()

                return redirect('review:review_success')

        except Exception as error:
            pass
            dbl.log("Ошибка работы с отзывом" + str(error))

    rating = [5, 4, 3, 2, 1]
    return render(request, 'review/review_create.html', {
        'form': form,
        'rating': rating,
        'list_crumb': list_crumb_for_software
    })
示例#13
0
 def test_validate_review_post_request_review_exists(self):
     # Review exists already
     test_data = {"courseCode": "TDT4290",
                  "score": 1,
                  "workload": 1,
                  "difficulty": 1,
                  "reviewText": "Lorem ipsum"}
     test_review = Review(user_email="*****@*****.**", course_code="TDT4290", score=4, workload=5, difficulty=3,
                          review_text="Test review", full_name="Test Testesen", study_programme="MTDT")
     test_review.save()
     with self.assertRaises(ValueError):
         validate_review_post_request(test_data, ["TDT4290", "TMA4125"], "*****@*****.**")
示例#14
0
def review(request, pk):
    if "form_submit" in request.POST:
        form = ReviewForm(request.POST)
        if form.is_valid():
            r = Review(
                user=request.user,
                location=Location.objects.only("id").get(id=pk),
                content=form.cleaned_data["content"],
                rating=form.cleaned_data["rating"],
            )
            r.save()
    return HttpResponseRedirect(reverse("location", args=(pk, )))
示例#15
0
class ReviewView(APIView):  # noqa
    queryset = Review.objects.all()

    def _get_data(self, request, goal_slug, suggestion_slug):
        self.member = Member.lookup(request.user, goal_slug)
        if self.member:
            self.suggestion = get_object_or_404(Suggestion,
                                                slug=suggestion_slug,
                                                goal__slug=goal_slug)

            self.review = Review.objects.filter(
                revision__suggestion=self.suggestion,
                owner=self.member.global_user).first()

    def _create_review(self):
        self.review = Review()
        self.review.owner = self.member.global_user
        self.review.revision = self.suggestion.get_current_revision()
        self.review.save()

    def get(self, request, goal_slug, suggestion_slug):  # noqa
        self._get_data(request, goal_slug, suggestion_slug)
        if not self.review:
            self._create_review()
        serializer = ReviewSerializer(self.review)
        return Response(serializer.data)

    def post(self, request, goal_slug, suggestion_slug):  # noqa
        self._get_data(request, goal_slug, suggestion_slug)
        if not self.review:
            self._create_review()

        data = ReviewSerializer(self.review).data
        data.update(request.data)

        serializer = ReviewSerializer(instance=self.review, data=data)
        if serializer.is_valid():
            self.review = serializer.save(is_draft=False)
            update_rating_and_save(self.review.revision.suggestion)
            self.review.comments.filter(is_draft=False).delete()
            notification = Notification.create_for_review(self.review)
            if notification.owner != self.review.owner:
                notification.save()
            return Response({'success': 1}, status=status.HTTP_200_OK)
        else:
            return Response({
                'success': 0,
                'errors': serializer.errors
            },
                            status=status.HTTP_200_OK)
示例#16
0
    def create(self, request, *args, **kwargs):
        restaurant = Restaurant.objects.get(id=kwargs['pk'])
        rating = self.request.data['rating']

        if rating in [1, 2, 3, 4, 5]:
            review = Review(author=self.request.user,
                            rating=rating,
                            restaurant=restaurant,
                            content=self.request.data['content'])
            review.save()
            return Response(self.get_serializer(review).data)
        else:
            return JsonResponse(
                {'detail': 'Please provide valid rating(1 to 5)!'})
示例#17
0
文件: views.py 项目: kfarr/vidhackday
def save_archive_ajax(request):
    if request.is_ajax():
	# Goal is to save archive_id witha new object with teh new dude and movie id

	movie_id = request.POST['movie_id'] 
	archive_id = request.POST['archive_id']
	
	review = Review(user = request.user, archive_id = archive_id, movie = Movie.objects.get(pk=movie_id))
	review.save()
	messages.success(request, "This review has been saved. %s %s" % (movie_id, archive_id))
	return HttpResponse('success')
    else:
	msg = "Error"
        return HttpResponse(msg)
示例#18
0
def review(request):
    user = request.user
    if Profile.objects.filter(user=user, is_council=True).exists():
        submission = request.POST.get('task')
        feedback = request.POST.get('feedback')
        rating = request.POST.get('rating')
        review = Review(user=Profile.objects.get(user=user),
                        submission_id=submission,
                        feedback=feedback,
                        rating=rating)
        review.save()
        return redirect('/portal/home?success=True')

    return redirect('/portal/home')
示例#19
0
	def post(self, request, *args, **kwargs):
		if not request.user.is_authenticated():
			return HttpResponseRedirect(reverse("accounts:auth_login"))
			
		token = ReviewToken.objects.filter(pk = request.POST['pk'])[0]
		if not ( token.user == request.user and token.active == 1 ):
			raise PermissionDenied
		
		r = Review(desc = request.POST['desc'], rating = request.POST['rating'], title=request.POST['title'])
		r.source = request.user
		r.pgr = token.pgr
		r.save()
		token.active = 0
		token.save()
		return HttpResponse("Success")
示例#20
0
    def __create_reviews(self):
        self.review_yoga_twist = Review()
        self.review_yoga_twist.owner = self.user_marie_houana
        self.review_yoga_twist.revision = self.rev_yoga_twist
        self.review_yoga_twist.rating = 2.5
        self.review_yoga_twist.description = "Not bad!"
        self.review_yoga_twist.is_draft = False
        self.review_yoga_twist.save()

        self.review_yoga_twist_2 = Review()
        self.review_yoga_twist_2.owner = self.user_mnieber
        self.review_yoga_twist_2.revision = self.rev_yoga_twist_2
        self.review_yoga_twist_2.rating = 4
        self.review_yoga_twist_2.description = "Good, good, good"
        self.review_yoga_twist_2.is_draft = False
        self.review_yoga_twist_2.save()
示例#21
0
    def __create_reviews(self):
        self.review_yoga_twist = Review()
        self.review_yoga_twist.owner = self.user_marie_houana
        self.review_yoga_twist.revision = self.rev_yoga_twist
        self.review_yoga_twist.rating = 2.5
        self.review_yoga_twist.description = "Not bad!"
        self.review_yoga_twist.is_draft = False
        self.review_yoga_twist.save()

        self.review_yoga_twist_2 = Review()
        self.review_yoga_twist_2.owner = self.user_mnieber
        self.review_yoga_twist_2.revision = self.rev_yoga_twist_2
        self.review_yoga_twist_2.rating = 4
        self.review_yoga_twist_2.description = "Good, good, good"
        self.review_yoga_twist_2.is_draft = False
        self.review_yoga_twist_2.save()
示例#22
0
class GetReviewTest(TestCase):
    def setUp(self):
      self.client = Client()
      self.user = User.objects.create_user('test_foo', '*****@*****.**','bqz_qux')
      self.user.save()
      self.user_two = User.objects.create_user('test_bar', '*****@*****.**', 'bqz_qux')
      self.user_two.save()
      self.toilet = Toilet(date = datetime.datetime.now() ,
                            creator = self.user, name = "test_toilet")
      self.toilet.save()
      self.toilet_second = Toilet(date = datetime.datetime.now(),
                           creator = self.user, name = "test_toilet2")
      self.toilet_second.save()
      self.review_one_one = Review(user=self.user, date = datetime.datetime.now(),
                               toilet = self.toilet, content = "foo bar", rank = 5,
                               up_down_rank = 1)
      self.review_one_one.save() 
      self.review_one_two = Review(user=self.user, date = datetime.datetime.now(),
                               toilet = self.toilet_second, content = "foo bar", rank = 5,
                               up_down_rank = 1)
      self.review_one_two.save()
      self.review_two_one =  Review(user=self.user_two, date = datetime.datetime.now(),
                               toilet = self.toilet, content = "foo bar", rank = 5,
                               up_down_rank = 1)
      self.review_two_one.save()
      self.review_two_two =  Review(user=self.user_two, date = datetime.datetime.now(),
                               toilet = self.toilet_second, content = "foo bar", rank = 5,
                               up_down_rank = 1)
      self.review_two_two.save()
      
    #get all reviews by user EQ3
    def test_get_review_user(self):
      response = self.client.post('/api/Review/get/', { 'start' : 0, 'end' : 10, 'filters' : json.dumps({'user' : self.user.id}) })
      responselist = json.loads(response.content)
      #there are two reviews per user
      self.assertEqual(len(responselist), 2)
      for review in responselist:
          self.assertEqual(review['fields']['user'], self.user.id)
          
    #get all reviews by toilet id EQ1
    def test_get_review_by_toilet(self):
      response = self.client.post('/api/Review/get/', { 'start' : 0, 'end' : 10, 'filters' : json.dumps({'toilet' : self.toilet.id})})
      responselist = json.loads(response.content)
      #there are two reviews per toilet
      self.assertEqual(len(responselist), 2)
      for review in responselist:
          self.assertEqual(review['fields']['toilet'], self.toilet.id)
          
    #get all reviews by a toilet that does not exist EQ2
    def test_get_review_by_non_exist_toilet(self):
      response = self.client.post('/api/Review/get/', { 'start' : 0, 'end' : 10, 'filters' : json.dumps({'toilet' : 666})})
      self.assertEqual(json.loads(response.content), [])
      
    #get all reviews by user tht doesn't exists EQ4
    def test_get_review_by_not_existant_user(self):
      response = self.client.post('/api/Review/get/', { 'start' : 0, 'end' : 10, 'filters' : json.dumps({'user' : 666}) }) 
      self.assertEqual(json.loads(response.content), [])
示例#23
0
 def setUp(self):
     with open('secrets.json', 'r') as f:
         secret_key = json.load(f)
     LoginPlatform(name="airbnb").save()
     User(id=1,
          email='*****@*****.**',
          password=bcrypt.hashpw("qweasd123!".encode('utf-8'),
                                 bcrypt.gensalt()).decode('utf-8'),
          first_name='jiwon',
          last_name='ko',
          birth_date=datetime.datetime.strptime("1997-2-20", "%Y-%m-%d"),
          is_host=False,
          platform=LoginPlatform.objects.get(name="airbnb")).save()
     Amenity(name='amenity').save()
     Room(id=1,
          title='Room title',
          address='Room 주소',
          max_personnal='10',
          bed_room='침실',
          bed='퀸 사이즈',
          bath_room='욕실 한 개',
          price=100000,
          latitude=30,
          longitude=50,
          description='room 설명').save()
     BookingStatus(status='예약완료').save()
     PaymentMethod(name='체크카드').save()
     Booking(id=1,
             check_in=datetime.datetime.strptime("2020-08-10", "%Y-%m-%d"),
             check_out=datetime.datetime.strptime("2020-08-12", "%Y-%m-%d"),
             price=100000,
             cleaning_expense=10000,
             service_tax=3000,
             accomodation_tax=3000,
             adult=3,
             children=1,
             infants=0,
             user=User.objects.get(email='*****@*****.**'),
             room=Room.objects.get(title='Room title'),
             status=BookingStatus.objects.get(status='예약완료'),
             payment_method=PaymentMethod.objects.get(name='체크카드'),
             created_at=datetime.datetime.strptime("2020-08-09",
                                                   "%Y-%m-%d")).save()
     Review(booking=Booking.objects.get(id=1),
            content='리뷰 내용',
            cleanliness_score=4.0,
            communication_score=5.0,
            check_in_score=3.0,
            accuracy_score=2.5,
            location_score=3.5,
            satisfaction_score=4.0,
            created_at=datetime.datetime.strptime("2020-09-01",
                                                  "%Y-%m-%d")).save()
     self.token = jwt.encode(
         {
             'email': User.objects.get(email='*****@*****.**').email
         },
         secret_key['SECRET_KEY'],
         algorithm=ALGORITHM).decode('utf-8')
示例#24
0
文件: views.py 项目: spondbob/replace
def review(request):
    response = ""
    
    text = {
            1 : ["kurang memuaskan karena harganya cukup mahal","pelayananannya kurang oke","masih banyak yang perlu di tingkatkan","pelayanannnya lemot","AC nya terlalu dingin, pernah ketetesan karena bocor","pelayannya kurang ramah kepada pengunjung","kurang asik tempatnya","bukan cuman bergaya jadul, udah mau kayak bangunan roboh!"],
            2 : ["tempatnya lumayan juga walau agak jauh","tempatnya kecil, kalo rame jadi sempit","ruangannya panas dan pengap","AC nya kurang dingin, so far so good","mungkin perlu buka cabang biar gak overload","coba harganya lebih murah dikit, pasti lebih rame","suka ada lalat masuk, perlu ditindak lanjuti"],
            3 : ["tempatnya nyaman buat kumpul sama teman-teman","pelayan nya oke-oke semua","biarpun jauh pasti aku datengin karena tempatnya oke","harganya murah, jadi suka","biarpun mahal tapi aku suka","gak bosen-bosen nya kesini karena dekat rumah","suka kesini kalo rame-rame sama temen","udah murah, cozy lagi, oke dah"],
            4 : ["high recommended buat yang low budget","paling cocok buat yang suka cuci mata","gak bosen-bosen nya buat kesini terus karena dekat rumah"],
            }
    
    users = User.objects.all()
    nUsers = users.count()
    
    for place in Place.objects.all():
        response += place.placeName + "<br />"
        nReview = randrange(6, 13)
        randomUsers = random.sample(users, nReview)
        
        for user in randomUsers:
            randPrice = randrange(5, 10)
            randService = randrange(5, 10)
            randLocation = randrange(5, 10)
            randCondition = randrange(5, 10)
            randComfort = randrange(5, 10)
            
            average = float(randPrice+randService+randLocation+randCondition+randComfort)/5
            
            if average <= 6.5:
                indextText = 1
            elif average <= 7.5:
                indextText = 2
            elif average <= 8.5:
                indextText = 3
            else:
                indextText = 4
            
            review = Review()
            review.reviewUser = user
            review.reviewPlace = place
            review.reviewPointPrice = randPrice
            review.reviewPointService = randService
            review.reviewPointLocation = randLocation
            review.reviewPointCondition = randCondition
            review.reviewPointComfort = randComfort
            review.reviewText = choice(text[indextText])
            #review.save()
            
            response += user.userAlias + " ("+str(average)+") => " + review.reviewText + "<br />"
        response += "<br />"
    
    return HttpResponse(response)
示例#25
0
    def post(self, request, *args, **kwargs):
        submission = Submission.objects.get(pk=kwargs.get('pk', None))

        if submission.status == 0:
            submission.status = 1
            submission.save()
            return redirect('review', submission.pk)
        elif submission.status == 1:
            form = ReviewForm(request.POST)
            if form.is_valid():
                review = Review(reviewer=request.user.judge,
                                submission=submission,
                                comment=request.POST['comment'])
                review.save()
                submission.status = request.POST['status']
                submission.save()
            return redirect('reviews')
示例#26
0
文件: views.py 项目: kpx13/vv
def review(request, name):
    c = get_common_context(request)
    r = Review.get_by_slug(name)
    if r:
        c.update({'p': r})
        c['title'] = r.name
        return render_to_response('page.html', c, context_instance=RequestContext(request))
    else:
        raise Http404()
示例#27
0
    def post(self, request, restaurant_id):
        user_who_wrote_review = request.user
        request_time = datetime.now(timezone.utc)
        review_data = json.loads(request.body)
        restaurant_for_review = Restaurants.objects.get(id=restaurant_id)
        orders_of_user = Order.objects.filter(
            user=user_who_wrote_review,
            restaurant=restaurant_for_review).order_by('-id')

        if len(orders_of_user) == 0:
            return JsonResponse({'message': 'INVALID_USER'}, status=401)

        latest_order_of_user = orders_of_user[0]
        date_of_latest_order = latest_order_of_user.created_at  #가장 최근 주문의 생성날짜
        #주문한지 7일이 지났다면 리뷰를 쓸수 없음
        days = 60 * 60 * 24
        if (request_time - date_of_latest_order).total_seconds() > (7 * days):
            return JsonResponse({'message': 'EXPIRED_PERIOD'}, status=401)

        rating = review_data['rating']
        #리뷰 등록
        Review(
            order=latest_order_of_user,
            user=user_who_wrote_review,
            restaurant=restaurant_for_review,
            comment=review_data['comment'],
            rating_taste=rating['taste'],
            rating_delivery=rating['delivery'],
            rating_quantity=rating['quantity'],
            rating_avg=sum(rating.values()) / len(rating),
            created_at=request_time,
        ).save()

        saved_review = Review.objects.latest('created_at')
        #menu와 review 연결
        join_review_menu_list = []
        for i in range(len(review_data['menus'])):
            join_review_menu_list.append(
                JoinReviewMenu(
                    review=saved_review,
                    menu=Menus.objects.get(id=review_data['menus'][i]['id']),
                    amount=review_data['amounts'][i],
                ))
        JoinReviewMenu.objects.bulk_create(join_review_menu_list)
        #review img와 review 연결
        if len(review_data['review_img']) != 0:
            review_img_list = []
            for i in range(len(review_data['review_img'])):
                review_img_list.append(
                    ReviewImage(
                        review=saved_review,
                        review_image=review_data['review_img'][i],
                    ))
            ReviewImage.objects.bulk_create(review_img_list)

        return JsonResponse({'message': 'SUCCESS'}, status=200)
示例#28
0
    def save(self, commit=True):
        """
        Though this form is linked to an Application instance, it's actually
        used to save the corresponding review instance.
        """

        data = {
            "reviewer": self.request.user,
            "interest": int(self.cleaned_data["interest"]),
            "experience": int(self.cleaned_data["experience"]),
            "quality": int(self.cleaned_data["quality"]),
            "reviewer_comments": self.cleaned_data["reviewer_comments"],
            "status": self.cleaned_data["status"],
        }

        review = getattr(self.instance, "review", None)

        if review is None:
            data["application"] = self.instance
            review = Review(**data)
        else:
            old_status = review.status

            for attr, value in data.items():
                setattr(review, attr, value)

            # If they were previously waitlisted and the status has been changed to
            # accepted or rejected, allow sending a new decision by clearing
            # decision_sent_date
            if old_status == "Waitlisted" and review.status != old_status:
                review.decision_sent_date = None

        if commit:
            review.save()
        else:
            self.review = review

            # If commit=False, super().save(commit=False) will set
            # self.save_m2m = self._save_m2m, for the user to call at a later time.
            # This will now also save the review instance.
            self._save_m2m = self._save_m2m_and_review

        return super().save(commit)
示例#29
0
class ReviewTestCase(TestCase):
    def setUp(self):
        self.instructor = Instructor(name="Teacher")
        self.instructor.save()
        self.review = Review(
            section=get_or_create_course_and_section("CIS-120-001", TEST_SEMESTER)[1],
            instructor=self.instructor,
        )
        self.review.save()

    def test_set_bits(self):
        self.review.set_averages(
            {
                "difficulty": 4,
                "course_quality": 3,
            }
        )
        self.assertEqual(2, ReviewBit.objects.count())
        self.assertEqual(4, ReviewBit.objects.get(field="difficulty").average)
示例#30
0
def get_reviews(url, movie, base=None):
    from requests import get
    from bs4 import BeautifulSoup as BS
    from time import sleep
    from random import randint

    reviews = 0

    try:
        response = get(url)

        html_soup = BS(response.text, 'html.parser')
        review_containers = html_soup.find_all('div',
                                               class_='imdb-user-review')

        for review in review_containers:
            title, comment, date, rating = get_review_info(review)

            review = Review()
            review.title = title
            review.comment = comment
            review.date = date
            review.movie = movie
            review.rating = rating
            review.url = url

            review.save()

        if html_soup.find('div', class_='load-more-data') is not None:
            if base is None:
                base = url

            _key = html_soup.find('div', class_='load-more-data')['data-key']
            _url = base + '/_ajax?paginationKey=' + _key
            sleep(randint(3, 8))
            get_reviews(_url, movie, base)
    except Exception as e:
        print('ERROR: ', e)
        print(movie, url)

    return reviews
示例#31
0
def create(request):
    # 여기서 글을 DB에 저장
    title = request.GET["title"]
    body = request.GET["body"]
    review = Review()
    review.title = title
    review.body = body
    review.pub_date = timezone.now()
    review.save()
    return redirect('home')
def add_review(request):
    '''
    allows users to add review and provide rating
    date created is recorded
    Displayed on book page
    '''
    logger.info("print add_review")
    context = {}
    user = request.user
    if user.is_authenticated:
        rating = int(request.POST.get("rating"))
        review_text = request.POST.get("review")
        isbn = request.POST.get("isbn")
        account = Account.objects.get(username=user.username)
        book = Books.objects.get(ISBN=isbn)
        try:
            findreview = Review.objects.filter(UID=account, BID=book)
            if findreview.exists():
                findreview.all().delete()

            review = Review(UID=account,
                            BID=book,
                            rating=rating,
                            review=review_text)
            review.save()
            review_data = {
                "id": review.id,
                "created_at": review.createdDate,
                "error": False,
                "errorMessage": "Add a review successfully!"
            }
            return JsonResponse(review_data, safe=False)
        except Exception as e:
            logger.info(e)
            print("cannot save review")
            review_data = {
                "error": True,
                "errorMessage": "Cannot add a review"
            }
            return JsonResponse(review_data, safe=False)
示例#33
0
def handle_review_csv(csv_file, user_who_uploaded):
	csv_file_text_mode = codecs.iterdecode(csv_file, "utf-8")
	csv_reader = csv.reader(csv_file_text_mode, delimiter=',')
	for row in csv_reader:
		try:
			first_email = row[0]
			second_email = row[1]
			first_application = Application.objects.filter(email=first_email).first()
			second_application = Application.objects.filter(email=second_email).first()
			winner = True if row[2] == "1" else False
			user = user_who_uploaded
			time = datetime.now()
			in_prog = False
			completed = True
			review = Review(winner=winner, 
					user=user, 
					time=time, 
					in_prog=in_prog, 
					completed=completed)
			review.apps.add(first_application, second_application)
			review.full_clean()
		except ValidationError as e:
			"""Fields are not valid."""
			return True, "The csv fields are not valid."
		else:
			review.save()
	return False, "Uploaded reviews"
示例#34
0
    def _review(
        self,
        application=None,
        reviewer=None,
        save=True,
        **kwargs,
    ):
        if application is None:
            application = self.user.application

        if reviewer is None:
            try:
                self.reviewer = User.objects.get(username="******")
            except User.DoesNotExist:
                self.reviewer = User.objects.create_user(
                    username="******", password="******")
                reviewer = self.reviewer

        decision_sent_date = kwargs.pop(
            "decision_sent_date",
            datetime.now().replace(tzinfo=settings.TZ_INFO).date())

        default_kwargs = {
            "reviewer": reviewer,
            "application": application,
            "interest": 10,
            "experience": 10,
            "quality": 10,
            "status": "Accepted",
            "reviewer_comments": "Very good",
            "decision_sent_date": decision_sent_date,
        }
        default_kwargs.update(kwargs)

        review = Review(**default_kwargs)
        if save:
            review.save()
            self.review = review

        return review
示例#35
0
 def setUp(self) -> None:
     courses = [
         Course(course_code="TDT4120", course_name="AlgDat", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="TMA4100", course_name="Matte 1", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="EXPH0004", course_name="Exphil", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="TFE4101", course_name="KretsDigtek", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="TFY4125", course_name="Fysikk", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="TDT4290", course_name="KPro", credit=7.5, average_grade=1, pass_rate=100.0),
         Course(course_code="TDT4136", course_name="AI Intro", credit=7.5, average_grade=1, pass_rate=100.0),
     ]
     for c in courses: c.save()
     reviews = [
         Review(id=1, course_code="TMA4100", user_email="*****@*****.**", score=5, workload=1, difficulty=2,
                review_text="Bra f*g", full_name="Test test", study_programme="MTDT"),
         Review(id=2, course_code="TMA4100", user_email="*****@*****.**", score=3, workload=0, difficulty=0,
                review_text="Givende", full_name="KPro Kproson", study_programme="MTKPRO"),
         Review(id=3, course_code="TMA4100", user_email="*****@*****.**", score=4, workload=1, difficulty=2,
                review_text="Lattice", full_name="Heman 2015", study_programme="MTDT"),
         Review(id=4, course_code="TDT4120", user_email="*****@*****.**", score=5, workload=2, difficulty=2,
                review_text="Kult", full_name="KPro Kproson", study_programme="MTKPRO"),
         Review(id=5, course_code="TDT4120", user_email="*****@*****.**", score=1, workload=0, difficulty=0,
                review_text="Kjipt", full_name="Test test", study_programme="MTDT"),
         Review(id=6, course_code="EXPH0004", user_email="*****@*****.**", score=3, workload=1, difficulty=0,
                review_text="<3", full_name="KPro Kproson", study_programme="MTDT")
     ]
     for r in reviews: r.save()
     UserAuth(expiring_token="valid_token", access_token="valid_token", user_email="*****@*****.**").save()
     User.objects.create(username="******", email="*****@*****.**").save()
示例#36
0
def submitreview(request, pid):
    if 'user' in request.session and Subscriber.objects.filter(email=request.session['user']).exists():
        post_data = request.POST
        this_product = Product.objects.get(id=pid)
        userObject = Subscriber.objects.get(email=request.session['user'])
        new_review = Review(subscriber=userObject,
                            product=this_product,
                            rating=post_data['rating'],
                            review=post_data['comment'])
        new_review.save()
        old_review_count = this_product.totalNumberOfRating
        old_star_rating = this_product.totalNumberOfStars
        new_star_rating = (int(old_review_count) * int(old_star_rating) +
                           int(post_data['rating'])) / (int(old_review_count)+1)
        new_review_count = int(old_review_count) + 1
        this_product.totalNumberOfRating = new_review_count
        this_product.totalNumberOfStars = new_star_rating
        this_product.save()

        return redirect('/product/'+pid)
    else:
        return redirect('/register')
示例#37
0
 def setUp(self):
     UserAuth(expiring_token="valid_token",
              access_token="valid_token",
              user_email="*****@*****.**").save()
     self.api_client = APIClient()
     self.api_client.credentials(HTTP_AUTHORIZATION="valid_token")
     User.objects.create(username="******",
                         email="*****@*****.**").save()
     User.objects.create(username="******",
                         email="*****@*****.**").save()
     Course(course_code="TMA4100",
            course_name="Matte 1",
            credit=7.5,
            average_grade=1,
            pass_rate=100.0).save()
     Review(course_code="TMA4100",
            user_email="*****@*****.**",
            score=5,
            workload=1,
            difficulty=2,
            review_text="Bra f*g",
            full_name="Test test",
            study_programme="MTDT").save()
     Review(course_code="TMA4100",
            user_email="*****@*****.**",
            score=3,
            workload=1,
            difficulty=2,
            review_text="Givende",
            full_name="KPro Kproson",
            study_programme="MTKPRO").save()
     self.curr_user = User.objects.get(username="******")
     self.other_user = User.objects.get(username="******")
     self.review1 = Review.objects.get(course_code="TMA4100",
                                       user_email="*****@*****.**")
     self.review2 = Review.objects.get(course_code="TMA4100",
                                       user_email="*****@*****.**")
     Upvote(user=self.curr_user, review=self.review1).save()
     Upvote(user=self.other_user, review=self.review1).save()
示例#38
0
def beer(request, beer_id):
	beer = get_object_or_404(Beer, pk=beer_id)
	reviews = Review.objects.filter(beer=beer.id)
	rating = reviews.aggregate(Avg('rating'))['rating__avg']

	# Maybe uneccesary	
	if request.user.is_authenticated():
		try:
			user_review = reviews.get(user = request.user)
		except ObjectDoesNotExist:
			user_review = None
	else: user_review = None

	if request.method == 'POST':
		reviewForm = ReviewForm(request.POST)
		if reviewForm.is_valid():
			body = reviewForm.cleaned_data['body']	
			r = Review(review_id=Review.objects.count()+1, user=request.user, beer=beer, body=body)
		        r.save()
			beer.rating = reviews.aggregate(Avg('rating'))['rating__avg']
			beer.save()	
			return render_to_response(
				'beer/beer.html', 
				{'beer': beer, 'rating':rating, 'reviews': reviews, 'user_review': r},
				context_instance=RequestContext(request)
			) 

	else:
		reviewForm = ReviewForm()
		return render_to_response(
			'beer/beer.html', 
			{'beer': beer, 'rating':rating, 'reviews': reviews, 'user_review': user_review, 'reviewForm': reviewForm},
			context_instance=RequestContext(request)
		)

	return render_to_response('beer/beer.html', 
		{'beer': beer, 'rating':rating, 'reviews': reviews, 'user_review': user_review, 'reviewForm': reviewForm},
		context_instance=RequestContext(request)
	)
示例#39
0
    def setUp(self):
        self.course, self.section = create_mock_data("CIS-120-001", TEST_SEMESTER)
        _, self.section2 = create_mock_data("CIS-120-002", TEST_SEMESTER)
        self.instructor = Instructor(name="Person1")
        self.instructor.save()
        self.rev1 = Review(
            section=create_mock_data("CIS-120-003", "2005C")[1],
            instructor=self.instructor,
            responses=100,
        )
        self.rev1.save()
        self.rev1.set_averages(
            {
                "course_quality": 4,
                "instructor_quality": 4,
                "difficulty": 4,
            }
        )
        self.instructor2 = Instructor(name="Person2")
        self.instructor2.save()
        self.rev2 = Review(
            section=create_mock_data("CIS-120-002", "2015A")[1],
            instructor=self.instructor2,
            responses=100,
        )
        self.rev2.instructor = self.instructor2
        self.rev2.save()
        self.rev2.set_averages(
            {
                "course_quality": 2,
                "instructor_quality": 2,
                "difficulty": 2,
            }
        )

        self.section.instructors.add(self.instructor)
        self.section2.instructors.add(self.instructor2)
        self.client = APIClient()
        set_semester()
示例#40
0
 def test_insert_review(self):
     """ Test if the review document is inserted properly """
     req = self.factory.post('/api/review/insert/',
                             self.expected,
                             content_type='application/json')
     actual = json.loads(view_response.insert_review_page(req).content)
     del actual['Timestamp']
     expected = Review(_id=actual['_id'],
                       restaurant_id="111111111111111111111111",
                       user_email="*****@*****.**",
                       title="title2",
                       content="content2",
                       rating=3)
     self.assertDictEqual(model_to_dict(expected), actual)
示例#41
0
    def __get_or_create_review(self, request, revision, all_reviews):
        review = all_reviews.filter(owner=request.global_user).first()
        if not review:
            review = Review()
            review.owner = request.global_user
            review.revision = revision
            review.save()

        return review
示例#42
0
def insert_review_page(request):
    """ Insert comment into database """
    validate(instance=request.body, schema=review_schema)
    body = json.loads(request.body)
    restaurant = Restaurant.objects.get(_id=ObjectId(body['restaurant_id']))
    review = Review.new_review(body)
    restaurant.rating = Review.new_rating(restaurant._id)
    restaurant.save(update_fields=['rating'])
    return JsonResponse({
        '_id':
        str(review._id),
        'restaurant_id':
        review.restaurant_id,
        'user_email':
        review.user_email,
        'title':
        review.title,
        'content':
        review.content,
        'Timestamp':
        review.Timestamp.strftime("%b %d, %Y %H:%M"),
        'rating':
        review.rating
    })
示例#43
0
文件: views.py 项目: spondbob/replace
def write(request):
    if request.method == "POST" :
        ret = "OK"
        
        user = User()
        user.userId = int(request.POST["userId"])
        
        place = Place()
        place.placeId = int(request.POST["placeId"])
        
        if Review.objects.filter(reviewUser=user, reviewPlace=place).exists():
            ret = "EXIST"
        else:
            review = Review()
            review.reviewUser = user
            review.reviewPlace = place
            review.reviewPointPrice = int(request.POST["reviewPointPrice"])
            review.reviewPointService = int(request.POST["reviewPointService"])
            review.reviewPointLocation = int(request.POST["reviewPointLocation"])
            review.reviewPointCondition = int(request.POST["reviewPointCondition"])
            review.reviewPointComfort = int(request.POST["reviewPointComfort"])
            review.reviewText = request.POST["reviewText"]
            review.save()

        return HttpResponse(ret)
    else :
        return HttpResponse("what?")
示例#44
0
class UpDownVoteTest(TestCase):
    def setUp(self):
      self.client = Client()
      self.user = User.objects.create_user('test_foo', '*****@*****.**','bqz_qux')
      self.user.save()
      self.user_two = User.objects.create_user('test_bar', '*****@*****.**', 'bqz_qux')
      self.user_two.save()

      self.toilet = Toilet(date = datetime.datetime.now() ,
                            creator = self.user, name = "test_toilet")
      self.toilet.save()
      self.review_one_one = Review(user=self.user, date = datetime.datetime.now(),
                               toilet = self.toilet, content = "foo bar", rank = 5,
                               up_down_rank = 0)
      self.review_one_one.save() 
      self.review_two_one =  Review(user=self.user_two, date = datetime.datetime.now(),
                               toilet = self.toilet, content = "foo bar", rank = 5,
                               up_down_rank = 0)
      self.review_two_one.save()
      
    #Upvote review 
    def test_up_vote_review(self):
      self.client.login(username=self.user.username, password='******')
      response = json.loads(self.client.post('/api/review/upvote/', {'review_pk': self.review_one_one.pk}).content)[0]
      updatedreview = Review.objects.get(pk=self.review_one_one.pk)
      self.assertEqual(updatedreview.up_down_rank, 1)
    
    #Try to upvote a review twice, only add the upvote once
    def test_up_vote_twice(self):
      vote = Vote(review=self.review_one_one, user = self.user_two, vote = 1) 
      vote.save()
      self.review_one_one.up_down_rank += 1
      self.review_one_one.save()
      self.client.login(username=self.user_two.username, password='******')
      response = json.loads(self.client.post('/api/review/upvote/', {'review_pk': self.review_one_one.pk}).content)[0]
      self.assertEqual(response['fields']['up_down_rank'],1)

    #Try to upvote when not logged in
    def test_up_vote_not_logged_in(self):
      response = self.client.post('/api/review/upvote/', {'review_pk': self.review_one_one.pk})
      self.assertEqual(response.status_code, 403)

    #upvote without review information
    def test_up_vote_no_data(self):
      self.client.login(username=self.user_two.username, password='******')
      response = self.client.post('/api/review/upvote/' )
      self.assertEqual(response.status_code, 400)

    def test_up_vote_get(self):
      self.client.login(username=self.user_two.username, password='******')
      response = self.client.get('/api/review/upvote/' )
      self.assertEqual(response.status_code, 415)
    #upvote a review that doesn't exist
    def test_up_vote_no_review(self):
      self.client.login(username=self.user_two.username, password='******')
      response = self.client.post('/api/review/upvote/', {'review_pk': 666})
      self.assertEqual(response.status_code, 400)
    #downvote a review
    def test_down_vote(self):
      self.client.login(username=self.user_two.username, password='******')
      response = json.loads(self.client.post('/api/review/downvote/', {'review_pk' : self.review_one_one.pk}).content)[0]
      self.assertEqual(response['fields']['up_down_rank'], -1)
      
    #Test down vote and upvote on same review 
    def test_down_after_up_vote(self):
      vote = Vote(review=self.review_one_one, user = self.user_two, vote = 1) 
      vote.save()
      self.review_one_one.up_down_rank += 1
      self.review_one_one.save()
      self.client.login(username=self.user_two.username, password='******')
      response = json.loads(self.client.post('/api/review/downvote/', {'review_pk': self.review_one_one.pk}).content)[0]
      self.assertEqual(response['fields']['up_down_rank'],0)
示例#45
0
 def _create_review(self):
     self.review = Review()
     self.review.owner = self.member.global_user
     self.review.revision = self.suggestion.get_current_revision()
     self.review.save()
示例#46
0
class Command(BaseCommand):
    help = \
        'Populates the database with example suggestions'

    def add_arguments(self, parser):
        pass

    def __migrate(self):
        if settings.DATABASES['default']['NAME'] == ":memory:":
            management.call_command('migrate', '--run-syncdb')
        else:
            management.call_command('migrate', '--run-syncdb')
            management.call_command(
                'makemigrations', 'goal', 'suggestion', 'review')
            management.call_command('migrate', '--fake-initial')

    def __make_global_user(self, username, password, first_name, last_name):
        user = User.objects.get_or_create(username=username)[0]
        user.set_password(password)
        user.first_name = first_name
        user.last_name = last_name
        user.save()

        global_user = GlobalUser()
        global_user.user = user
        global_user.save()

        return global_user

    def __create_superuser(self):
        management.call_command(
            'createsuperuser',
            '--noinput',
            username='******',
            email='*****@*****.**'
        )

        self.user_mnieber = self.__make_global_user(
            'mnieber', '***REMOVED***', 'Maarten', 'Nieber')

    def __create_users(self):
        self.user_anders_om = self.__make_global_user(
            "andersom", "***REMOVED***", "Anders", "Om")

        self.user_marie_houana = self.__make_global_user(
            "mhouana", "***REMOVED***", "Maria", "Houana")

    def __create_goal(self):
        self.become_a_yogi = Goal()
        self.become_a_yogi.owner = self.user_marie_houana
        self.become_a_yogi.title = "Become a yogi"
        self.become_a_yogi.is_draft = False
        self.become_a_yogi.save()

    def __create_members(self):
        self.yogi_mnieber = Member()
        self.yogi_mnieber.global_user = self.user_mnieber
        self.yogi_mnieber.goal = self.become_a_yogi
        self.yogi_mnieber.save()

        self.yogi_anders_om = Member()
        self.yogi_anders_om.global_user = self.user_anders_om
        self.yogi_anders_om.goal = self.become_a_yogi
        self.yogi_anders_om.save()

        self.yogi_marie_houana = Member()
        self.yogi_marie_houana.global_user = self.user_marie_houana
        self.yogi_marie_houana.goal = self.become_a_yogi
        self.yogi_marie_houana.save()

    def __create_suggestions(self):
        self.yoga_bend = Suggestion()
        self.yoga_bend.goal = self.become_a_yogi
        self.yoga_bend.owner = self.user_mnieber
        self.yoga_bend.is_draft = False
        self.yoga_bend.image = "suggestions/KroukTom-710x300-crop.jpg"
        self.yoga_bend.slug = "bend-backwards"
        self.yoga_bend.save()

        yoga_bend = Revision()
        yoga_bend.title = "Bend backwards"
        yoga_bend.description = yoga_bend_content
        yoga_bend.suggestion = self.yoga_bend
        yoga_bend.save()

        self.yoga_meditate = Suggestion()
        self.yoga_meditate.goal = self.become_a_yogi
        self.yoga_meditate.owner = self.user_mnieber
        self.yoga_meditate.is_draft = False
        self.yoga_meditate.image = "suggestions/Yoga_Nidra.jpg"
        self.yoga_meditate.slug = "meditate-often"
        self.yoga_meditate.save()

        yoga_meditate = Revision()
        yoga_meditate.title = "Meditate often"
        yoga_meditate.description = yoga_meditate_content
        yoga_meditate.suggestion = self.yoga_meditate
        yoga_meditate.save()

        self.yoga_twist = Suggestion()
        self.yoga_twist.goal = self.become_a_yogi
        self.yoga_twist.owner = self.user_anders_om
        self.yoga_twist.is_draft = False
        self.yoga_twist.image = "suggestions/MC_AM06_00_sized2.jpg"
        self.yoga_twist.slug = "keep-twisting"
        self.yoga_twist.save()

        self.rev_yoga_twist = Revision()
        self.rev_yoga_twist.title = "Keep twisting"
        self.rev_yoga_twist.description = yoga_twist_content
        self.rev_yoga_twist.suggestion = self.yoga_twist
        self.rev_yoga_twist.save()

        time.sleep(1)

        self.rev_yoga_twist_2 = Revision()
        self.rev_yoga_twist_2.title = "Keep twisting"
        self.rev_yoga_twist_2.description = yoga_twist_2_content
        self.rev_yoga_twist_2.suggestion = self.yoga_twist
        self.rev_yoga_twist_2.save()

        self.yoga_acrobatics = Suggestion()
        self.yoga_acrobatics.goal = self.become_a_yogi
        self.yoga_acrobatics.owner = self.user_marie_houana
        self.yoga_acrobatics.is_draft = False
        self.yoga_acrobatics.image = "suggestions/yoga-acrobats.jpg"
        self.yoga_acrobatics.slug = "yoga-acrobatics"
        self.yoga_acrobatics.save()

        yoga_acrobatics = Revision()
        yoga_acrobatics.title = "Acrobatics"
        yoga_acrobatics.description = yoga_acrobatics_content
        yoga_acrobatics.suggestion = self.yoga_acrobatics
        yoga_acrobatics.save()

    def __create_reviews(self):
        self.review_yoga_twist = Review()
        self.review_yoga_twist.owner = self.user_marie_houana
        self.review_yoga_twist.revision = self.rev_yoga_twist
        self.review_yoga_twist.rating = 2.5
        self.review_yoga_twist.description = "Not bad!"
        self.review_yoga_twist.is_draft = False
        self.review_yoga_twist.save()

        self.review_yoga_twist_2 = Review()
        self.review_yoga_twist_2.owner = self.user_mnieber
        self.review_yoga_twist_2.revision = self.rev_yoga_twist_2
        self.review_yoga_twist_2.rating = 4
        self.review_yoga_twist_2.description = "Good, good, good"
        self.review_yoga_twist_2.is_draft = False
        self.review_yoga_twist_2.save()

    def __create_comments(self):
        self.comment_1 = Comment()
        self.comment_1.owner = self.user_mnieber
        self.comment_1.body = "Thanks for the feedback"
        self.comment_1.review = self.review_yoga_twist
        self.comment_1.is_draft = False
        self.comment_1.save()

        self.comment_2 = Comment()
        self.comment_2.owner = self.user_anders_om
        self.comment_2.body = "I see your point"
        self.comment_2.review = self.review_yoga_twist
        self.comment_2.reply_to = self.comment_1
        self.comment_2.is_draft = False
        self.comment_2.save()

    def handle(self, *args, **options):
        management.call_command('initdb')
        self.__migrate()
        self.__create_superuser()
        self.__create_users()
        self.__create_goal()
        self.__create_members()
        self.__create_suggestions()
        self.__create_reviews()
        self.__create_comments()
示例#47
0
 def test_multiple_ratings(self):
     review1 = Review(rating=5, reviewer=self.user, parkingspot=self.test_spot1)
     review2 = Review(rating=4, reviewer=self.user, parkingspot=self.test_spot1)
     review3 = Review(rating=3, reviewer=self.user, parkingspot=self.test_spot1)
     review1.save()
     review2.save()
     review3.save()
     rating = self.test_spot1.get_avg_rating()
     self.assertEqual(4, rating)
     review1.delete()
     review2.delete()
     review3.delete()
示例#48
0
 def test_one_rating(self):
     review1 = Review(rating=5, reviewer=self.user, parkingspot=self.test_spot1)
     review1.save()
     rating = self.test_spot1.get_avg_rating()
     self.assertEqual(5, rating)
     review1.delete()