Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error on uploading image in django: "coercing to Unicode: need string or buffer, tuple found"

Trying to work with ImageField in django. Here are my models

class Album(models.Model):
    title = models.CharField(max_length=100)

    def __unicode__(self):
        return self.title

class Photo(models.Model):
    image = models.ImageField(upload_to='photos/')
    album = models.ForeignKey(Album)
    title = models.CharField(max_length=100, default="")

    def __unicode__(self):
        return self.title

class PhotoModelForm(forms.ModelForm):
    class Meta:
        model = Photo

Here is a part of urls.py

...
url(r'^trial/upload/$', 'trial.views.upload'),
...

views.py

def upload(request):
    if request.method == 'POST':
        form = PhotoModelForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save()
            return render_to_response('trial/thanks_upload.html',{
                'photo': photo
            }, context_instance = RequestContext(request))
    else:
        form = PhotoModelForm()
    return render_to_response('trial/upload.html', {
      'form': form
    }, context_instance = RequestContext(request))

upload.html

<form enctype="multipart/form-data" action="/trial/upload/" method="post">
    {% csrf_token %}
    {% for field in form %}
        <div class="fieldWrapper">
            {{ field.errors }}
            {{ field.label_tag }}: {{ field }}
        </div>
    {% endfor %}
    <p><input type="submit" value="Upload" /></p>
</form>

But on saving I have next error: TypeError at /trial/upload/ coercing to Unicode: need string or buffer, tuple found

Errors appears on photo.save

Does anybody has ideas why could it be? Why tuple appears at all? I'm sure there is a stupid bug...

like image 239
megido Avatar asked Dec 10 '25 09:12

megido


1 Answers

I've got it myself. In settings.py there is MEDIA_ROOT setting, which was

MEDIA_ROOT = 'd:/dev/python/scripts/app/media/',

Python makes the object tuple because of the comma at the end. That's why it couldn't save the object. Watch your commas next time!

like image 119
megido Avatar answered Dec 12 '25 22:12

megido



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!