在基于 class 的视图中使用 get 方法访问 form.cleaned_data
Accessing form.cleaned_data in get method in class based views
我有一种情况,我应该首先向用户显示一个表单,用户在其中填写两个字段,然后根据表单字段查询数据库并向用户显示对象列表。
但问题是我使用基于 class 的视图,我无法在我的 get 方法中访问清理后的数据。我知道必须在 post 方法中处理表单而不是 get 方法,所以我无法在 get 方法中处理表单。
这是我的代码:
views.py
class IncomeTransactionReport(LoginRequiredMixin, ListView):
def post(self, request, *args, **kwargs):
# here I get form from post request
form = IncomeReportForm(request.POST)
# if form is valid redirect user to the same page to show the results based on the filled
# in form fields 'from_date' and 'to_date'
if form.is_valid():
from_date = form.cleaned_data['from_date']
to_date = form.cleaned_data['to_date']
return redirect('income_report')
# else render the same page with the form and form errors
else:
error_message = 'Please solve the error and try again'
return render(request, 'report_income.html', context={'error_message': error_message,
'form': form}, status=422)
def get(self, request, *args, **kwargs):
# here I need to access 'from_date' and 'to_date' to query the database and show the results
# in paginated pages to the user
if from_date != None and to_date != None:
incomes = Income.objects.filter(user=user,
date__gte=datetime.date.fromisoformat(from_date),
date__lte=datetime.date.fromisoformat(to_date)).all()
elif from_date != None:
incomes = Income.objects.filter(user=user,
date__gte=datetime.date.fromisoformat(from_date),
date__lte=datetime.date.fromisoformat(from_date) + \
relativedelta.relativedelta(months=+1)).all()
else:
incomes = Income.objects.filter(user=user).all()
page = request.POST.get('page', 1)
paginator = Paginator(incomes, 5)
try:
incomes = paginator.page(page)
except PageNotAnInteger:
incomes = paginator.page(1)
except EmptyPage:
incomes = paginator.page(paginator.num_pages)
message = 'This is your requested list of incomes'
# here I return the results
return render(request, 'report_income.html', {'message': message, 'incomes': incomes})
如果您需要更多信息,请在此处 post 告诉我。
为了回答您的问题,我将只描述 Django 中正确的表单处理。但看在上帝的份上,请不要 post 在阅读完美解释所有内容的文档之前提出此类问题 here
这是如何处理其中包含表单的视图的示例:
SomeClassBasedView(TemplateView):
template_name = 'some_template.html'
def get(self, request):
# some custom get processing
form = SomeForm() # inhereting form.Form or models.ModelForm
context = { 'form': form,
# other context
}
return render(request, self.template, context)
def post(self, request):
# this works like 'get data from user and populate form'
form = SomeForm(request.POST)
if form.is_valid():
# now cleaned_data is created by is_valid
# example:
user_age = form.cleaned_data['age']
# some other form proccessing
context = {
'form': SomeForm(),
# other context
}
return render(request, self.template, context)
# if there were errors in form
# we have to display same page with errors
context = {
'form': form,
# other context
}
return render(request, self.template, context)
经过深入的搜索和思考,我发现最好的办法是将表单清理后的数据放入会话中,然后使用其他方法(例如 get 方法)访问它。
我有一种情况,我应该首先向用户显示一个表单,用户在其中填写两个字段,然后根据表单字段查询数据库并向用户显示对象列表。
但问题是我使用基于 class 的视图,我无法在我的 get 方法中访问清理后的数据。我知道必须在 post 方法中处理表单而不是 get 方法,所以我无法在 get 方法中处理表单。
这是我的代码:
views.py
class IncomeTransactionReport(LoginRequiredMixin, ListView):
def post(self, request, *args, **kwargs):
# here I get form from post request
form = IncomeReportForm(request.POST)
# if form is valid redirect user to the same page to show the results based on the filled
# in form fields 'from_date' and 'to_date'
if form.is_valid():
from_date = form.cleaned_data['from_date']
to_date = form.cleaned_data['to_date']
return redirect('income_report')
# else render the same page with the form and form errors
else:
error_message = 'Please solve the error and try again'
return render(request, 'report_income.html', context={'error_message': error_message,
'form': form}, status=422)
def get(self, request, *args, **kwargs):
# here I need to access 'from_date' and 'to_date' to query the database and show the results
# in paginated pages to the user
if from_date != None and to_date != None:
incomes = Income.objects.filter(user=user,
date__gte=datetime.date.fromisoformat(from_date),
date__lte=datetime.date.fromisoformat(to_date)).all()
elif from_date != None:
incomes = Income.objects.filter(user=user,
date__gte=datetime.date.fromisoformat(from_date),
date__lte=datetime.date.fromisoformat(from_date) + \
relativedelta.relativedelta(months=+1)).all()
else:
incomes = Income.objects.filter(user=user).all()
page = request.POST.get('page', 1)
paginator = Paginator(incomes, 5)
try:
incomes = paginator.page(page)
except PageNotAnInteger:
incomes = paginator.page(1)
except EmptyPage:
incomes = paginator.page(paginator.num_pages)
message = 'This is your requested list of incomes'
# here I return the results
return render(request, 'report_income.html', {'message': message, 'incomes': incomes})
如果您需要更多信息,请在此处 post 告诉我。
为了回答您的问题,我将只描述 Django 中正确的表单处理。但看在上帝的份上,请不要 post 在阅读完美解释所有内容的文档之前提出此类问题 here 这是如何处理其中包含表单的视图的示例:
SomeClassBasedView(TemplateView):
template_name = 'some_template.html'
def get(self, request):
# some custom get processing
form = SomeForm() # inhereting form.Form or models.ModelForm
context = { 'form': form,
# other context
}
return render(request, self.template, context)
def post(self, request):
# this works like 'get data from user and populate form'
form = SomeForm(request.POST)
if form.is_valid():
# now cleaned_data is created by is_valid
# example:
user_age = form.cleaned_data['age']
# some other form proccessing
context = {
'form': SomeForm(),
# other context
}
return render(request, self.template, context)
# if there were errors in form
# we have to display same page with errors
context = {
'form': form,
# other context
}
return render(request, self.template, context)
经过深入的搜索和思考,我发现最好的办法是将表单清理后的数据放入会话中,然后使用其他方法(例如 get 方法)访问它。