How to use two different Django Form at the same template?

雨燕双飞 提交于 2019-12-03 07:59:08

Use the prefix argument so that your field names don't clash.

For example:

alert form = AlertForm(request.POST, prefix='alert') 
notifier_form = NotifierForm(request.POST, prefix='notifier')

You need to use the same prefix in your unbound forms.

extra_context = { 'alert_form': AlertForm(prefix='alert'),  notifier_form': NotifierForm(prefix='notifier') }

The advantage of using prefix is that you don't need to manually rename the fields, as umnik700 suggests in their answer.

The problem is that on your forms the fields have the same names.

request.POST is a dictionary-like object. So it only contains the name/value pairs from the request. If the field names are the same on both of the forms then when you call

alert_form = AlertForm(request.POST)
notifier_form = NotifierForm(request.POST)

they are initialized with the same values. To resolve this make the names to be unique between your two forms. For example prefix all the field names on the AlertForm with "alert_".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!