Beispiel #1
0
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)
Beispiel #2
0
def reviews(request):
    reviews_set = Review.objects.filter(is_active=True).order_by('date')
    department_set = Department.objects.all()

    review_form = ReviewForm(request.POST or None)
    if request.method == 'POST' and review_form.is_valid():
        review_form.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    appointment_form = AppointmentForm(request.POST or None)
    if request.method == 'POST' and appointment_form.is_valid():
        appointment_form.save()
        return HttpResponseRedirect(request.META.get('HTTP_REFERER'))

    paginator = Paginator(reviews_set, 4, orphans=2)
    page = request.GET.get('page')
    try:
        articles = paginator.page(page)
    except PageNotAnInteger:
        articles = paginator.page(1)
    except EmptyPage:
        articles = paginator.page(paginator.num_pages)

    return render(
        request, 'reviews.html', {
            "articles": articles,
            "review_form": review_form,
            'appointment_form': appointment_form,
            'departments': department_set
        })
Beispiel #3
0
def reviews(request):
    c = get_common_context(request)
    # display all approved reviews with pagination
    items = Review.objects.filter(approved=True)
    paginator = Paginator(items, PAGINATION_COUNT)
    page = int(request.GET.get("page", "1"))
    try:
        items = paginator.page(page)
    except PageNotAnInteger:
        page = 1
        items = paginator.page(page)
    except EmptyPage:
        page = paginator.num_pages
        items = paginator.page(page)
    c["page"] = page
    c["page_range"] = paginator.page_range
    if len(c["page_range"]) > 1:
        c["need_pagination"] = True
    c["reviews"] = items
    # get places list to populate place choices
    c["places"] = Place.objects.all()
    if request.method == "POST":
        form = ReviewForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            c["review_ok"] = True
    form = ReviewForm()
    c.update({"form": form})
    return render_to_response("reviews.html", c, context_instance=RequestContext(request))
Beispiel #4
0
    def post(self, request):
        form = ReviewForm(request.POST)
        print(form)
        if form.is_valid():

            print(' in review create')
            form.save(commit=True)
        else:
            print('in else')
            form = ReviewForm()
        return render(request, 'companyreview.html', {'form': form})
Beispiel #5
0
def modify_review(request, id_review):
    context = {}
    review = get_object_or_404(Review, pk=id_review)
    if request.method == 'GET':
        if review is None:
            pass
        else:
            form = ReviewForm(instance=review)
            context = {'post': {'content': review.ticket}, 'form': form}
        return render(request, 'review/addreview.html', context)
    elif request.method == 'POST':
        form = ReviewForm(request.POST, instance=review)
        if form.is_valid():
            form.save()
            return redirect('posts')
Beispiel #6
0
def review_update(request, service_id, review_id):
    categories = Category.objects.all().order_by('updated_at')
    my_re = Review.objects.get(pk=review_id)
    try:
        service = Service.objects.get(pk=service_id)
    except:
        raise Http404
    review = Review.objects.filter(service_obj=service)
    review_form = ReviewForm(instance=my_re)
    if request.method=="POST":
        updated_form = ReviewForm(request.POST, instance=my_re)
        if updated_form.is_valid():
            updated_form.save()
            return redirect('my_review')
    return render(request, 'service.html', {'review':review,'review_form':review_form,'categories':categories,'service':service})
Beispiel #7
0
def review_add_view(request, pk):
    user = request.user
    if not user.is_authenticated:
        return HttpResponse(status=403)

    member = Member.objects.get(pk=user.id)
    if member.member_type != 0:
        return HttpResponse(status=401)

    market = Market.objects.get(pk=pk)
    form = ReviewForm()

    if request.method == 'POST':
        form = ReviewForm(data=request.POST)
        if form.is_valid():
            review = form.save(commit=False)
            review.market_idx = market.id
            review.reviewer_idx = member.consumer_idx
            review.reviewer_name = member.username
            review.save()

            market.stars += review.stars
            market.save()
            return redirect('market_post', pk=pk)

    context = {'form': form, 'market': market}
    return render(request, 'review/add.html', context=context)
Beispiel #8
0
    def test_save_form_with_no_existing_review(self):
        self._apply()

        form = ReviewForm(instance=self.user.application,
                          data=self.data,
                          request=self.request)
        self.assertTrue(form.is_valid())
        form.save()

        self.user.refresh_from_db()
        self.assertTrue(hasattr(self.user.application, "review"))

        review = self.user.application.review
        for field in self.data:
            self.assertEqual(getattr(review, field), self.data[field])
        self.assertEqual(review.reviewer, self.reviewer2)
Beispiel #9
0
def create_review(request):

    created = False

    if request.method == 'POST':

        review_form = ReviewForm(data=request.POST)

        if review_form.is_valid():

            review = review_form.save()
            review.save()

            created = True

        else:
            print(review_form.errors)

    else:

        review_form = ReviewForm()

    return render(request, 'review/create_review.html', {
        'review_form': review_form,
        'created': created
    })
Beispiel #10
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"
            })
Beispiel #11
0
    def test_save_form_does_not_clear_decision_sent_date_for_waitlisted_changes(
            self):
        """
        When waitlisted, changes are still allowed to the review. Unlike above, if
        their status is not changed to something else, changes get saved but
        decision_sent_date should not get cleared.
        """
        self._apply()
        self._review(status="Waitlisted")

        form = ReviewForm(instance=self.user.application,
                          data=self.data,
                          request=self.request)
        self.assertTrue(form.is_valid())
        form.save()

        self.user.refresh_from_db()

        review = self.user.application.review
        self.assertIsNotNone(review.decision_sent_date)
Beispiel #12
0
    def test_save_form_with_existing_review(self):
        """
        Reviews are allowed to be changed as long as a decision
        has not been sent (tested above)
        """
        self._apply()
        self._review(decision_sent_date=None)

        form = ReviewForm(instance=self.user.application,
                          data=self.data,
                          request=self.request)
        self.assertTrue(form.is_valid())
        form.save()

        self.user.refresh_from_db()

        review = self.user.application.review
        for field in self.data:
            self.assertEqual(getattr(review, field), self.data[field])
        # The reviewer should be updated
        self.assertEqual(review.reviewer, self.reviewer2)
Beispiel #13
0
    def test_save_with_commit_false(self):
        """
        When save is called with commit=False, the review should be set on the form
        and form.save_m2m should be set to form._save_m2m_and_review()
        """
        self._apply()

        form = ReviewForm(instance=self.user.application,
                          data=self.data,
                          request=self.request)
        form.is_valid()
        form.save(commit=False)

        self.assertIsInstance(form.review, Review)

        self.user.refresh_from_db()
        self.assertFalse(hasattr(self.user.application, "review"))

        form.save_m2m()
        self.user.refresh_from_db()
        self.assertTrue(hasattr(self.user.application, "review"))
        self.assertEqual(form.review, self.user.application.review)
Beispiel #14
0
def sample(request):
    rev_form = ReviewForm()

    if request.POST:
        rev_form = ReviewForm(request.POST)

    if rev_form.is_valid():
        form1 = rev_form.save()


    context={'form1':rev_form}

    return render(request, "forms.html", context)
Beispiel #15
0
def page(request):
    c = get_common_context(request)
    if request.POST and request.POST['action'] == 'call':
        call_form = RequestForm(request.POST)
        if call_form.is_valid():
            call_form.save()
            call_form = RequestForm()
            messages.success(request, u'Спасибо! В ближайшее время мы Вам перезвоним.')
            return HttpResponseRedirect('/')
    else:
        call_form = RequestForm()
        
    if request.POST and request.POST['action'] == 'request':
        reg_form = RegisterForm(request.POST)
        if reg_form.is_valid():
            reg_form.save()
            reg_form = RegisterForm()
            messages.success(request, u'Спасибо! Ваша заявка отправлена.')
            return HttpResponseRedirect('/')
    else:
        reg_form = RegisterForm()
        
    if request.POST and request.POST['action'] == 'review':
        review_form = ReviewForm(request.POST)
        if review_form.is_valid():
            review_form.save()
            review_form = ReviewForm()
            messages.success(request, u'Спасибо! Ваш отзыв отправлен.')
            return HttpResponseRedirect('/')
    else:
        review_form = ReviewForm()
    
    c['call_form'] = call_form
    c['reg_form'] = reg_form
    c['review_form'] = review_form
    c['photos'] = Photo.objects.all()
    c['reviews'] = Review.objects.all()
    return render_to_response('base.html', c, context_instance=RequestContext(request))
Beispiel #16
0
    def test_save_form_clears_decision_sent_date_when_changing_from_waitlisted(
            self):
        """
        If the status of the review has been changed from waitlisted to something
        else, clear the decision sent date so that they can be sent a new notification
        email. The form will pass validation if a field has changed after a decision
        has been sent only if they are waitlisted, tested above.
        """
        self._apply()
        self._review(status="Waitlisted")
        data = self.data.copy()
        data["status"] = "Accepted"

        form = ReviewForm(instance=self.user.application,
                          data=data,
                          request=self.request)
        self.assertTrue(form.is_valid())
        form.save()

        self.user.refresh_from_db()

        review = self.user.application.review
        self.assertIsNone(review.decision_sent_date)
Beispiel #17
0
def create_ticketreview(request):
    if request.method == 'GET':
        form = TicketReviewForm()
        return render(request, 'review/addticketreview.html', {'form': form})
    elif request.method == 'POST':
        data = request.POST
        ticket_form = TicketForm({
            'title': data['ticket_title'],
            'user': request.user,
            'description': data['ticket_description'],
            'image': data['ticket_image']
        })
        if ticket_form.is_valid():
            ticket = ticket_form.save()
            review_form = ReviewForm({
                'ticket': ticket,
                'rating': data['review_rating'],
                'headline': data['review_headline'],
                'body': data['review_body'],
                'user': request.user
            })
            if review_form.is_valid():
                review_form.save()
                return redirect('flux')
Beispiel #18
0
def add_review_to_portfolio(request, pk):
    portfolio = get_object_or_404(ArtistPortfolio, pk=pk)
    if request.POST:
        form = ReviewForm(request.POST)
        if form.is_valid():
            review = form.save(commit=False)
            review.portfolio = portfolio
            review.name = request.user
            review.save()

            messages.success(request, "Review created successfully ")
            url = reverse_lazy('artist:detail',
                               kwargs={'slug': portfolio.slug})
            return redirect(url)

    form = ReviewForm(initial={'portfolio': portfolio})
    return render(request, 'reviews/add_review.html', {'form': form})
Beispiel #19
0
 def post(self, request, *args, **kargs):
     form = ReviewForm(request.POST)
     if (form.is_valid()):
         review = form.save(commit=False)
         review.movie = Movie.objects.get(pk=kargs['movie_pk'])
         review.created_by = User.objects.get(id=request.user.id)
         try:
             review.save()
         except IntegrityError as e:
             old_review = Review.objects.filter(
                 movie=review.movie, created_by=review.created_by)[0]
             old_review.comment = review.comment
             old_review.rate = review.rate
             old_review.save()
         return redirect(
             "movies:movie",
             kargs['movie_pk'],
         )
Beispiel #20
0
def review_form(request, username, template_name="review/review_form.html"):
	healer = get_object_or_404(Healer, user__username__iexact=username)
	if not healer.is_review_permission(request.user):
		raise Http404

	reviewer = get_object_or_404(Client, user=request.user)
	try:
		review = Review.objects.filter(healer=healer, reviewer=reviewer)[0]
		notify = False
		title = 'Edit My Review for '
	except IndexError:
		review = None
		notify = True
		title = 'Write a Review for '
	title += str(healer.user.client)
	prev_rating = review.rating if review else None

	fb = request.GET.get('fb', False)
	if fb:
		template_name = "review/review_fb_form.html"

	form = ReviewForm(request.POST or None, instance=review)
	if form.is_valid():
		review = form.save(commit=False)
		review.healer = healer
		review.reviewer = reviewer
		review.save()
		if notify:
			review.notify()
		healer.update_rating(review.rating, prev_rating)
		if healer.review_permission == Healer.VISIBLE_EVERYONE and not is_my_client(healer.user, request.user):
			friend_process(request, 'clients', healer.user.id, 'invite')

		return redirect(reverse('review_form_success', args=[healer.user.username]) + ('?fb=1' if fb else ''))

	return render_to_response(template_name,
		{
			"title": title,
			"healer": healer,
			"form": form,
			"fb": fb
		},
		context_instance=RequestContext(request))
Beispiel #21
0
def create_review(request):
	# Create one review
	from review.forms import ReviewForm

	if request.method == 'POST':
		form = ReviewForm(request.POST)
#		if review: form = ReviewForm(request.POST, instance=review)

		if form.is_valid():
			instance = form.save()
			messages.success(request, "This review has been saved.")
			instance.user = request.user
			instance.save()
#			return HttpResponseRedirect(reverse('review.views.dashboard_view', ))
		else:
			messages.error(request, "Unable to save this review.")
	else:
		form = ReviewForm()
#		if review: form = ReviewForm(instance = review)

	movies = Movie.objects.all()
	return render_to_response('create_review.html', {'form': form, 'movies': movies}, context_instance=RequestContext(request))
Beispiel #22
0
def tour(request, slug):
    context_dict = {}

    interested = False

    if request.method == 'POST':

        people_form = PeopleForm(data=request.POST)

        if people_form.is_valid():
            people = people_form.save(commit=False)
            tour = TourDetail.objects.get(slug=slug)
            people.tourdetail = tour
            people.save()

            interested = True
    else:
        people_form = PeopleForm()

    reviewed = False

    if request.method == 'POST':
        review_form = ReviewForm(data=request.POST)
        if review_form.is_valid():
            review = review_form.save(commit=False)
            tourdetail = TourDetail.objects.get(slug=slug)

            userprofile = UserProfile.objects.get(user=request.user)

            review.tourdetail = tourdetail
            review.user = request.user
            review.user_image = userprofile.picture

            review.save()
            reviewed = True

            return redirect('tour', slug=review.tourdetail.slug)

    else:
        review_form = ReviewForm()

    try:

        tourdetail = TourDetail.objects.get(slug=slug)

        tourinclusions = TourInclusion.objects.filter(
            inclusion=tourdetail.inclusion_type)
        tourexclusions = TourExclusion.objects.filter(
            exclusion=tourdetail.exclusion_type)

        terms = TermNCondition.objects.filter(term=tourdetail.term_type)

        touritinerarys = TourItinerary.objects.filter(tourdetail=tourdetail)

        tourimages = TourImage.objects.filter(tourdetail=tourdetail)

        tourcategorys = TourCategory.objects.filter(tourdetail=tourdetail)

        importantpoints = ImportantPoint.objects.filter(tourdetail=tourdetail)

        reviews = ReviewForTours.objects.filter(tourdetail=tourdetail)

        context_dict['importantpoints'] = importantpoints

        context_dict['terms'] = terms
        blogs = Title.objects.all().order_by('-pub_date')[:5]
        context_dict['blogs'] = blogs

        context_dict['tourinclusions'] = tourinclusions
        context_dict['tourexclusions'] = tourexclusions
        context_dict['interested'] = interested
        context_dict['people_form'] = people_form

        context_dict['tourdetail'] = tourdetail

        context_dict['touritinerarys'] = touritinerarys
        context_dict['tourimages'] = tourimages
        context_dict['tourcategorys'] = tourcategorys

        context_dict['reviews'] = reviews
        context_dict['reviewed'] = reviewed
        context_dict['review_form'] = review_form

    except TourDetail.DoesNotExist:
        raise Http404("Page does not exist")

    return render(
        request,
        'tours/tour.html',
        context_dict,
    )
Beispiel #23
0
    def post(self, request, contractor_id):
        # contractor info
        contractor = Contractor.objects.get(lic_num=contractor_id)
        # contractor background image
        o_id = contractor.lic_id
        try:
            bgimage = BackgroundPhoto.objects.get(
                content_type=ContentType.objects.get(model='contractor'),
                object_id=o_id)
        except:
            bgimage = None

        bh = BondHistory.objects.filter(
            contractor_id=o_id).order_by('-bond_effective_date').first()
        wh = WorkerCompensationHistory.objects.filter(
            contractor_id=o_id).order_by('-insur_effective_date').first()

        data_source = 'California Contractors State License Board'
        try:
            if contractor_id.startswith('TX'):
                hscore = Hscore.objects.create(contractor=contractor,
                                               score=None,
                                               rank=None,
                                               max=None)
            else:
                hscore = Hscore.objects.get(contractor_id=o_id)
        except:
            hscore = Hscore.objects.create(contractor=contractor,
                                           score=None,
                                           rank=None,
                                           max=None)

        letter_grade = convert_hscore_to_rank(hscore)
        full_state_name = get_state_full_name(contractor.state)
        # Lic Type
        lic_type = contractor.lic_type.split('&')
        # review
        try:

            review = Review.objects.filter(
                content_type=ContentType.objects.get(model='contractor'),
                object_id=o_id,
                review_status='A')
        except:
            review = None
        # rating

        RATING_STAR_MAX = 10
        ratings = {}
        ratings['stars'] = range(RATING_STAR_MAX, 0, -1)
        if contractor_id.startswith('TX'):
            ratings['overall'] = 0
            ratings['rate'] = 0

        else:
            contractor_ratings = Rating.objects.filter(
                content_type=ContentType.objects.get(model='contractor'),
                object_id=o_id).order_by('ratings_average')

            # TODO:NEED TO CHANGE HERE
            ratings['overall'] = (avg_rating(review, 'Q') + avg_rating(
                review, 'E') + avg_rating(review, 'L')) / 3
            try:
                ratings['rate'] = [(item.average,
                                    round(item.average * 1.0 / RATING_STAR_MAX,
                                          2)) for item in contractor_ratings]
            except:
                pass
        try:
            project_photos = Photo.objects.filter(
                content_type=ContentType.objects.get(model='contractor'),
                object_id=o_id)
        except:
            project_photos = None
        try:
            if (contractor.lic_expire_date is not None) and (
                    contractor.lic_expire_date < datetime.date.today()):
                length = int(contractor.lic_expire_date.year -
                             contractor.lic_issue_date.year)
            elif (not contractor.lic_expire_date) and (
                    not contractor.lic_issue_date):
                length = 0
            else:
                length = int(datetime.date.today().year -
                             contractor.lic_issue_date.year)
        except:
            length = "N/A"
        # test issue, won't happen in prod

        try:
            complaint = ComplaintOverall.objects.get(contractor=contractor)
        except:
            complaint = Complaint1
            complaint.case = 0
            complaint.citation = 0
            complaint.arbitration = 0
            complaint.complaint = 0

        if request.user.is_anonymous():
            p_lic_num = None
        else:
            try:
                p_lic_num = str(request.user.professional_profiles.first().
                                professional.lic_num)
            except:
                p_lic_num = None

        # other situation
        user_rating_form = UserRatingForm()
        # review_form = request.session.get('review_form', None)
        # if review_form is None:
        if request.user.is_authenticated:
            review_form = ReviewForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'project_date': datetime.datetime.today().strftime(
                        '%Y-%m-%d')
                })
        else:
            review_form = ReviewForm(initial={
                'project_date':
                datetime.datetime.today().strftime('%Y-%m-%d')
            })

        try:
            overview = Overview.objects.get(
                content_type=ContentType.objects.get(model='contractor'),
                object_id=o_id).overview
        except:
            if contractor.license_board:
                data_source = contractor.license_board
            if contractor.csp and contractor.csp != '':
                overview = _(
                    """{lic_name} is a contractor company located in {csp} . The company holds a license number 
                according to {data_source}. According to real-time data analysis, this licensed contractor's hoome score 
                is {score} and is rated as {rank}. The License is verified as active when we checked last time. If you would
                 like to know {lic_name} more, please contact us and we will share more information and data about this
                  contractor to you.""").format(
                        lic_name=contractor.lic_name,
                        csp=contractor.csp,
                        data_source=data_source,
                        score=hscore.score,
                        rank=letter_grade,
                        full_state_name=full_state_name)
            else:
                overview = _(
                    """{lic_name} is a contractor company. The company holds a license number 
                according to {data_source}. According to real-time data analysis, this licensed contractor's hoome score 
                is {score} and is rated as {rank}. The License is verified as active when we checked last time. If you would
                 like to know {lic_name} more, please contact us and we will share more information and data about this
                  contractor to you.""").format(
                        lic_name=contractor.lic_name,
                        data_source=data_source,
                        score=hscore.score,
                        rank=letter_grade,
                        full_state_name=full_state_name)

        overview_form = OverviewForm(initial={'overview': overview})

        info_dict = {
            "contractor": contractor,
            "bg_image": bgimage,
            "overview": overview,
            'review': review,
            "score": hscore.score,
            'bond_history': bh,
            "wc_history": wh,
            "lic_type": lic_type,
            "ratings": ratings,
            'project_photos': project_photos,
            'review_form': review_form,
            "user_rating_form": user_rating_form,
            "complaint": complaint,
            "length": length,
            'p_lic_num': p_lic_num,
            'rank': letter_grade,
            'overview_form': overview_form
        }

        if request.POST.get('review'):
            user_rating_form = UserRatingForm(request.POST)
            review_form = ReviewForm(request.POST)
            # TODO: assign a random password
            # TODO: validator doesn't work
            if review_form.is_valid() and user_rating_form.is_valid():
                # User = #ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)

                # user = User(email=review_form.cleaned_data['email'],
                #             username=review_form.cleaned_data['email'],
                #             last_name=review_form.cleaned_data['last_name'],
                #             first_name=review_form.cleaned_data['first_name'],
                #             password=make_password("aaaaaaa"))
                # user.save()
                model_type = check_professional_type(request)
                review = review_form.save(commit=False)
                if request.user.is_authenticated():
                    review.user = request.user
                review.content_type = ContentType.objects.get(model=model_type)
                review.object_id = contractor.lic_id
                review.save()

                for field in user_rating_form.cleaned_data:
                    user_rating = UserRating(
                        review=review,
                        rating_type=field[0].upper(),
                        rating_score=int(user_rating_form.cleaned_data[field]))
                    user_rating.save()
                # direct to the page to upload photos
                # TODO: ADD PHOTOFORM VALIDATION FOR SECURITY
                content_type = ContentType.objects.get(model='review')
                object_id = int(review.id)
                files = request.FILES.getlist('project photos')
                if len(files) > 0:
                    for f in files:
                        instance = Photo.objects.create(
                            img=f,
                            title=f.name,
                            content_type=content_type,
                            object_id=object_id)
                        instance.save()
                else:
                    pass
                # request.session.pop('review_form', None)
                # TODO: redirect the sucess url and add bootstrap messages: success
                return redirect(request.path)
            else:
                # request.session.update({'review_form': review_form.data})
                info_dict['review_form'] = review_form
                info_dict["user_rating_form"] = user_rating_form
                messages.warning(
                    request,
                    _('Submit Failed. Please verify your content is correct.'))
                return render(request, 'contractor/contractor.html',
                              {"info_dict": info_dict})
        # TODO: need to change here
        elif request.POST.get('overview'):
            edit_overview(request, contractor_id)
            return redirect(request.path)
        else:
            raise Http404(_("Error Pages!"))
Beispiel #24
0
def service(request, service_id):
    categories = Category.objects.all().order_by('updated_at')
    try:
        service = Service.objects.get(pk=service_id)
    except:
        raise Http404
    if request.method == 'POST':
        message_form = MessageForm(request.POST)
        if message_form.is_valid():
            message = message_form.save(commit=False)
            message.sender = request.user
            message.service = service
            message.recipient = message.service.author
            message.content = message_form.cleaned_data.get("content")
            message.save()
            messages.success(request, '메시지를 성공적으로 전송했습니다.')
    message_form = MessageForm()
    service_author = User.objects.filter(service=service)
    category = Category.objects.filter(name=service.title)
    add_to_cart = AddServiceForm(initial={'quantity': 1})
    if request.method == "POST":
        review_form = ReviewForm(request.POST, request.FILES)
        if review_form.is_valid():
            temp_form = review_form.save(commit=False)
            temp_form.author = request.user
            temp_form.service_obj = service
            review_form.save()
            messages.success(request, '리뷰를 등록하였습니다.')
    review_form = ReviewForm()
    review = Review.objects.filter(service_obj=service)
    # 비슷한 서비스 (같은 카테고리 내 최신게시물 4개)
    c_ser = Service.objects.filter(
        category=service.category).order_by('-updated_at')
    paginator = Paginator(c_ser, 4)
    page = request.GET.get('page')
    c_ser = paginator.get_page(page)
    services = Service.objects.all().annotate(
        average_rating=Avg('review__rating'))
    if request.method == 'POST':
        login_form = AuthenticationForm(request=request, data=request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return render(
                    request, 'service.html', {
                        'c_ser': c_ser,
                        'services': services,
                        'review': review,
                        'review_form': review_form,
                        'service': service,
                        'message_form': message_form,
                        'add_to_cart': add_to_cart,
                        'categories': categories,
                        'category': category,
                        'login_form': login_form,
                        'service_author': service_author
                    })
    login_form = AuthenticationForm()
    return render(
        request, 'service.html', {
            'c_ser': c_ser,
            'services': services,
            'review': review,
            'review_form': review_form,
            'service': service,
            'message_form': message_form,
            'add_to_cart': add_to_cart,
            'categories': categories,
            'category': category,
            'login_form': login_form,
            'service_author': service_author
        })
Beispiel #25
0
    def post(self, request, o_id):
        template_name = 'meister/meister.html'
        meister = Meister.objects.get(lic_num=o_id)
        try:
            bgimage = BackgroundPhoto.objects.get(
                content_type=ContentType.objects.get(model='meister'),
                object_id=o_id)
        except BackgroundPhoto.DoesNotExist:
            bgimage = None
        #data_source = 'California Contractors State License Board'

        try:
            review = Review.objects.filter(
                content_type=ContentType.objects.get(model='meister'),
                object_id=o_id,
                review_status='A')
        except:
            review = None
        # rating
        RATING_STAR_MAX = 10
        meister_ratings = Rating.objects.filter(
            content_type=ContentType.objects.get(model='meister'),
            object_id=o_id).order_by('ratings_average')
        ratings = {}
        ratings['stars'] = range(RATING_STAR_MAX, 0, -1)
        # TODO:NEED TO CHANGE HERE
        ratings['overall'] = (avg_rating(review, 'Q') + avg_rating(
            review, 'E') + avg_rating(review, 'L')) / 3
        try:
            ratings['rate'] = [(item.average,
                                round(item.average * 1.0 / RATING_STAR_MAX, 2))
                               for item in meister_ratings]
        except:
            pass
        project_photos = Photo.objects.filter(
            content_type=ContentType.objects.get(model='meister'),
            object_id=o_id)
        if request.user.is_anonymous():
            p_lic_num = None
        else:
            try:
                p_lic_num = str(request.user.professional_profiles.first().
                                professional.lic_num)
            except:
                p_lic_num = -1

        # other situation
        user_rating_form = UserRatingForm()
        if request.user.is_authenticated:
            review_form = ReviewForm(
                initial={
                    'first_name': request.user.first_name,
                    'last_name': request.user.last_name,
                    'project_date': datetime.datetime.today().strftime(
                        '%Y-%m-%d')
                })
        else:
            review_form = ReviewForm(initial={
                'project_date':
                datetime.datetime.today().strftime('%Y-%m-%d')
            })
        try:
            overview = Overview.objects.get(
                content_type=ContentType.objects.get(model='meister'),
                object_id=o_id).overview
        except Overview.DoesNotExist:
            overview = _(
                """{lic_name} is a professional located in {full_state_name}. The professional is verified as 
            active when we checked last time. If you would like to know {lic_name} more, please contact us and we will 
            share more information and data about this meister to you."""
            ).format(lic_name=meister.lic_name,
                     full_state_name=get_state_full_name(meister.state))
        overview_form = OverviewForm(initial={'overview': overview})
        info_dict = {
            "meister": meister,
            "bg_image": bgimage,
            "overview": overview,
            'review': review,
            "ratings": ratings,
            'project_photos': project_photos,
            'review_form': review_form,
            "user_rating_form": user_rating_form,
            'p_lic_num': p_lic_num,
            'overview_form': overview_form
        }

        if request.POST.get('review'):
            user_rating_form = UserRatingForm(request.POST)
            review_form = ReviewForm(request.POST)
            # TODO: assign a random password
            # TODO: validator doesn't work
            if review_form.is_valid() and user_rating_form.is_valid():
                model_type = check_professional_type(request)
                review = review_form.save(commit=False)
                if request.user.is_authenticated():
                    review.user = request.user
                review.content_type = ContentType.objects.get(model=model_type)
                review.object_id = o_id
                review.save()

                for field in user_rating_form.cleaned_data:
                    user_rating = UserRating(
                        review=review,
                        rating_type=field[0].upper(),
                        rating_score=int(user_rating_form.cleaned_data[field]))
                    user_rating.save()
                # direct to the page to upload photos
                # TODO: ADD PHOTOFORM VALIDATION FOR SECURITY
                content_type = ContentType.objects.get(model='review')
                object_id = int(review.id)
                files = request.FILES.getlist('project photos')
                if len(files) > 0:
                    for f in files:
                        instance = Photo.objects.create(
                            img=f,
                            title=f.name,
                            content_type=content_type,
                            object_id=object_id)
                        instance.save()
                else:
                    pass
                # request.session.pop('review_form', None)
                # TODO: redirect the sucess url and add bootstrap messages: success
                return redirect(request.path)
            else:
                # request.session.update({'review_form': review_form.data})
                info_dict['review_form'] = review_form
                info_dict["user_rating_form"] = user_rating_form
                messages.warning(
                    request,
                    _('Submit Failed. Please verify your content is correct.'))
                return render(request, template_name, {"info_dict": info_dict})
        elif request.POST.get('overview'):
            edit_overview(request, o_id)
            return redirect(request.path)
        else:
            raise Http404(_("Error Pages!"))
Beispiel #26
0
def review_detail(request, pk):
    proposals = Proposal.objects.select_related("result")
    proposal = get_object_or_404(proposals, pk=pk)
    
    admin = request.user.groups.filter(name="reviewers-admins").exists()
    speakers = [s.user for s in proposal.speakers()]
    
    if proposal.session_type == Proposal.SESSION_TYPE_TUTORIAL:
        if not request.user.groups.filter(name="reviewers-tutorials").exists():
            return access_not_permitted(request)
    else:
        if not request.user.groups.filter(name="reviewers").exists():
            return access_not_permitted(request)
    
    if not admin and request.user in speakers:
        return access_not_permitted(request)
    
    try:
        latest_vote = LatestVote.objects.get(proposal=proposal, user=request.user)
    except LatestVote.DoesNotExist:
        latest_vote = None
    
    if request.method == "POST":
        if request.user in speakers:
            return access_not_permitted(request)
        if proposal.invited:
            return access_not_permitted(request)
        
        if "vote_submit" in request.POST:
            review_form = ReviewForm(request.POST)
            if review_form.is_valid():
                
                review = review_form.save(commit=False)
                review.user = request.user
                review.proposal = proposal
                review.save()
                
                return redirect(request.path)
            else:
                message_form = SpeakerCommentForm()
        elif "message_submit" in request.POST:
            message_form = SpeakerCommentForm(request.POST)
            if message_form.is_valid():
                
                message = message_form.save(commit=False)
                message.user = request.user
                message.proposal = proposal
                message.save()
                
                for speaker in speakers:
                    if speaker and speaker.email:
                        ctx = {
                            "proposal": proposal,
                            "message": message,
                            "reviewer": False,
                        }
                        send_email(
                            [speaker.email], "proposal_new_message",
                            context = ctx
                        )
                
                return redirect(request.path)
        elif "result_submit" in request.POST:
            if admin:
                result = request.POST["result_submit"]
                
                if result == "accept":
                    proposal.result.accepted = True
                    proposal.result.save()
                elif result == "reject":
                    proposal.result.accepted = False
                    proposal.result.save()
                elif result == "undecide":
                    proposal.result.accepted = None
                    proposal.result.save()
            
            return redirect(request.path)
    else:
        initial = {}
        if latest_vote:
            initial["vote"] = latest_vote.vote
        review_form = ReviewForm(initial=initial)
        message_form = SpeakerCommentForm()
    
    proposal.comment_count = proposal.result.comment_count
    proposal.total_votes = proposal.result.vote_count
    proposal.plus_one = proposal.result.plus_one
    proposal.plus_zero = proposal.result.plus_zero
    proposal.minus_zero = proposal.result.minus_zero
    proposal.minus_one = proposal.result.minus_one
    
    reviews = Review.objects.filter(proposal=proposal).order_by("-submitted_at")
    
    return render_to_response("reviews/review_detail.html", {
        "proposal": proposal,
        "latest_vote": latest_vote,
        "reviews": reviews,
        "review_form": review_form,
        "message_form": message_form
    }, context_instance=RequestContext(request))