1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

django usernameを表示したかった

Posted at

画像をアップロードすると同時にその投稿者の名前も登録したかった

モデルは

models.py
class Post(models.Model):
	image = models.ImageField(upload_to="image/")
	created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='posts')

(わかりやすくするために色々省いてる)

viewにはここも色々省くが、最終的にこんな感じの記述をすればよかった

views.py
		photo = Post()
		photo.image = form.cleaned_data['image']
		photo.created_by = request.user
		photo.save()

最初、

photo.created_by = request.user.username

みたいなことを書いてて、こうすると
"Post.created_by" must be a "User" instance.ってエラーが出て
ああこれはまだまだ基礎がなってないなと反省して涙した。

あとはindex.htmlでuser.usernameを書いてあげれば表示できます。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?