ValueError - 无法分配

时间:2011-11-07 08:10:19

标签: django

请为我提供类似下面的表单和模型类,但每次尝试将数据发送到数据库时都会出现此错误:

  

/ activity / add / product /中的ValueError无法分配“u'Cameras'”:   “user_products.category”必须是“类别”实例。

请有帮助我解决这个问题的大师。感谢。

形式

class headersearch(forms.Form):
    kywords = forms.CharField(max_length = 100, error_messages = {'required': 'Please type a keyword to search'})
    catgory = forms.ChoiceField(widget=forms.Select, choices=CATEGORY_CHOICES)

    def __init__(self, *args, **kwargs):
        super(headersearch, self).__init__(*args, **kwargs)
        self.fields['catgory'].choices = header_search()

class advancedsearch(forms.Form):
    kywords = forms.CharField(max_length = 100)
    catgory = forms.ChoiceField(widget=forms.Select, choices=CATEGORY_CHOICES)
    priceRangeFrom = forms.IntegerField()
    priceRangeTo = forms.IntegerField()
    state = forms.ChoiceField(widget=forms.Select, choices=STATE_CHOICES)

    def __init__(self, *args, **kwargs):
        super(advancedsearch, self).__init__(*args, **kwargs)
        self.fields['catgory'].choices = header_search()

class additem(forms.Form):
    productName = forms.CharField(max_length = 100)
    category = forms.ChoiceField(widget=forms.Select, choices = ADD_CATEGORY_CHOICES)
    priceFrom = forms.IntegerField()
    productState = forms.ChoiceField(widget=forms.Select, choices=STATE_CHOICES)
    description = forms.CharField(widget=forms.Textarea, max_length = 200)
    tags = forms.CharField(max_length = 100)
    image = forms.CharField(max_length = 100, required = False)
    dateAdded = forms.CharField(widget=forms.HiddenInput, initial = datetime.datetime.today)

    def __init__(self, *args, **kwargs):
        super(additem, self).__init__(*args, **kwargs)
        self.fields['category'].choices = add_product()

模型

class grp_categorie(models.Model):
    category = models.CharField(max_length = 100, unique = True)
    visibleOnNavi = models.BooleanField()
    type = models.CharField(max_length = 100, choices=TYPE_CHOICES)

    def __unicode__(self):
        return "%s" %(self.category)


class categories(models.Model):
    category = models.ForeignKey(grp_categorie)
    member = models.CharField(max_length = 100)
    values = models.CharField(max_length = 200)

    def __unicode__(self):
        return "%s" %(self.values)


class user_products(models.Model):
    productName = models.CharField(max_length = 100)
    category = models.ForeignKey(categories)
    priceFrom = models.IntegerField()
    productState = models.CharField(max_length = 100, choices=STATE_CHOICES)
    description = models.CharField(max_length = 200)
    tags = models.CharField(max_length = 100)
    image = models.FileField(upload_to="images/%Y/%m/%d", blank = True, null = True)
    dateAdded = models.DateTimeField()

    def __unicode__(self):
        return "%s %s %s %s %s %s %s %s" %(self.productName, self.category, self.priceFrom, self.productState, self.description, self.tags, self.image, self.dateAdded)

这是处理表单

的视图
def add_product(request):
    if request.method == "POST":
        formadd = additem(request.POST)
        if formadd.is_valid():
            cd = formadd.cleaned_data
            p = user_products(
                productName = cd['productName'],
                category = cd['category'],
                priceFrom = cd['priceFrom'],
                productState = cd['productState'],
                description = cd['description'],
                tags = cd['tags'],
                image = cd['image'],
                dateAdded = cd['dateAdded']
            )

            p.save()
            request.session['product'] = cd['productName']
            return HttpResponseRedirect('/activity/add/product/done/')
    else:
        formadd = additem()
    return render_to_response('activity/add_item.html', { "formadd" : formadd }, context_instance = RequestContext(request, processors=[navi]))

这是错误页面

的snapshop

error page

每次提交表单时都会出现错误。

回溯

  

环境:

     

请求方法:POST请求URL:   http://localhost:8000/activity/add/product/

     

Django版本:1.3.1 Python版本:2.7.2已安装的应用程序:   ['django.contrib.auth','django.contrib.contenttypes',   'django.contrib.sessions','django.contrib.sites',   'django.contrib.messages','django.contrib.staticfiles',   'django.contrib.admin','django.contrib.admindocs','south',   'mystore.store']已安装的中间件:   ( 'django.middleware.common.CommonMiddleware',   'django.contrib.sessions.middleware.SessionMiddleware',   'django.middleware.csrf.CsrfViewMiddleware',   'django.middleware.csrf.CsrfResponseMiddleware',   'django.contrib.auth.middleware.AuthenticationMiddleware',   'django.contrib.messages.middleware.MessageMiddleware')

     

回溯:文件   在“C:\ Python27 \ lib \ site-packages \ django \ core \ handlers \ base.py”中   get_response     111. response = callback(request,* callback_args,** callback_kwargs)add_product中的文件“C:\ django_sites \ www \ mystore .. \ mystore \ store \ views.py”     81. dateAdded = cd ['dateAdded'] init 中的文件“C:\ Python27 \ lib \ site-packages \ django \ db \ models \ base.py”     352. setattr(self,field.name,rel_obj)文件“C:\ Python27 \ lib \ site-packages \ django \ db \ models \ fields \ related.py”in   设置     331. self.field.name,self.field.rel.to._meta.object_name))

     

异常类型:/ activity / add / product / Exception值的ValueError:   无法分配“u'Cameras”:“user_products.category”必须是a   “类别”实例。

1 个答案:

答案 0 :(得分:2)

您没有显示此错误发生的位置(回溯中的代码),但在您从表单创建模型的某个地方,这绝对是一个问题。

  

/ activity / add / product /中的ValueError无法分配“u'Cameras'”:“user_products.category”必须是“类别”实例。

正如所说,设置user_products.category时,您必须将categories实例传递给它,而不是字符串Cameras

user_products = user_products()
user_products.category = 'Cameras' # will cause ValueError on FK field

如果您正在处理表单POST数据,则必须从字符串“Camera”中提取相关对象。它应该更像是......

user_products.category = categories.objects.get(grp_categorie__category='Camera')
# replace with a method to actually get your categories instance.