Django + HTMX:尽管 strip=True 并且即使在视图中调用了 strip(),搜索表单也不会删除尾随空格

Django + HTMX: Search Form is not removing trailing spaces despite strip=True & even if strip() is called in view

出于某些奇怪的原因,当 hx-POSTing 到 /word-search/ 时,我的表单没有被清理。这导致搜索没有 return 结果,尽管它实际上存在于数据库中。

表格:

class WordSearchForm(forms.Form):
    word_search = forms.CharField(
        strip=True,
        widget=forms.TextInput(
            attrs={
                'class': 'form-control',
                'hx-post': '/word-search/',
                'hx-target': '#results',
                'hx-trigger': 'keyup changed delay:500ms',
                'placeholder': 'Search by word...'
            }
        )
    )

查看:

@require_http_methods(['POST'])
def word_search(request):

    if request.META.get('HTTP_HX_REQUEST'):

        results = None
        search_text = request.POST.get('word_search', None)

        print(search_text.endswith(' ')) => True

        if search_text is not None:

            ...

            word = search_text.strip() -> Even this does not work
            sentences = KWord.objects.filter(word__word=word)

您没有使用 Django Forms interface,因此 Django 无法应用过滤功能。您必须通过调用 form.is_valid() 来验证表单。经过验证的数据将在 form.cleaned_data.

if request.META.get('HTTP_HX_REQUEST'):
    form = WordSearchForm(request.POST)
    if form.is_valid():
        # Now strip has been applied to `word_search` field
        search_text = form.cleaned_data['word_search']
        ...

关于第二个问题:检查 filter(word__word=word) 过滤器。 __word field lookup does not exists, so I guess the HTMX request throws a 500 internal server error, but you don't have error handling on the frontend to see it. Maybe you want to make a word__contains 过滤。