Django CBV:post()和form_valid()方法

时间:2018-09-19 12:11:32

标签: django

我想使用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'

我认为我对此有误解。

编辑:

使用cleaned_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)

这似乎可行,但是我不确定语法吗?

0 个答案:

没有答案