基于Django Class的视图将数据发布到ListView?

时间:2014-01-08 10:54:08

标签: listview post formview django-class-based-views django-1.5

我有一个包含2个字段的表单(开始日期,结束日期),我想将数据发布到ListView以下是我正在使用的代码,但我想知道这是在django中执行post方法的正确方法1.5基于类的视图。可以写GET& POST方法在同一个ListView中,其中get方法将返回ListView&在post方法中将返回Filtered ListView&在同一模板中渲染数据。

froms.py

class DailytaskfilterForm(forms.Form):
    start_date = forms.DateField()
    end_date = forms.DateField()

    def clean(self):
        cleaned_data = super(DailytaskfilterForm, self).clean()

        try:
            start_date = cleaned_data.get('start_date')
        except:
            start_date = ""

        if not start_date:
            errormsg = "Please Select start Date"
            self._errors["start_date"] = self.error_class([errormsg])

        try:
            end_date = cleaned_data.get('end_date')
        except:
            end_date = ""

        if not end_date:
            errormsg = "Please Select End Date"
            self._errors["end_date"] = self.error_class([errormsg])

        return cleaned_data

Views.py

class DailytaskfilterformView(LoginRequiredMixin, FormView):

    template_name = 'viewdailytask.html'
    form_class = DailytaskfilterForm

    def form_valid(self, form):
        sdate = form.cleaned_data['start_date']
        edate = form.cleaned_data['end_date']
        return HttpResponseRedirect(reverse('dashboard:dailytask-list-filter', kwargs={'start_date':sdate, 'end_date':edate}))

    def form_invalid(self, form):
        return self.render_to_response(self.get_context_data(form=form))

    def post(self, request, *args, **kwargs):
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

class Dailytaskfilterview(LoginRequiredMixin, ListView):

    template_name = 'viewdailytask.html'
    model = DailyTask
    context_object_name = 'dailytasks'
    paginate_by = 10

    def get_context_data(self, **kwargs):
        context = super(Dailytaskfilterview, self).get_context_data(**kwargs)
        user = self.request.user
        name = User.objects.get(username=user)
        fullname = "%s %s" % (name.first_name, name.last_name)
        context['fname'] = fullname
        context['pk'] = name.pk
        return context

    def get_queryset(self):
        start_date = self.kwargs['start_date']
        end_date = self.kwargs['end_date']
        user = self.request.user
        pk = User.objects.get(username=user).id
        return DailyTask.objects.filter(user=pk).filter(date__range=(start_date, end_date)).order_by('-date')

urls.py

url(
    regex=r'dailytask/filter/$',
    view=DailytaskfilterformView.as_view(),
    name='dailytask-filter'
    ),

url(
    regex=r'dailytask/filter/(?P<start_date>[-\w\d]+)/(?P<end_date>[-\w\d]+)/$',
    view=Dailytaskfilterview.as_view(),
    name='dailytask-list-filter'
    ),

0 个答案:

没有答案