本文介绍了只能将元组(不是"unicode")连接到元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Django 1.5.4

我是Django的新手,我尝试显示通过管理面板上传的图片,但不幸的是,图片源代码中的url字段为,如果我更改了 {{article.image.url}} 更改为 {{article.image}} ,图片网址显示为

I am a newbie in Django and i tried to display the image uploaded via admin panel, but unfortunately the url field in the source code for the image is Empty and if i change {{ article.image.url }} to {{ article.image }}, the image url shows up as

<img src="media/abyss.jpg" alt="" height="450"/>

当我单击图像的链接时,显示为

and when i click the link for image, it says

TypeError at /media/abyss.jpg
can only concatenate tuple (not "unicode") to tuple

请帮助我.

Settings.py文件

Settings.py File

 MEDIA_ROOT = (os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/'),)
 MEDIA_URL = '/media/'

Models.py文件

Models.py File

class Article(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255)
    description = models.TextField()
    content = models.TextField()
    published = models.BooleanField(default=True)
    image = models.ImageField(upload_to='media', blank=True)
    created = models.DateTimeField(auto_now_add=True)


   def __unicode__(self):
       return u'%s' % self.title

   class Meta:
      ordering = ['-created']

   def get_absolute_url(self):
      return reverse('blog.views.article', args=[self.slug])

Urls.py

urlpatterns = patterns('',
                       url(r'^admin/', include(admin.site.urls)),
                       url(r'^$', 'blog.views.index'),
                       url(r'^blog/(?P<slug>[\w\-]+)/$', 'blog.views.article'),
                       url(r'^(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),
                       )

index.html

index.html

{% extends "blog/base.html" %}

{% block content %}
    <h1>PyStack</h1>

    <div>
        {% for article in articles %}
            <img src="{{ article.image.url }}" alt="" height="450"/>
            <h2><a href="{{ article.get_absolute_url }}">{{ article.title|capfirst }}</a></h2>
            <p>{{ article.description }}</p>
            <hr/>
        {% endfor %}
    </div>

{% endblock %}

推荐答案

MEDIA_ROOT 应该是字符串而不是元组:

MEDIA_ROOT should be string not tuple:

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), '..', 'media').replace('\\','/')

尾随逗号使其成为一个元组:

Trailing comma makes it a tuple:

>>> x = (1,)
>>> type(x)
<type 'tuple'>
>>> x + u'foo'
Traceback (most recent call last):
    x + u'foo'
TypeError: can only concatenate tuple (not "unicode") to tuple

这篇关于只能将元组(不是"unicode")连接到元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:41