我试着把作者的名字用于已发表的文章。
在模型中
class Artigo(models.Model):
autor = models.ForeignKey('auth.User', on_delete = models.CASCADE)
titulo = models.CharField(max_length = 100)
categoria = models.CharField(max_length = 20)
conteudo = models.TextField()
data_publicacao = models.DateTimeField(
default = timezone.now
)
def publicacao(self):
self.data_publicacao = timezone.now()
self.save()
def __str__(self):
return self.titulo
在视野中
def noticias(request):
artigos = Artigo.objects.filter(data_publicacao__lte = timezone.now()).order_by('data_publicacao')
return render(request, 'noticia/noticias.html', {'artigos':artigos})
在HTML中
<h1>Noticias</h1>
{% for artigo in artigos %}
<div>
<h1><a href ="">{{ artigo.titulo}} </a> </h1>
<p>{{ artigo.conteudo }}</p>
<p>Publicado em: {{ artigo.data_publicacao }}</p>
<p>{{ artigo.autor.username }}</p>*
</div>
{% endfor %}
这个{{artigo.autor.username}}不起作用。我有错误:异常值:基数为10的int()的文字无效:'ElFrances'
我不知道如何取得作者的名字或其他细节
好吧,我想你想使用django用户,这没关系,但这里有一些细节
先在模型上看到你需要导入它:
from django.contrib.auth.models import User
然后你这样做
class Artigo(models.Model):
autor = models.OneToOneField(User, on_delete=models.CASCADE)
告诉我这是否适合你
也做了* in
{{}} Artigo.autor.username
* is for something? perhaps try deleting it你尝试过只使用artigo.autor
吗?
由于这一行,你会收到错误
autor = models.ForeignKey('auth.User', on_delete = models.CASCADE)
而不是上面的行替换此行
autor = models.ForeignKey(User, on_delete = models.CASCADE)
并且还使用select_related for Query性能,因为当您获取作者详细信息时,您再次访问数据库。