0

According to link1 and link2 I made model which is listed in another model as kierunek = models.ForeignKey('Kierunek', default=1) and as name of select, show self.nazwa_kierunku. Everything works fine, but I cant get def __unicode__ works. I tried also def __str__. There is always name "Object Kierunek".

One of my code samples. I tried many variants of this:

from django.db import models

class Kierunek(models.Model):
    nazwa_kierunku = models.CharField('Nazwa kierunku', max_length=100)
    created = models.DateTimeField('Timecreated', auto_now_add=True, null=True)
    modified = models.DateTimeField('Timeupdated', auto_now=True, null=True)
    def __unicode__(self):
        return self.nazwa_kierunku

class Meta:
    verbose_name = "Nazwa kierunku"
    verbose_name_plural = "Nazwy kierunkow"
Community
  • 1
  • 1
RaV
  • 1,029
  • 1
  • 9
  • 25

1 Answers1

1

Assuming you are using pyhton 3

__str__() and  __unicode__() methods

In Python 2, the object model specifies str() and unicode() methods. If these methods exist, they must return str (bytes) and unicode (text) respectively.

The print statement and the str built-in call str() to determine the human-readable representation of an object. The unicode built-in calls unicode() if it exists, and otherwise falls back to str() and decodes the result with the system encoding. Conversely, the Model base class automatically derives str() from unicode() by encoding to UTF-8.

In Python 3, there’s simply str(), which must return str (text).

(It is also possible to define bytes(), but Django application have little use for that method, because they hardly ever deal with bytes.)

Django provides a simple way to define str() and unicode() methods that work on Python 2 and 3: you must define a str() method returning text and to apply the python_2_unicode_compatible() decorator.

On Python 3, the decorator is a no-op. On Python 2, it defines appropriate unicode() and str() methods (replacing the original str() method in the process). Here’s an example:

from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible

@python_2_unicode_compatible
class MyClass(object):
    def __str__(self):
        return "Instance of my class"

This technique is the best match for Django’s porting philosophy.

For forwards compatibility, this decorator is available as of Django 1.4.2.

Finally, note that repr() must return a str on all versions of Python.

Source https://docs.djangoproject.com/en/1.8/topics/python3/#str-and-unicode-methods

lapinkoira
  • 8,320
  • 9
  • 51
  • 94