Why is Django reverse () not working with unicode?

Here is a django model file that does not work as I expected. I would expect the to_url method to do a reverse lookup in the urls.py file and get a URL that matches the call to this view with the arguments provided by the Arguments model.

from django.db import models
class Element(models.Model):
    viewname = models.CharField(max_length = 200)
    arguments = models.ManyToManyField('Argument', null = True, blank = True )

    @models.permalink
    def to_url(self):
        d = dict( self.arguments.values_list('key', 'value') )
        return (self.viewname, (), d)
class Argument(models.Model):
    key = models.CharField(max_length=200)
    value = models.CharField(max_length=200)

The value of d ends like a dictionary from a Unicode string to another Unicode string, which, it seems to me, should work fine with the reverse () method, which will be called by the permalink decorator, but this leads to:

TypeError: reverse() keywords must be strings
+3
source share
1 answer

to_url , d dict Unicode. Django, , Python. :

>>> def f(**kwargs): print kwargs
... 
>>> d1 = { u'foo': u'bar' }
>>> d2 = { 'foo': u'bar' }
>>> f(**d1)
TypeError: f() keywords must be strings
>>> f(**d2)
{'foo': u'bar'}

d = dict( self.arguments.values_list('key', 'value') )

-

d = dict((str(k), v) for k, v in self.arguments.values_list('key', 'value').iteritems())

.

+5

Source: https://habr.com/ru/post/1742021/


All Articles