3
2

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] CreateViewにおいてformで指定していないfieldにデータを追加する方法

Last updated at Posted at 2019-08-04

環境

  • Python: 3.7.2
  • Django: 2.0.13

実装

  • modelを定義し、modelformを作る。
project/app/models.py
from django.db import models

class SampleModel(models.Model):
    field1 = models.CharField(verbose_name='フィールド1', max_length=200)
    field2 = models.CharField(verbose_name='フィールド2', max_length=200)
    field3 = models.CharField(verbose_name='フィールド3', max_length=200)
    field4 = models.CharField(verbose_name='フィールド4', max_length=200)
project/app/forms.py
from django import forms
from .models import SampleModel

class SampleCreateForm(forms.ModelForm):
    class Meta:
        model = SampleModel
        fields = ('field1', 'field2', 'field3')
  • fieldsに含まれていない field4を自分で設定したい
project/app/views.py
from django.views.generic import CreateView
from django.shortcuts import redirect

from .models import SampleModel
from .forms import SampleCreateForm

class SampleCreateView(CreateView):
    model = SampleModel
    form_class = SampleCreateForm
    def post(self, request, *args, **kwargs):
        context_object_name = 'sample_create'
        form = self.form_class(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.field4 = 'ここに値を書き込む'
            obj.save()
            return redirect('sample_detail', pk=obj.pk)


sample_create = SampleCreateView.as_view()
  • save() を commit=False で呼び出すと、データベースに保存する前のモデルオブジェクトを返してくれるらしい

  • 他にいい方法があったら教えてください><

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?