0
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のFormに動的な初期値を入れる
Python
DjangoのFormを表示する時の初期値の設定。

forms.py

coding: utf-8

from django import forms
from app.models import Order

class OrderForm(forms.ModelForm):
name = forms.CharField(
max_length = 200,
initial = u'鈴木太郎', # 初期値
)

class Meta:
    model = Order

views.py

from django.shortcuts import get_object_or_404
from django.views.generic.simple import direct_to_template
from app.models import Order, Customer
from app.forms import OrderForm

def orderRegister(request):
num = 1
customer = get_object_or_404(Customer, id=num)
form = OrderForm(initial = {
'name': customer.name}) # 初期値

return direct_to_template(request, 'some.html',
    extra_context = {
        'form': form,
    },
)
0
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
0
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?