【问题标题】:can only concatenate tuple (not "unicode") to tuple只能将元组(不是“unicode”)连接到元组
【发布时间】:2013-10-04 20:44:04
【问题描述】:

我正在使用 Django 1.5.4

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

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

当我点击图片链接时,它说

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

请帮帮我。

Settings.py 文件

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

Models.py 文件

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])

网址.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

{% 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 %}

【问题讨论】:

    标签: python django unicode


    【解决方案1】:

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

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

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

    >>> 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
    

    【讨论】:

    • 谢谢,它有帮助,但现在我在尝试 {{ article.image.url }} 时得到 Page Not Found
    • @AjayKumar 请将其作为一个新问题发布并将其标记为已解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    相关资源
    最近更新 更多