【发布时间】:2018-08-04 07:30:54
【问题描述】:
我正在尝试通过 html 表单编辑 django 数据库。但是我不确定为什么会出现以下错误。产品类别是外键,我无法更改它的值。我该如何解决这个错误?谢谢。
ValueError 在 /shop/polyester-cushions/eiffel/edit_product/ 不能 分配“'Polyester Cushions'”:“Product.category”必须是“Category” 实例。
models.py
from django.db import models
from django.urls import reverse
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='category', blank=True)
def __str__(self):
return '{}'.format(self.name)
class Product(models.Model):
CATEGORY_CHOICES = (
("Cotton Cushions", "Cotton Cushions"),
("Polyester Cushions", "Polyester Cushions")
)
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, choices=CATEGORY_CHOICES)
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return '{}'.format(self.name)
edit_product.html
<div class="form-group row">
<label class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-10">
<select name="category" class="form-control" value="{{ product.category }}">
<option {% if product.category == "Cotton Cushions" %} selected {% endif %} value="Cotton Cushions">Cotton Cushions</option>
<option {% if product.category == "Polyester Cushions" %} selected {% endif %} value="Polyester Cushions">Polyester Cushions</option>
</select>
</div>
</div>
views.py
@login_required(login_url="/")
def EditProduct(request, c_slug, product_slug):
try:
product = Product.objects.get(category__slug=c_slug, slug=product_slug)
error = ''
if request.method == 'POST':
product_form = ProductForm(request.POST, request.FILES, instance=product)
if product_form.is_valid():
product.save()
return redirect('shop/my_products.html/')
else:
error = "Data is not valid"
return render(request, 'shop/edit_product.html', {'product':product, 'error':error})
except Product.DoesNotExist:
return redirect('/')
forms.py
from django import forms
from django.forms import ModelForm
from .models import Product
class ProductForm(ModelForm):
class Meta:
model = Product
fields = ('name','slug','description','category','price','image','stock','available')
【问题讨论】:
-
该选项中的值是一个字符串,您基本上是在尝试将字符串插入 ForeignKey 字段。尝试将值设置为 ID 并从视图中的 ID 获取模型。
-
添加您的views.py以及表单类代码(如果有问题)
-
维吉:谢谢。我明白你现在的意思了。 Satendra:我已经加进去了。
标签: python html django templates