FORMVIEW和GET

时间:2018-01-17 22:25:38

标签: django python-3.x django-forms django-templates django-views

我正在努力清理一个FORMVIEW而收效甚微。我有以下表格:

... FORMS

class BookRequestNumberSearch(forms.Form):

q = forms.IntegerField(required=True)

def __init__(self, *args, **kwargs):
    user = kwargs.pop('user')
    q = kwargs.pop('q', None)
    super(BookRequestNumberSearch, self).__init__(*args, **kwargs)
    self.fields['q'].widget.attrs['class'] = 'name2'

def clean(self):
    cleaned_data = super(BookRequestNumberSearch, self).clean()
    request_number = cleaned_data.get('q')#
    if request_number:
        if Book.objects.filter(request_number__iexact=request_number).exists():
            try:
                Book.objects.get(request_number__iexact=request_number)
                self.add_error('request_number',' Error.')
            except Book.DoesNotExist:
                pass
    return cleaned_data      

观点......

class BookRequestNumberSearchView(LoginRequiredMixin,FormView):
    form_class = BookRequestNumberSearch
    template_name = 'Book/book_request_number_search.html'
def get_form_kwargs(self):
    kwargs = super(BookRequestNumberSearchView, self).get_form_kwargs()
    kwargs['user'] = self.request.user
    kwargs['q'] = self.request.GET.get("q")
    return kwargs

def get_initial(self):
    init = super(BookRequestNumberSearchView, self).get_initial()
    init.update({'q':self.request.GET.get("q")})
    return init  

和HTML

<form method="GET" autocomplete=off action="{% url 'Book:procedure_request_number_search_detail' %}" >

  <div>
    <h1 class="title">Book Request Number Search</h1>
  </div>

  <div class="section">
    {{ form.q }}
  </div>

此代码有效,但我无法弄清楚如何让Django调用CLEAN。我怀疑也许是因为我正在做GET CLEAN没有得到认可?我花了大部分时间玩各种变化,但无论我做什么,CLEAN都会被忽略。谢谢你的任何想法。

1 个答案:

答案 0 :(得分:1)

FormView的工作方式是,一旦有效数据被POST,它就会调用FormView的form_valid()方法。因此,您可以将一个form_valid方法添加到BookRequestNumberSearchView,在那里您可以访问表单的已清理数据:

class BookRequestNumberSearchView(LoginRequiredMixin,FormView):
    form_class = BookRequestNumberSearch
    template_name = 'Book/book_request_number_search.html'

    def form_valid(self, form):
        print(form.cleaned_data)
        return # should return an HttpResponse

注意我是如何通过form.cleaned_data访问已清理的数据(根据文档here)。

我怀疑,根据您的代码,您可能没有正确使用clean()方法。干净的方法应该简单地处理插入到表单中的数据并将数据转换为“更干净”的状态。然后,您需要访问干净的数据,并根据form_valid部分中的查询进行查询。

祝你好运!

您可以看到FormView文档here