为什么这个Django表单返回unicode?

时间:2014-05-30 23:40:39

标签: python django unicode

我有一个Django模型表单,我用它来允许用户更新他们之前上传到网站的套牌。但是,出于某种原因,清理后的数据将以unicode的形式返回。因此,如果他们进入" Deck Foo"作为名称,它将作为(u'Deck Foo',)记录在数据库中。我在我的网站上可能有10个其他的模型表单,它们都按预期完美地工作,我看不出它们和它之间的单一区别。为什么这些被保存为unicode而不是常规字符串?

forms.py

class DeckForm(forms.ModelForm):
    class Meta:
        model = Deck
        fields = ['name', 
                  'format', 
                  'type',
                  'packs',
                  'deck_list',
                  'is_active']

    def clean(self):
        if self.cleaned_data['type'] == 'COMMANDER' and self.cleaned_data['format'] != 'VINTAGE':
            raise forms.ValidationError('Commander is only played in vintage format.')
        return self.cleaned_data

views.py

def deck_detail(request,
                deck_slug, 
                template_name="deck/deck_detail.html"
                ):

    deck = Deck.objects.get(slug=deck_slug)

    if request.method == 'POST':
        form = DeckForm(request.POST, instance=deck)
        if form.is_valid():
            name = form.cleaned_data['name']
            format = form.cleaned_data['format']
            type = form.cleaned_data['type']
            packs = form.cleaned_data['packs']
            deck_list = form.cleaned_data['deck_list']
            is_active = form.cleaned_data['is_active']

            deck.name = name,
            deck.slug = slugify(name),
            deck.format = format,
            deck.type = type,
            deck.packs = packs,
            deck.deck_list = deck_list,
            deck.is_active = is_active

            deck.save()
            return HttpResponseRedirect('/deck/'+deck.slug)
    else:
        form = DeckForm(instance=deck)

HTML

<form action="/deck/{{deck.slug}}/" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit Deck" />
</form>

1 个答案:

答案 0 :(得分:4)

您正在将deck.name变成元组。

deck.name = name,

您的示例表明您的问题实际上并不是unicode问题。而是将元组插入到数据库中而不是简单的unicode字符串。试试这个:

deck.name = name  # no comma

(u'Deck Foo',)(在您的数据库中)是具有单个unicode元素的元组的字符串表示形式。 unicode字符串看起来像这样:

u'Deck Foo'

但是您的数据库只是将字符串写入数据库而不使用引号或前缀u