【发布时间】:2021-05-04 23:23:44
【问题描述】:
我正在开发一个类似于 twitter 的应用程序,用户可以在其中发帖。 我想制作一个包含用户名发布、发布内容和日期的 div。
由于用户名是 ForeignKey,所以在获取整个 User 表之前我遇到了一些错误。
我只需要获取用户名字段,里面似乎是一个字典和列表,如下所示。
您可以在下面找到代码: 模型
class User(AbstractUser):
pass
class PostData(models.Model):
active = models.BooleanField(default=True) # In case I want to add a delete feature in the future
post_content = models.CharField(max_length=360)
date_post_created = models.DateTimeField(auto_now_add=True)
user_posting = models.ForeignKey(User, on_delete=models.CASCADE, related_name="userposting")
def __str__(self):
return f"{self.post_content}"
def serialize(self):
return {
"post_content": self.post_content,
"user_posting":serializers.serialize("json", User.objects.all()),
"date_post_created": self.date_post_created
}
views.py
def all_posts(request):
# Get posts.
posts = PostData.objects.all()
#Return in reverse chronological order
posts = posts.order_by("-date_post_created").all()
return JsonResponse([post.serialize() for post in posts], safe=False)
posts.js(包含提供 html 的代码)
function load_posts(){
fetch('allposts')
.then(response => response.json())
.then(posts => {
posts.forEach(element => {
console.log(element.post_content);
console.log(element.user_posting);
console.log(element.date_post_created);
(...)
当前输出:
from console.log(element.post_content); teste teste teste
** 来自 console.log(element.user_posting); **
[ {"model": "network.user", "pk": 1, “字段”:{“密码”: “pbkdf2_sha256$216000$C13hJOjD4ojv$AW5a0AFEisWO7IG0MkVNQ8k6+OnfN0CljEV8lnfEaKE=", "last_login": "2021-01-29T00:01:37.127Z", "is_superuser": false,
“用户名”:“伊戈尔”,“名字”:“”,“姓氏”:“”,“电子邮件”: “igor@igor.pt”,“is_staff”:假,“is_active”:真,
"date_joined": "2021-01-25T17:02:11.514Z", "groups": [],
“用户权限”:[] } } ]
来自 console.log(element.date_post_created); 2021-01-25T23:48:03.515Z
我想提取在这种情况下包含 Igor 的字段 username。 我试过了:
console.log(element.user_posting[0]['fields']['username']);
当我尝试时:
console.log(element.user_posting[0].fields.username);
出现错误:
( Uncaught (in promise) TypeError: Cannot read property 'username' of undefined at posts.js:26 at Array.forEach (<anonymous>) at posts.js:23
【问题讨论】:
-
由于返回的数据是 JSON 对象数组,因此您可以使用
element.user_posting[0].fields.username。您使用 [] 访问数组和点符号(parentNode.childNode)访问对象。 -
感谢您的回复。得到一个错误:( Uncaught (in promise) TypeError: Cannot read property 'username' of undefined at posts.js:26 at Array.forEach (
) at posts.js:23 -
你能不能试试
let user = JSON.parse(element.user_posting[0]); console.log(user.fields.username);我猜数组的内容是一个字符串并且还没有被解析为一个对象,所以使用 JSON.parse() 可以让它成为一个对象。 -
谢谢,得到错误:“Uncaught (in promise) SyntaxError: Unexpected end of JSON input” /// at JSON.parse (
) at posts.js:26 >> 让用户= JSON.parse(element.user_posting[0]); /// at Array.forEach ( ) at posts.js:23 >> posts.forEach(element => { /// 我昨天花了 3 个小时来解决这个问题。我会完成一份报告,我会今晚再看看这个。:(谢谢你的帮助。 -
Django 在登录时提供会话用户,在注销时提供匿名用户。我认为您没有处理这种情况 - 注销时。
标签: javascript python django