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 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 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 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 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 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 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 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 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 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_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 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 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, 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 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 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 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 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 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 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 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 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 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 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 })