django - Django CBV:post() 和 form_valid() 方法
问题描述
我想使用post()
和form_valid()
方法来填写我的表格,提交数据并使用数据进行一些处理。
我的课看起来像这样:
class HomeView(CreateView):
""" Render the home page """
template_name = 'app/index.html'
form_class = CustomerForm
def post(self, request, *args, **kwargs):
if request.method != 'POST':
return HttpResponseRedirect(self.get_success_url())
form = self.form_class(request.POST)
email = request.POST['email']
country_id = request.POST['country']
country = Country.objects.get(id=country_id)
for checkbox in request.POST.getlist('DocumentChoice'):
document = Document.objects.get(id=checkbox)
token = self.gen_token(email, document.edqm_id)
Download.objects.create(email=email, country=country, pub_id=checkbox, token=token,
expiration_date=now + timedelta(minutes=10))
if not form.is_valid():
print('form invalid')
continue
return HttpResponseRedirect(self.get_success_url())
我想添加form_valid()
方法以免覆盖我的post()
方法。
我试过这样的事情:
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
email = request.POST['email']
country_id = request.POST['country']
country = Country.objects.get(id=country_id)
print("I'm in post method")
if form.is_valid():
return self.form_valid(form)
return HttpResponseRedirect(reverse('app-home'))
def form_valid(self, form):
print("I'm in form_valid method")
for checkbox in self.request.POST.getlist('DocumentChoice'):
document = Document.objects.get(id=checkbox)
token = self.gen_token(self.email, document.edqm_id)
Download.objects.create(email=self.email, country=self.country, pub_id=checkbox, token=token,
expiration_date=now + timedelta(minutes=10))
self.send_email(self.email, document.upload, document.publication.title, document.edqm_id, token)
return super(HomeView, self).form_valid(form)
但我没有克服让工作成为我的课程,特别是在这个问题上:'HomeView' object has no attribute 'email'
我想我对此有误解。
编辑 :
使用 clean_data :
def form_valid(self, form):
email = form.cleaned_data['email']
country = form.cleaned_data['country']
for checkbox in self.request.POST.getlist('DocumentChoice'):
document = Document.objects.get(id=checkbox)
token = self.gen_token(email, document.edqm_id)
Download.objects.create(email=email, country=country, pub_id=checkbox, token=token,
expiration_date=now + timedelta(minutes=10))
self.send_email(email, document.upload, document.publication.title, document.edqm_id, token)
return super(HomeView, self).form_valid(form)
它似乎有效,但我不确定语法?
解决方案
推荐阅读
- bash - 无法使用 Bash 脚本 JQ 遍历值中有空格的 JSON 内部数组
- javascript - TypeError:未定义不是对象(评估“this”)
- c# - 如何拆分字符串并将其插入 DataTemplate 中的 Binding
- python-3.x - Python:使用 Numba 签名
- ethereum - 广播离线交易
- firebase-authentication - 如何使用存储在 Firebase 身份验证模拟器中的用户在 Functions Emulator 中验证 Firebase 云功能?
- r - 使用栅格中的多个函数提取值
- bash - 根据目录中的最新文件名替换文本文件中的参数
- javascript - 范围值需要正则表达式
- sql - SQL - 删除总和等于给定数字的随机行