Form
vsの違いと適切な使い方について混乱しているようですModelForm
使用するフォームのタイプに関係なく、フォームのテンプレート側は同じままです。 注: フォーム内のすべての値 (POST にバインドされているか、インスタンスがある限り) は、レンダリング時に事前入力されます。
<form class="well" action="{% url member-profile %}" method="POST" enctype="multipart/form-data">{% csrf_token %}
<fieldset>
{{ form.non_field_errors }}
{{ form.display_name.label_tag }}
<span class="help-block">{{ form.display_name.help_text }}</span>
{{ form.display_name }}
<span class="error">{{ form.display_name.errors }}</span>
{{ form.biography.label_tag }}
<span class="help-block">{{ form.biography.help_text }}</span>
{{ form.biography }}
<span class="error">{{ form.biography.errors }}</span>
<input type="submit" class="button primary" value="Save" />
</fieldset>
</form>
レコードからフォームに入力する (またはフォームをレコードとして送信する) 場合は、おそらく使用するのが最善ですModelForm
EX ユーザー FK ドロップダウンを表示しないプロファイル フォーム:
class ProfileForm(forms.ModelForm):
"""Profile form"""
class Meta:
model = Profile
exclude = ('user',)
景色:
def profile(request):
"""Manage Account"""
if request.user.is_anonymous() :
# user isn't logged in
messages.info(request, _(u'You are not logged in!'))
return redirect('member-login')
# get the currently logged in user's profile
profile = request.user.profile
# check to see if this request is a post
if request.method == "POST":
# Bind the post to the form w/ profile as initial
form = ProfileForm(request.POST, instance=profile)
if form.is_valid() :
# if the form is valid
form.save()
messages.success(request, _(u'Success! You have updated your profile.'))
else :
# if the form is invalid
messages.error(request, _(u'Error! Correct all errors in the form below and resubmit.'))
else:
# set the initial form values to the current user's profile's values
form = ProfileForm(instance=profile)
return render(
request,
'membership/manage/profile.html',
{
'form': form,
}
)
else
外側がインスタンスでフォームを初期化することに注意してくださいform = ProfileForm(instance=profile)
。フォームの送信は投稿でフォームを初期化しますが、それでもインスタンスにバインドしますform = ProfileForm(request.POST, instance=profile)