错误:强制转换为Unicode:需要找到字符串或缓冲区

时间:2017-02-13 11:26:27

标签: python django string unicode

我目前正在使用python django Web框架中的Calendar。我正在尝试打印一些内容并引发以下错误:

  

TypeError:强制转换为Unicode:需要字符串或缓冲区,找不到

我见过有类似问题的人,但没有'长'的人和一个有效的解决方案.... 回溯:

> Internal Server Error: /tande/holiday/ Traceback (most recent call
> last):   File
> "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line
> 149, in get_response
>     response = self.process_exception_by_middleware(e, request)   File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line
> 147, in get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/Library/Python/2.7/site-packages/django/contrib/auth/decorators.py",
> line 23, in _wrapped_view
>     return view_func(request, *args, **kwargs)   File "/Users/ryoung/Documents/Database/prodman/tande/views.py", line 83, in
> holiday
>     cal = HolidayCalendar(my_holidays).formatmonth(year, month)   File "/Users/ryoung/Documents/Database/prodman/tande/views.py", line 397,
> in __init__
>     print holiday   File "/Library/Python/2.7/site-packages/django/db/models/query.py", line
> 237, in __repr__
>     return repr(data)   File "/Library/Python/2.7/site-packages/django/db/models/base.py", line
> 467, in __repr__
>     u = six.text_type(self) TypeError: coercing to Unicode: need string or buffer, long found

这是我的代码:

class HolidayCalendar(HTMLCalendar):

    def __init__(self, holiday):
        super(HolidayCalendar, self).__init__()
        self.holiday = self.holiday_days(holiday)
        print holiday
        # for something in holiday:
        #     print something

    def holiday_days(self, holiday):
            field = lambda holiday: holiday.start_date.day
            return dict(
            [(day, list(items)) for day, items in groupby(holiday, field)]
            )

我试图看看self.holiday的设置是什么...我尝试了一个for循环,因为我认为这将是一个项目列表,它引发了同样的错误。 以下是调用上述

的视图
@login_required
def holiday(request):
    # get persons username
    # get month and year today
    date_today = datetime.now()
    year = date_today.year
    month = date_today.month
    # get holiday objects in the current month
    my_holidays = Holiday.objects.order_by('start_date').filter(
        Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month)
    )
    cal = HolidayCalendar(my_holidays).formatmonth(year, month)

    # forms... render template...etc

谢谢!

1 个答案:

答案 0 :(得分:1)

问题似乎出现在您的Holyday模型的 str unicode 方法中。那些方法应该返回resp。一个字符串或unicode对象,看起来它返回一个很长的(可能是pk - 狂野的猜测...)