Answer the question
In order to leave comments, you need to log in
How to get User.last_name in Django model as foreign key?
There are models in django app:
class News(models.Model):
news_title = models.CharField(max_length=255, verbose_name="Заголовок поста") # 3аголовок поста
slug = models.SlugField(max_length=255, verbose_name="Идентификатор") # Slug
news_date = models.DateTimeField(u'Дата публикации') # дата публикации u'Дата публикации'
news_image = models.ImageField(upload_to='images/post_images', verbose_name="Изображение статьи")
news_flickr_albumId = models.CharField(max_length=300, default="Нет фотографий", verbose_name="Flickr Album ID")
news_content = models.TextField(max_length=20000,
default="No content",
verbose_name="Текст поста (максим 20000 симв)") # текст поста
news_author = models.ForeignKey(User, default='1', verbose_name="Автор статьи") # Автор поста
class Meta:
ordering = ['-news_date', ]
verbose_name = 'Новость'
verbose_name_plural = 'Новости'
def __unicode__(self):
return self.slug
def get_absolute_url(self):
return "/news/%s/" % self.slug
Answer the question
In order to leave comments, you need to log in
1. As we noticed, news_author does not take from User User.username. The field is turned into news_author_id and User.pk (id) is taken from User. Taking last_name is stupid, because collisions are inevitable. Another thing is that you see username, because the user has return self.username in the __unicode__ method. To display what you want - use its own methods or attributes (get_full_name or last_name, as you want).
2. Why don't you feed the vast majority of bread - let me call attributes crooked? Why do attributes news_author, news_title, news_content if your model is ALREADY called News?
3.
def get_absolute_url(self):
return "/news/%s/" % self.slug
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question