LoginSignup
11
9

More than 5 years have passed since last update.

DjangoのCreateViewでユーザーを外部キーを挿入する方法

Last updated at Posted at 2018-10-25

やりたいこと

Djangoで以下のようなmodelとformがあってCreateViewを使いたい。
author_idはuserテーブルのidと外部キーになっているので作成時に現在ログイン中のuser_idを作成時に挿入したい。

models.py

class Post(models.Model):
    postid = models.AutoField(primary_key=True)
    author = models.ForeignKey(
        'accounts.User', on_delete=models.SET_NULL, null=True)
    picture = models.ImageField(
        upload_to="image/posts/", blank=True, null=True)
    text = models.TextField(blank=True)

forms.py


from .models import Post


class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ("picture", "text")

解決策

stackoverflowに良さそうな解決方法があった。
formのバリデーション実行時に現在ログイン中のidを差し込んで返す。

class New(generic.edit.CreateView):
    template_name = 'post/new.html'
    form_class = PostForm

    def form_valid(self, form):
        form.instance.author_id = self.request.user.id
        return super(New, self).form_valid(form)


参考

11
9
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
11
9