fildred13
fildred13

Reputation: 2350

Why is this Django form returning unicode?

I have a Django Model Form which I'm using to allow users to update decks they have previously uploaded to the site. For some reason, though, the cleaned data is coming back as unicode. So, for instace, if they enter "Deck Foo" as the name, it gets recorded in the database as (u'Deck Foo',). I have probably 10 other Model Forms across my site and they all work perfectly as expected and I cannot see a single difference between them and this. Why are these being saved as unicode instead of regular strings?

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>

Upvotes: 0

Views: 1106

Answers (1)

Justin O Barber
Justin O Barber

Reputation: 11601

You are turning deck.name into a tuple here.

deck.name = name,

Your example suggests that your problem is not actually a unicode problem. Rather, a tuple is being inserted into your database instead of a simple unicode string. Try this instead:

deck.name = name  # no comma

(u'Deck Foo',) (in your database) is a string representation of a tuple with a single unicode element. A unicode string would look like this:

u'Deck Foo'

But your database will simply write the string to the database without the quotation marks or prefixed u.

Upvotes: 6

Related Questions