我创建了一个表单,用户可以在其中输入日期范围。提交后,需要从我的数据库中返回一个列表,其中包括生日在该日期范围内的所有人。我是Django的新手,我已经尝试但不明白如何通过我的" start_date& END_DATE"作为从我的表格到ListView的kwargs。
views.py:
class BirthdaysRangeFormView(FormView):
template_name = 'snippets/date_selection_form.html'
form_class = datefilterform
def get_form_kwargs(self):
kwargs = super(BirthdaysRangeFormView, self).get_form_kwargs()
kwargs ['request'] = self.request
return kwargs
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['title'] = "Date Selection"
context['header'] = "Please select date range"
return context
def form_valid(self, form):
self.start_date = (form.cleaned_data['start_date'], People.next_birthday)
self.end_date = (form.cleaned_data['end_date'], People.next_birthday)
return self.redirect_to_results()
def redirect_to_results(self):
self.success_url = "dates:birthdays"
return redirect(
self.get_success_url(),
)
class BirthdaysListView(BirthdaysRangeFormView, ListView):
template_name = 'dates/birthdays.html',
context_object_name = "person"
person = True
# queryset = People.objects.order_by('next_birthday')
def get_queryset(self):
test = ''
forms.py:
class datefilterform(forms.Form):
model = People
start_date = forms.DateField(
input_formats=['%d/%m/%Y'],
widget=DateTimePicker(
options={"format": "DD/MM/YYYY", "pickTime": False})
)
end_date = forms.DateField(
input_formats=['%d/%m/%Y'],
widget=DateTimePicker(
options={"format": "DD/MM/YYYY", "pickTime": False})
)
People.next_birthday = start_date
People.next_birthday = end_date
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request')
super(datefilterform, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_id = 'main_form'
self.helper.form_class ='form-horizontal'
self.helper.label_class = 'col-lg-3'
self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
'start_date',
'end_date',
FormActions(
Submit('submit', 'Submit'),
Button('cancel', 'Cancel', css_class='cancel')
)
)
def clean(self):
cleaned_data = super().clean()
start_date = cleaned_data.get("start_date")
end_date = cleaned_data.get("end_date")
if not check_end_date(start_date, end_date):
raise forms.ValidationError(
"Incorrect Dates entered, End date must be after start date"
)
我以前做过简单的ListView,但我不明白如何使用" request"在基于班级的观点。
答案 0 :(得分:0)
您只需在基于班级的视图中访问self.request
即可。
而是遵循格式,以便您可以在同一视图中处理POST和GET请求。
class MyView(FormView):
template_name = 'some_template.html'
success_url = '...'
form_class = MyForm
def get(self, request, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
def form_invalid(self, form, **kwargs):
pass
def form_valid(self, form, **kwargs):
pass
.....