gpt4 book ai didi

django TemplateView 和表单

转载 作者:行者123 更新时间:2023-12-03 22:48:10 29 4
gpt4 key购买 nike

我有一些问题要弄清楚新的 django View (模板 View )和表单如何工作我也找不到好的资源,官方文档没有解释我如何获取请求(我的意思是获取和发布)和新表单django View 类

谢谢

添加以便更好地解释

例如我有这个表格:

from django import forms

class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)

这是读取和打印表单的代码(老式方式):
def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form

return render_to_response('contact.html', {
'form': form,
})

好吧,我的问题是如何用模板 View 做同样的事情谢谢

最佳答案

改用 FormView,即

from django.views.generic import TemplateView, FormView

from forms import ContactUsEmailForm


class ContactView(FormView):
template_name = 'contact_us/contact_us.html'
form_class = ContactUsEmailForm
success_url = '.'

def get_context_data(self, **kwargs):
context = super(ContactView, self).get_context_data(**kwargs)
#context["testing_out"] = "this is a new context var"
return context

def form_valid(self, form):
# This method is called when valid form data has been POSTed.
# It should return an HttpResponse.
#form.send_email()
#print "form is valid"
return super(ContactView, self).form_valid(form)

更多关于 FormView in Django Docs

从技术上讲,也可以使用 TemplateView,只需覆盖 post 方法,因为默认情况下模板 View 不允许您发布到它:
class ContactUsView(TemplateView):
template_name = 'contact_us/contact_us.html'

def post(self, request, *args, **kwargs):
context = self.get_context_data()
if context["form"].is_valid():
print 'yes done'
#save your model
#redirect

return super(TemplateView, self).render_to_response(context)

def get_context_data(self, **kwargs):
context = super(ContactUsView, self).get_context_data(**kwargs)

form = ContactUsEmailForm(self.request.POST or None) # instance= None

context["form"] = form
#context["latest_article"] = latest_article

return context

我认为 FormView 更有意义。

关于django TemplateView 和表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8133505/

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