如何在Django数据库中保存用户等级?

时间:2019-05-09 19:06:44

标签: django django-models django-forms django-templates django-views

这是我在Django中的第一个项目。我试图将评级保存在Django数据库中,但是当我单击单选按钮时,该值未存储在数据库中。我曾尝试过先前上传的Stack Overflow解决方案,但没有一个能帮助我解决问题。我首先是在 forms.py 中使用 RadioSelect ,但仍然遇到相同的问题。

代码如下:

Model.py

class Product(models.Model):
    title = models.CharField(max_length=120)
    brand = models.CharField(max_length=120,default="None")
    model = models.CharField(max_length=120,default="None")
    slug = models.SlugField(blank=True, unique=True)
    category = models.CharField(max_length=120 , default="Phone")
    price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99)

class Rating(models.Model):
    product=models.ForeignKey(Product,default=None, on_delete=models.PROTECT)
    user=models.ForeignKey(User,default=None, on_delete=models.PROTECT)
    rating = models.CharField(max_length=120)

Views.py

def add_rating(request,id):
    product = get_object_or_404(Product, pk=id)
    pro = Product.objects.get(id=id)
    if request.method == "POST":
        form = RatingForm(request.POST)
        if form.is_valid():
            product = form.cleaned_data['product']
            user = form.cleaned_data['user']
            rating = form.cleaned_data['rating']

            product = request.POST.get('product', ''),
            user = request.POST.get('user', ''),
            rating = request.POST.get('rating', ''),

            obj = Rating(product=product, user=user, rating=rating)
            obj.save()
            context = {'obj': obj}
            return render(request, 'product/detail.html',context)
        else:
           form=RatingForm()
        return HttpResponse('Please rate the product')

Forms.py

from django import forms
from .models import Rating

class RatingForm(forms.ModelForm):

   class Meta:
      model = Rating
      fields = ('product', 'user','rating')

template.py

<form method="POST" action="{% url 'add_rating' product.id %}">{%    csrf_token %}
<ul class="rate-area" style="display:inline;position:absolute">
<input type="radio" id="5-star" name="rating" value="5" /><label for="5-   star" title="Amazing">5 stars</label>
<input type="radio" id="4-star" name="rating" value="4" /><label for="4-star" title="Good">4 stars</label>
<input type="radio" id="3-star" name="rating" value="3" /><label for="3-star" title="Average">3 stars</label>
<input type="radio" id="2-star" name="rating" value="2" /><label for="2-star" title="Not Good">2 stars</label>
<input type="radio" id="1-star" name="rating" value="1" /><label for="1-star" title="Bad">1 star</label>
<button type="submit" value="Rate">Rate</button>

</ul>

</form>

1 个答案:

答案 0 :(得分:0)

您应该在模型上使用“ CharField”,而应该使用“ ChoiceField”,那么ChoiceField将成为下拉选择。

使用通用编辑视图也将更容易; https://docs.djangoproject.com/en/2.2/ref/class-based-views/generic-editing/