def testProfanities(self): """Test REVIEW_ALLOW_PROFANITIES and PROFANITIES_LIST settings""" a = Article.objects.get(pk=1) d = self.getValidData(a) # Save settings in case other tests need 'em saved = getattr(settings, 'PROFANITIES_LIST', []), getattr(settings, 'REVIEW_ALLOW_PROFANITIES', False) # Don't wanna swear in the unit tests if we don't have to... settings.PROFANITIES_LIST = ["rooster"] # Try with REVIEW_ALLOW_PROFANITIES off settings.REVIEW_ALLOW_PROFANITIES = False f = ReviewForm(a, data=dict(d, comment="What a rooster!", rating="4")) self.assertFalse(f.is_valid()) # Now with REVIEW_ALLOW_PROFANITIES on settings.REVIEW_ALLOW_PROFANITIES = True f = ReviewForm(a, data=dict(d, comment="What a rooster!", rating="4")) self.assertTrue(f.is_valid()) # Restore settings settings.PROFANITIES_LIST, settings.REVIEW_ALLOW_PROFANITIES = saved
def test_missing_data(self): # missing title and user_display_name is allowed form_data = { 'rating': 3, 'review': 'Not bad' } form = ReviewForm(data=form_data) self.assertTrue(form.is_valid()) form_data = { 'review': 'Not bad' } form = ReviewForm(data=form_data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {'rating': ['This field is required.']} ) form_data = { 'rating': 2 } form = ReviewForm(data=form_data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {'review': ['This field is required.']} )
def educator_profile(request, educator_id): educator = Educator.objects.get(pk=educator_id) profile_form = EducatorProfileForm(instance=educator) if Review.objects.all().exists(): reviews = Review.objects.filter(educator=educator) else: reviews = None if request.method == 'POST': review_form = ReviewForm(data=request.POST) if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.educator = educator review.save() return HttpResponseRedirect('/profiles/%d/' % educator.id) else: review_form = ReviewForm() return render(request, 'educator_profile.html', {'educator' : educator, 'profile_form' : profile_form, 'review_form' : review_form, 'reviews' : reviews})
def review(request, prof_id=None): """ Review a prof """ if (request.method == 'POST'): # Insert the current user, and the prof with the id # Happens when review is made through Review post_values = request.POST.copy() if prof_id: post_values['prof'] = prof_id post_values['user'] = request.user.id print(post_values) form = ReviewForm(post_values) if (form.is_valid()): form.save() prof_id = post_values['prof'] return redirect(reverse('profs_getProf', args=(prof_id, ))) else: print(form.errors) return render(request, 'reviews/review_form.html') # If there's an input prof, return review page for that prof if prof_id: user = User.objects.get(pk=request.user.id) prof = prof_views.prof(prof_id) course = prof.course_set.all() data = {'user': user, 'prof': prof} review_form = ReviewForm(initial=data) review_form.fields['course'].queryset = course curr_prof = True return render(request, 'reviews/review_form.html', { 'review_form': review_form, 'curr_prof': curr_prof, 'prof': prof }) review_form = ReviewForm() return render(request, 'reviews/review_form.html', {'review_form': review_form})
def tamperWithForm(self, **kwargs): a = Article.objects.get(pk=1) d = self.getValidData(a) d.update(kwargs) f = ReviewForm(Article.objects.get(pk=1), data=d) self.assertFalse(f.is_valid()) return f
def product_detail(request,id): product = get_object_or_404(Product,id=id) reviews = Review.objects.all().filter(product=product) average_rating = reviews.aggregate(Avg('rating')) if average_rating['rating__avg']: average_rating = int(round(average_rating['rating__avg'])) else: average_rating = 0 reviews_count = reviews.aggregate(Count('id')) reviews_count = reviews_count['id__count'] form = ReviewForm(request.POST or None) if form.is_valid() and request.user.is_authenticated(): review = form.save(commit=False) review.user = request.user review.product = product review.save() return HttpResponseRedirect(product.get_absolute_url()) context = { "title":product.name, "instance":product, "review_form":form, "reviews":reviews, "average_rating":average_rating, "reviews_count":reviews_count } return render(request,"product_detail.html",context)
def test_add_review_form_invalid(self): form = ReviewForm({ 'content': 'Test content', 'rating': True, }) self.assertFalse(form.is_valid())
def product_detail(request, pk): ''' Create a view that returns a single Product object based on the product ID (pk) and render it to the 'product_detail.html' template Or return a 404 if the post is not found. ''' product = get_object_or_404(Product, pk=pk) avg_rating = Review.objects.filter(product_id=pk).aggregate(Avg('rating')) try: reviews = Review.objects.filter(product_id=pk).order_by('-created') except: reviews = None if request.method == 'POST': form = ReviewForm(request.POST, request.FILES) if form.is_valid(): review = form.save(commit=False) review.product = product review.user = request.user review.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = ReviewForm() context = { 'product': product, 'avg_rating': avg_rating, 'reviews': reviews, 'form': form, } return render(request, "product_detail.html", context)
def add_review(request, wine_id): wine = get_object_or_404(Wine, pk=wine_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data["rating"] print(rating) print(form.cleaned_data) comment = form.cleaned_data["comments"] user_name = request.user.username review = Review() review.wine = wine review.user_name = user_name review.rating = rating review.comments = comment review.pub_date = datetime.datetime.now() review.save() update_clusters() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect( reverse("reviews:wine_detail", args=(wine.id, ))) return render(request, "reviews/wine_detail.html", { "wine": wine, "form": form })
def review_project(request, slug): project = get_object_or_404(Project, slug=slug) profile = request.user.get_profile() reviewer = Reviewer.objects.get(user=profile) if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.project = project review.author = profile review.save() if reviewer.can_feature: project.community_featured = review.mark_featured if reviewer.can_delete: project.deleted = review.mark_deleted if reviewer.can_feature or reviewer.can_delete: project.save() review.send_notifications() messages.success(request, _('Review posted!')) return http.HttpResponseRedirect(review.get_absolute_url()) else: messages.error(request, _('Please correct errors below.')) else: form = ReviewForm() context = {'form': form, 'project': project, 'reviewer': reviewer} return render_to_response('reviews/review_project.html', context, context_instance=RequestContext(request))
def book_detail(request, book_id): """" A view for book detail page """ book = get_object_or_404(Book, pk=book_id) book_reviews_found = Review.objects.filter( book_id=book_id).order_by('-review_id') if book_reviews_found.count() > 0: book_reviews_count = book_reviews_found.count() + book.ratings_count else: book_reviews_count = book.ratings_count form = ReviewForm(request.POST or None) if request.method == 'POST': if form.is_valid(): form.instance.user = request.user form.instance.book = book form.save() messages.success(request, 'Review Submitted') form = ReviewForm(None) return redirect( reverse('book_detail', kwargs={'book_id': book.book_id})) context = { "book": book, "book_reviews_count": book_reviews_count, "form": form, } return render(request, 'books/book_detail.html', context)
def create_review(request, book_id): if request.method == "POST": create_form = ReviewForm(request.POST) if create_form.is_valid(): # The commit=false optional parameter is passed to the form.save() function. # This will create a new instance of Review using the data in the POST request, # but won't save to the database yet so that we can assign the user to the review. review = create_form.save(commit=False) # To access the current user by referring to the user object inside the request object. # When the review is added, we will assign the current logged # in user to the user variable in the Review object. review.user = request.user review.book = get_object_or_404(Book, pk=book_id) review.save() messages.success( request, f"New Book Review, {create_form.cleaned_data['title']}, has been created" ) return redirect(reverse(index)) else: return render(request, 'reviews/create-template.html', {'form': create_form}) else: create_form = ReviewForm() return render(request, 'reviews/create-template.html', {'form': create_form})
def class_page(request, class_id): educator_class = EducatorClass.objects.get(id=class_id) educator = educator_class.user.educator reviews = Review.objects.filter(educator_class=educator_class) if request.method == 'POST': review_form = ReviewForm(data=request.POST) if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.educator = educator review.educator_class = educator_class review.save() return render(request, 'class_page.html', {'educator_class' : educator_class, 'educator' : educator, 'reviews' : reviews, 'review_form' : review_form}) else: review_form = ReviewForm() return render(request, 'class_page.html', {'educator_class' : educator_class, 'educator' : educator, 'reviews' : reviews, 'review_form' : review_form})
def product_view(request, p_id): try: temp = Product.objects.get(pk=p_id) except Product.DoesNotExist: return HttpResponseNotFound('<h1>Page not found</h1>') if not temp.is_active: return HttpResponseNotFound('<h1>Page not found</h1>') form = ReviewForm(request.POST or None) if request.method == "POST": if not request.user.is_authenticated: return redirect("/login") if form.is_valid(): try: OrderedItem.objects.get(user=request.user, product=temp) except OrderedItem.DoesNotExist: return HttpResponseNotAllowed( "you have not ordered item please order it to review") except OrderedItem.MultipleObjectsReturned: pass review_given = True try: ProductReview.objects.get(user=request.user, product=temp) except ProductReview.DoesNotExist: review_given = False except ProductReview.MultipleObjectsReturned: pass if review_given: return HttpResponseNotAllowed( "you have already submited review") form = form.save(commit=False) form.user = request.user form.product = temp print(type(form.rating)) if form.rating == 1: temp.rating_1 += 1 elif form.rating == 2: temp.rating_2 += 1 elif form.rating == 3: temp.rating_3 += 1 elif form.rating == 4: temp.rating_4 += 1 elif form.rating == 5: temp.rating_5 += 1 temp.rating_avg = round( ((temp.rating_1 + 2 * temp.rating_2 + 3 * temp.rating_3 + 4 * temp.rating_4 + 5 * temp.rating_5) / (temp.rating_1 + temp.rating_2 + temp.rating_3 + temp.rating_4 + temp.rating_5)), 2) form.save() temp.save() form = ReviewForm() product_user = temp.user is_seller = product_user.username == request.user.username return render(request, "product_template.html", { "product": temp, "form": form, "is_seller": is_seller })
def test_blank_form(self): form = ReviewForm({}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'author': ['This field is required.'], 'rating': ['This field is required.'], 'content': ['This field is required.'], })
def test_add_review_form_valid(self): form = ReviewForm({ 'title': 'Test Form', 'content': 'Test content', 'rating': True, }) self.assertTrue(form.is_valid())
def test_form_valid(self): form_data = { 'user_display_name': 'Me', 'title': 'Test title', 'rating': 3, 'review': 'Not bad' } form = ReviewForm(data=form_data) self.assertTrue(form.is_valid())
def add_review(request, movie_id): movie = get_object_or_404(Movie, pk=movie_id) form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.movie = movie review.save() if request.is_ajax(): return HttpResponse(json.dumps({'author': review.author, 'body': review.body }), status=200) return HttpResponseRedirect(reverse('movie-detail', args=[movie_id]))
def product_reviews(request, product_id): """ Returns a view with all the reviews for a specific product. If current user has a review, get that and allow them to update. """ product = get_object_or_404(Product, pk=product_id) reviews = Review.objects.filter(product=product_id) form = ReviewForm() user_review = "" user_purchased = False if request.user.is_authenticated: user_profile = UserProfile.objects.get(user=request.user) user_purchased = verify_purchase(user_profile, Order, product) for review in reviews: if review.user_profile == user_profile: user_review = review form = ReviewForm(instance=user_review) if request.method == "POST": if user_review != "": form = ReviewForm(request.POST, instance=user_review) else: if len(request.POST["review_content"]) <= 15: messages.error( request, "Review not long enough, please write a review longer than 15 characters.", ) return redirect(reverse("product_reviews", args=(product_id, ))) form_data = { "review_content": request.POST["review_content"], } form = ReviewForm(form_data) if form.is_valid(): review = form.save(commit=False) review.user_profile = user_profile review.product = product review.save() messages.success(request, "Review added.") return redirect(reverse("product_reviews", args=(product_id, ))) messages.error(request, "Error adding review.") return redirect(reverse("product_reviews", args=(product_id, ))) context = { "product": product, "reviews": reviews, "form": form, "user_review": user_review, "user_purchased": user_purchased, "page_title": f"{product.name} reviews", } return render(request, "products/product-reviews.html", context)
def create_review(request, id_user): form = ReviewForm() if request.method == "POST": form = ReviewForm(data=request.POST) # Si el formulario es válido... if form.is_valid(): rate = form.cleaned_data['valoration'] com = form.cleaned_data['comment'] if 0.0 <= float(rate) <= 5.0: fromUser = get_object_or_404(User, pk=request.user.id) toUser = get_object_or_404(User, pk=id_user) rent_list_from = Rent.objects.filter(user=fromUser) rent_list_to = Rent.objects.filter(user=toUser) games_from = Game.objects.filter(owner=fromUser) games_to = Game.objects.filter(owner=toUser) #Voy a comprobar si ambos usuarios comparten un alquiler existRent = False if rent_list_from: for rent in rent_list_from: for game in games_to: if rent.game == game: existRent = True break if rent_list_to: for rent in rent_list_to: for game in games_from: if rent.game == game: existRent = True break if existRent: valoration = Valoration(fromUser=fromUser, toUser=toUser, rate=rate) comment = Comment(fromUser=fromUser, toUser=toUser, comment=com) valoration.save() comment.save() list_valoration = Valoration.objects.filter(toUser=toUser) suma = 0.0 numero = 0 for valor in list_valoration: suma = suma + valor.rate numero = numero + 1 media = suma/numero toUser.rate = media try: toUser.save() except DataError: return redirect('/profile/{}'.format(toUser.id)) return redirect('/profile/{}'.format(toUser.id)) else: return render(request, "createReview.html", {'form': form, 'mensaje': 'Necesitas haber alquilado algun producto del Usuario para poder darle una valoración'}) else: return render(request, "createReview.html", {'form': form}) return render(request, "createReview.html", {'form': form})
def test_invalid_rating(self): form_data = { 'rating': 0, 'review': 'Not bad' } form = ReviewForm(data=form_data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {'rating': ['Rating must be between 1 and 5.']} )
def submit(request): if request.method == "POST": review_form = ReviewForm(data=request.POST) next_url = request.POST.get("next_url", "/") if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.save() return redirect(next_url) else: return public(request, review_form) return redirect('/')
def views_create(request, event): if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): event = Event.objects.get(pk=event) event.reviews.create(user=request.user,review=request.POST['review']) return redirect('events:musics_show', event.id) return HttpResponse({"message": "works"})
def post(self, *args, **kwargs): qs = Review.objects.filter(user=self.request.user, book=self.get_object()) if not qs.exists(): form = ReviewForm(self.request.POST) if form.is_valid(): obj = form.save(commit=False) obj.user = self.request.user obj.book = self.get_object() obj.save() else: form = ReviewForm(self.request.POST, instance=qs.first()) form.save() return redirect('books:book_detail', self.get_object().id)
def post(self, request, pk): url = f'/furniture/details/{self.get_object().id}/' post_values = request.POST.copy() form = ReviewForm(post_values) if form.is_valid(): author = Profile.objects.get(user__pk=request.user.id) post_values['furniture'] = self.get_object() review = Review(content=post_values['content'], score=post_values['score'], furniture=self.get_object(), author=author) review.save() return HttpResponseRedirect(url)
def test_valid_data(self): form = ReviewForm({ 'author': 'test author', 'rating': 5, 'content': "This is an awesome supplier!" }) self.assertTrue(form.is_valid()) test_review = form.save(commit=False) test_review.supplier = self.ts1 test_review.save() self.assertEqual(test_review.author, 'test author') self.assertEqual(test_review.rating, 5) self.assertEqual(test_review.content, 'This is an awesome supplier!') self.assertEqual(test_review.status, 'draft') self.assertIs(test_review.supplier, self.ts1)
def index(request): # Make a request if(request.method=='POST'): post_values = request.POST.copy() post_values['user'] = request.user.id form = ReviewForm(post_values) if(form.is_valid()): form.save() # Go to that profs page prof_id = post_values['prof'] return redirect(reverse('profs_getProf', args=(prof_id,))) profs = all_profs() return render(request, 'profs/index.html', {'review_form': ReviewForm, 'profs': profs})
def add_review(request, id): """ View to add a review for an artifact, redirect back to view detail. """ if request.method == "POST": review_form = ReviewForm(request.POST) if review_form.is_valid(): review_artifact = review_form.save(commit=False) try: review_artifact.review_id = Review.objects.get(artifact=id) except: review_artifact.review_id = Review.objects.create( artifact=Artifact.objects.get(pk=id)) review_artifact.review_owner_id = request.user.id review_artifact.review_date = timezone.now() review_artifact.save() messages.success( request, "You have successfully added a review for the artifact.") else: messages.error( request, "Sorry, there was a problem with your review submission.") else: review_form = ReviewForm() reviewed = False reviews = ReviewLineItem.objects.filter(review_id__artifact=id) artifact = Artifact.objects.get(id=id) ownership = OrderLineItem.objects.filter(artifact=id).filter( owner_id=request.user.id).first() if ownership != None: owner = True for review in reviews: if review.review_owner_id == ownership.owner_id: reviewed = True else: owner = False return render( request, "review.html", { "artifact": artifact, "review_form": review_form, "reviews": reviews, "owner": owner, "reviewed": reviewed, }) return redirect("view_artifact", id=id)
def getProf(request, prof_id): # Make a new review for the specific prof if(request.method=='POST'): # Insert the current user, and the prof with the id post_values = request.POST.copy() post_values['prof'] = prof_id post_values['user'] = request.user.id form = ReviewForm(post_values) if(form.is_valid()): form.save() return redirect(reverse('profs_getProf', args=(prof_id,))) else: messages.error(request, "Error") return render(request, 'profs/prof.html') prof = Prof.objects.get(pk=prof_id) reviews = Review.objects.filter(prof = prof) return render(request, 'profs/prof.html', {'review_form': ReviewForm, 'prof': prof, 'reviews': reviews})
def add_review(request, laptop_id): laptop = get_object_or_404(Laptop, id=laptop_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] review = Review() review.laptop = laptop review.rating = rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('reviews:review_detail', args=(review.id,))) return render(request, 'add_review.html', {'laptop': laptop, 'form': form})
def product_detail(request, id): """Specific details of a particular book""" product = get_object_or_404(Product, id=id) reviews = Review.objects.filter(product_id=id).order_by('pub_date') product.views = product.views + 1 product.save() if request.method == 'POST': form = ReviewForm(request.POST, request.FILES) if form.is_valid(): review = form.save(commit=False) review.product = product review.user = request.user review.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) else: form = ReviewForm() context = {'product': product, 'reviews': reviews, 'form': form} return render(request, 'product_detail.html', context)
def create(request): if request.method == "GET": form = ReviewForm(initial={'hours': 0}) return TemplateResponse(request, 'reviews/edit.html', {'form': form}) elif request.method == "POST": review = Review(user=request.user) form = ReviewForm(request.POST, instance=review) if form.is_valid(): form.save() profile = request.user.userprofile profile.semester_reviews = F('semester_reviews') + 1 profile.total_reviews = F('total_reviews') + 1 profile.save() return redirect('prof_course_detail', course_slug=review.prof_course.course.slug, prof_slug=review.prof_course.prof.slug) else: return TemplateResponse(request, 'reviews/edit.html', {'form': form})
def add_review(request, game_id): game = get_object_or_404(Game, pk=game_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name = request.user.username review = Review() review.game = game review.user_name = user_name review.rating = rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() """Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button.""" return HttpResponseRedirect(reverse('game_detail', args=(game.id,))) return render(request, 'game_detail.html', {'game': game, 'form': form})
def add_review(request, game_id): game = get_object_or_404(Game, pk=game_id) form = ReviewForm(request.POST) if form.is_valid(): rating = form.cleaned_data['rating'] comment = form.cleaned_data['comment'] user_name = request.user.username review = Review() review.game = game review.user_name = user_name review.rating = rating review.comment = comment review.pub_date = datetime.datetime.now() review.save() """Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button.""" return HttpResponseRedirect(reverse('game_detail', args=(game.id, ))) return render(request, 'game_detail.html', {'game': game, 'form': form})
def book(request, book_id): ''' Returns the view for a single book ''' book = get_object_or_404(Books, pk=book_id) reviews = Review.objects.filter(book_id=book_id).order_by("pub_date") authors = book.author author = Author.objects.all().filter(name=True) if request.method == "POST": form = ReviewForm(request.POST, request.FILES) if form.is_valid(): review = form.save(commit=False) review.book = book review.user = request.user review.save() return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: form = ReviewForm() context = {"book": book, "author": "author", "reviews": reviews, "form": form} return render(request, "books/book.html", context)
def update_review(request, review_id): review_to_be_updated = get_object_or_404(Review, pk=review_id) if request.method == 'POST': update_form = ReviewForm(request.POST, instance=review_to_be_updated) if update_form.is_valid(): update_form.save() messages.info( request, f"{update_form.cleaned_data['title']} has been updated") return redirect(reverse(index)) else: return render(request, 'reviews/update-template.html', {'form': update_form}) else: update_form = ReviewForm(instance=review_to_be_updated) return render(request, 'reviews/update-template.html', {'form': update_form})
def write_review_view(request, product_slug): product = Product.objects.filter(slug=product_slug).first() review_form = ReviewForm(request.POST or None) if request.method == 'POST': if review_form.is_valid(): title = review_form.cleaned_data['title'] body = review_form.cleaned_data['body'] score = review_form.cleaned_data['score'] new_review = Review(user = request.user , product = product , title=title, body=body, score=score) new_review.save() return redirect('product_view', product_slug=product_slug) context = { 'product': product, 'review_form': review_form, } return render(request, 'products/write_review.html', context)
def add_review(request, game_slug): try: game = Game.objects.get(slug=game_slug) except Game.DoesNotExist: return restricted(request, status=404, message="The game you're looking for doesn't exist") if request.method == 'POST': review_form = ReviewForm(data=request.POST) if review_form.is_valid(): # Save review to database review = review_form.save(commit=False) review.poster = request.user review.game = game review.save() messages.success(request, "Your review has been added") # Update stored average rating game.average_rating = \ (game.average_rating * game.number_ratings + int(review.rating)) / (game.number_ratings + 1) game.number_ratings += 1 game.save() print(review.id) return HttpResponseRedirect( reverse('game', kwargs={'game_slug': game_slug})) else: messages.error(request, "You submitted an invalid review") review_form = ReviewForm() else: review_form = ReviewForm() context_dict = init_context_dict(request, "Add Review") context_dict['review_form'] = review_form context_dict['slug'] = game_slug return render(request, 'reviews/review.html', context=context_dict)
def movie_detail(request, movie_pk): movie = get_object_or_404(Movie, pk=movie_pk) error = '' recommendations = Movie.objects.filter(category=movie.category).exclude( pk=movie_pk) if request.method == 'POST': review_form = ReviewForm(request.POST) if request.user.is_authenticated(): if review_form.is_valid(): new_review = review_form.save(commit=False) new_review.movie = movie new_review.user = request.user new_review.save() return redirect(reverse('movies:detail', args=(movie.pk, ))) else: error = 'Debes estar logeado para dejar una review' review_form = ReviewForm() avg_rating = Movie.avg_rating(movie) if request.user.is_staff: reviews = movie.reviews.a_moderar() else: reviews = movie.reviews.aceptado() context = { 'movie': movie, 'review_form': review_form, 'error': error, 'avg_rating': avg_rating, 'recommendations': recommendations, 'reviews': reviews } return render(request, 'movie_detail.html', context)
def edit(request, review_id): review = get_object_or_404(Review.objects.select_related(), id=review_id) # Cannot view an individual review of another user if request.user != review.user: raise Http404 # Show the edit page if request.method == "GET": form = ReviewForm(instance=review) return TemplateResponse(request, 'reviews/edit.html', {'form': form}) # Update the review elif request.method == "POST": form = ReviewForm(request.POST, instance=review) if form.is_valid(): form.save() return redirect('index') else: return TemplateResponse(request, 'reviews/edit.html', {'form': form}) else: return HttpResponse(status=404)
def book_info(request, book_id): books = Book.objects.all() books_nav = books.order_by('-release_date')[:2] cart = request.session.get('shopping_cart', {}) grand_total = 0 for item in cart: grand_total += cart[item]['subtotal'] book_selected = get_object_or_404(Book, pk=book_id) book_form = BookForm(instance=book_selected) review_form = ReviewForm(request.POST) reviews = Review.objects.filter(book=book_id) if request.method == "POST": if request.user.is_authenticated: if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.book = book_selected review.save() messages.success( request, f"Review has been posted on {book_selected.title}") return redirect('book_info', book_id=book_id) else: messages.warning(request, "Kindly log in to post reviews !") return redirect('account_login') return render( request, 'books/book_info.template.html', { "books_nav": books_nav, "form": book_form, "book": book_selected, "reviews": reviews, "review_form": review_form, "grand_total": grand_total, })
def test_form_review_ok(self): form = ReviewForm({'content': "content", "rating": "5"}) self.assertTrue(form.is_valid())
def create_review(request, order_id): order_model = get_object_or_404(Order, pk=order_id) if request.method == "POST": review_form = ReviewForm(request.POST) # save the review into the database and flash out a review # successfully added message if review_form.is_valid(): filled_review_form = review_form.save(commit=False) filled_review_form.reviewed_by = request.user filled_review_form.plant = order_model.plant filled_review_form.order = order_model filled_review_form.save() # to retrieve the plant to display on product page plant = get_object_or_404(Plant, pk=filled_review_form.plant.id) query = Q(plant__exact=plant) # to retrieve all reviews reviews = Review.objects.all() # to retrieve all the reviews for the plant plant_reviews = reviews.filter(query).values().distinct() # to retrieve ave ratings of the selected plant plant_ave_rating = plant_reviews.aggregate(Avg('rating')) # to retrieve total number of reviews for the selected plant plant_total_reviews = plant_reviews.count() # to save the plant total reviews and average ratings if plant_ave_rating != None and plant_total_reviews: plant.rating = float(plant_ave_rating['rating__avg']) plant.save(update_fields=["rating"]) plant.reviews = plant_total_reviews plant.save(update_fields=["reviews"]) messages.success(request, "Your review is successfully added.") return redirect(reverse(user_account)) else: create_review_form = ReviewForm() return render(request, 'reviews/user_review-template.html', { 'form': create_review_form, "order": order_model }) else: create_review_form = ReviewForm() return render(request, 'reviews/user_review-template.html', { 'form': create_review_form, "order": order_model })