在Django中,可以使用UpdateView和CreateView来处理表单的更新和创建操作。要将这两个表单显示在同一页上,可以通过以下步骤实现:
下面是一个示例代码:
from django.views.generic import UpdateView, CreateView
from django.urls import reverse_lazy
from .models import YourModel
from .forms import YourForm
class FormView(UpdateView, CreateView):
model = YourModel
form_class = YourForm
template_name = 'your_template.html'
success_url = reverse_lazy('your_success_url')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['update_form'] = self.get_form(self.get_form_class())
context['create_form'] = self.get_form(self.get_form_class())
return context
在上面的示例中,需要替换"YourModel"为你要操作的模型,"YourForm"为你的表单类,"your_template.html"为你的模板文件名,"your_success_url"为操作成功后的重定向URL。
在模板文件"your_template.html"中,可以使用以下代码来渲染表单:
<form method="post">
{% csrf_token %}
{{ update_form.as_p }}
{{ create_form.as_p }}
<input type="submit" value="Save">
</form>
这样就可以在同一页上显示UpdateView和CreateView的表单了。
注意:以上代码仅为示例,实际使用时需要根据自己的项目结构和需求进行适当的修改。
领取专属 10元无门槛券
手把手带您无忧上云