gpt4 book ai didi

python - 将 View 与模板 View django 合并

转载 作者:行者123 更新时间:2023-12-01 04:34:26 24 4
gpt4 key购买 nike

我希望我的主页的登陆页面是一个带有输入的表单,用户可以输入内容。所以我遵循了几个教程,现在我有了这个:

views.py:

def create2(request): 
if request.method =='POST':
form = LocationForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('')
else:
form = LocationForm()

args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('location/index.html', args)

在我的 urls.py 中:

url(r'^$', 'core.views.create2'),

效果非常好,如果我转到 127.0.0.1:8000,我会访问 index.html,当在输入中输入某些内容时,它会保存在数据库中。然而,我主页的旧部分看起来像这样

class LandingView(TemplateView):
model = Location
template_name="location/index.html"
def search
...

和 urls.py:url(r'^$', core.views.LandingView.as_view(), name='index'),

它有一个函数 search 我所以我的问题是,有没有办法将 def create2 合并到我的 LandingView 中。我尝试了几件事,但最终总是得到没有输入字段的index.html。我也尝试过

def create2 
...
def search
...

但没有成功。

有谁知道如何将它们合并在一起吗?

编辑谢谢,工作解决方案现在看起来像这样

class Create(CreateView):
model = coremodels.Location
template_name = 'location/test.html'
fields = ['title']
def form_valid(self, form):
form.save()
return HttpResponseRedirect('')

return super(Create, self).form_valid(form)

最佳答案

根据您要寻找的结果,有多种方法可以解决此问题:

<强>1。使用CreateViewUpdateView

Django 已经提供了一些类,可以为您的模型呈现表单,使用 POST 提交表单,如果表单验证不成功,则重新呈现带有错误的表单。

检查generic editing views文档。

<强>2。覆盖get_context_data

LandingView 中,覆盖 TemplateViewget_context_data方法,以便您的上下文包含您在 create2 中创建的表单。

<强>3。使用FormView

如果您仍然想使用自己定义的表单而不是 CreateViewUpdateView 为您生成的模型表单,您可以使用 FormView ,它与 TemplateView 几乎相同,除了它还自动处理表单提交/错误。

<小时/>

无论如何,您都可以将 search 函数保留在基于类的 View 中,并从 get_context_data 调用它,以将其结果包含在模板的上下文中。

关于python - 将 View 与模板 View django 合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com