Am wondering how i can get this html code into a forms.py in my ReviewForm as widgets.
This code: 'rating': forms.Select(attrs={'class': 'form-control',}),
Should be as the html code under with 1-5. And also be saved in models so the rating still gets saved when edited.
So basicly allow the forms.py when you edit it to render a dropdown with 1-5 atm its just a dropdown with no numbers cant figure out how to get numbers in the dropdown with the widget.
<div>
<label>Rating</label><br>
<select class="form-control" name="rating">
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected>3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
forms.py
class ReviewForm(forms.ModelForm):
class Meta:
model = Review
fields = ('content', 'rating')
widgets = {
'content': forms.Textarea(attrs={'class': 'form-control'}),
'rating': forms.Select(attrs={'class': 'form-control',}),
}
Models.py
class Product(models.Model):
category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL)
sku = models.CharField(max_length=254, null=True, blank=True)
name = models.CharField(max_length=254)
description = models.TextField()
has_sizes = models.BooleanField(default=False, null=True, blank=True)
price = models.DecimalField(max_digits=6, decimal_places=2)
rating = models.DecimalField(max_digits=6, decimal_places=2, null=True, blank=True)
image_url = models.URLField(max_length=1024, null=True, blank=True)
image = models.ImageField(null=True, blank=True)
def __str__(self):
return self.name
def get_rating(self):
reviews_total = 0
for review in self.reviews.all():
reviews_total += review.rating
if reviews_total > 0:
return reviews_total / self.reviews.count()
return 0
class Review(models.Model):
product = models.ForeignKey(Product, related_name='reviews', on_delete=models.CASCADE)
rating = models.IntegerField(default=3)
content = models.TextField()
created_by = models.ForeignKey(User, related_name='reviews', on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.created_by)