Skip to content

Commit

Permalink
forms: Use forms on reviews
Browse files Browse the repository at this point in the history
  • Loading branch information
pta2002 committed May 21, 2017
1 parent 4e7372e commit f5f7cae
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 48 deletions.
33 changes: 32 additions & 1 deletion shop/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from django.contrib.auth.models import User
from django.core.validators import validate_email, validate_slug, MinLengthValidator
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from crispy_forms.layout import Submit, Layout, Div

class RegisterForm(forms.Form):
username = forms.CharField(label='Username', max_length=150,
Expand Down Expand Up @@ -32,3 +32,34 @@ def __init__(self, *args, **kwargs):
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'


class ReviewForm(forms.Form):
title = forms.CharField(label='Title', max_length=150, required=False)
rating = forms.FloatField(label='Rating',
widget=forms.NumberInput(attrs={'min': 1, 'max': 5, 'step': 1}),
required=True)
review = forms.CharField(label='Review',
widget=forms.Textarea(attrs={'class': 'vresize'}),
required=True)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'modal-body'
self.helper.layout = Layout(
Div(
'title',
'rating',
'review',
css_class='modal-body'
),
Div(
Submit('submit', 'Post Review'),
css_class='modal-footer'
)
)


def clean_rating(self):
data = self.cleaned_data
return int(data['rating'])
23 changes: 2 additions & 21 deletions shop/templates/shop/product.html
Original file line number Diff line number Diff line change
Expand Up @@ -148,27 +148,8 @@ <h4>{% if review.title %}{{ review.title }} - {% endif %}{{ review.rating }}/5</
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title" id="review-label">{% if reviewed %}Edit your{% else %}Write a{% endif %} review</h4>
</div>
<form class="" action="{% url 'shop:viewproduct' product.id %}" method="post">
<div class="modal-body">
{% csrf_token %}
<div class="form-group">
<label class="control-label" for="review-title">Review title (optional)</label>
<input type="text" class="form-control" id="review-title" name="title" value="{% if reviewed %}{{ reviewed.title }}{% endif %}">
</div>
<div class="form-group">
<label class="control-label" for="review-rating">Rating (1 to 5)</label>
<input type="number" min="1" max="5" step="1" class="form-control" id="review-rating" name="rating" value="{% if reviewed %}{{ reviewed.rating }}{% endif %}">
</div>
<div class="form-group">
<label class="control-label" for="review-itself">Review</label>
<textarea type="text" class="form-control vresize" id="review-itself" name="review">{% if reviewed %}{{ reviewed.review }}{% endif %}</textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary">{% if reviewed %}Update{% else %}Post{% endif %} review</button>
</div>
</form>
{% load crispy_forms_tags %}
{% crispy form %}
</div>
</div>
</div>
Expand Down
35 changes: 9 additions & 26 deletions shop/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,42 +32,24 @@ def view_product(request, id):


if request.method == 'POST':
errors = []

form = ReviewForm(request.POST)
if not request.user.is_authenticated():
return redirect(reverse('shop:login') + '?next=%s' % request.path)

if not product.is_owned_by(request.user):
errors.append("You don't own this product!")

if 'rating' not in request.POST:
errors.append('Rating is a required field')

if len(request.POST.get('review', '').strip()) == 0:
errors.append('Review is a required field')

if len(request.POST.get('title', '')) > 150:
errors.append('Title must be at most 150 characters')

try:
if not 0 < int(request.POST.get('rating')) <= 5:
errors.append('Rating must be between 1 and 5')
except ValueError:
errors.append('Invalid rating')

if not errors:
messages.warning(request, "You don't own this product.")
elif form.is_valid():
try:
review = product.review_set.get(user=request.user)
except ObjectDoesNotExist:
review = Review(product=product, user=request.user)

review.title = request.POST.get('title', '')
review.review = request.POST.get('review').strip()
review.rating = request.POST.get('rating')
review.title = form.cleaned_data['title']
review.review = form.cleaned_data['review']
review.rating = form.cleaned_data['rating']
review.save()

for error in errors:
messages.warning(request, error)
else:
form = ReviewForm()

reviews = sorted(product.review_set.all(), key=lambda t: -t.get_ordering())
for review in reviews:
Expand All @@ -84,6 +66,7 @@ def view_product(request, id):

context = {
'reviews': reviews,
'form': form,
'product': product,
'incart': cart.in_cart(product),
'can_buy': request.user.userextra.can_purchase_item(product),
Expand Down

0 comments on commit f5f7cae

Please sign in to comment.