gpt4 book ai didi

django - 是否可以在 ListView 模板中使用表单?

转载 作者:行者123 更新时间:2023-12-05 08:58:59 25 4
gpt4 key购买 nike

我构建了一个 ListView ,它运行良好,并提供了我想要的内容。

在这个 ListView 的模板中,我声明了一个指向 CreateView 的表单。表格是这样的,

{% if user.is_authenticated %}
<form action="{% url 'post_wall' %}" method="POST">
{% csrf_token %}
<input type='text' name='body' />
<input type='hidden' name='from_user' value='{{ user.id }}' />
<input type='hidden' name='to_user' value='{{ to_user }}' />
<input type='submit' value='POST'/>
</form>
{% endif %}

post_wall url对应

url(r'accounts/post_wall', WallCreate.as_view(), name='post_wall'),

包含表单的 url 是

url(r'accounts/wall/(?P<slug>\w+)/$', WallList.as_view(), name='wall'),

这会调用 CreateView,

class WallCreate(CreateView):
model = WallPost

def get_success_url(self):
url = reverse('wall', kwargs={'slug': request.POST.to_user})
return HttpResponseRedirect(url)

这给了我一个

TemplateDoesNotExist at /accounts/post_wall
users/wallpost_form.html

当帖子被发送到 CreateView 时,这不应该正常工作吗?或者我对 CBV 有什么误解?

最佳答案

是的,但是所有的表单处理都必须由 ListView 自己完成。这很简单,考虑到您可以从 ModelFormMixin 继承行为。您将只需要一个 url(到 ListView )。该模板将如下所示:

{% if user.is_authenticated %}
<form action="" method="POST">
{% csrf_token %}
{{ form }}
<input type='submit' value='POST'/>
</form>
{% endif %}

你的观点:

from django.views.generic.list import ListView
from django.views.generic.edit import ModelFormMixin

class ListWithForm(ListView, ModelFormMixin):
model = MyModel
form_class = MyModelForm

def get(self, request, *args, **kwargs):
self.object = None
self.form = self.get_form(self.form_class)
# Explicitly states what get to call:
return ListView.get(self, request, *args, **kwargs)

def post(self, request, *args, **kwargs):
# When the form is submitted, it will enter here
self.object = None
self.form = self.get_form(self.form_class)

if self.form.is_valid():
self.object = self.form.save()
# Here ou may consider creating a new instance of form_class(),
# so that the form will come clean.

# Whether the form validates or not, the view will be rendered by get()
return self.get(request, *args, **kwargs)

def get_context_data(self, *args, **kwargs):
# Just include the form
context = super(ListWithForm, self).get_context_data(*args, **kwargs)
context['form'] = self.form
return context

关于django - 是否可以在 ListView 模板中使用表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18664182/

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