HTMX-如何在字段 "keyup changed" 时获取有效表单

HTMX-How can I get valid form when field "keyup changed"

我有一个 forms.py 如下。我正在使用 htmx 进行验证。我想获得使用 form.is_valid() 函数的完整表格。但就我而言,我没有得到有效的表格。

有什么方法可以用 HTMX 获取所有表单吗?

forms.py

class UniversityForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.form_id = 'university-form'
        self.helper.attrs = {
            'hx-post': reverse_lazy('index'),
            'hx-target': '#university-form',
            'hx-swap': 'outerHTML'
        }
        self.helper.add_input(Submit('submit', 'Submit'))
    
    subject = forms.ChoiceField(
        choices=User.Subjects.choices,
        widget=forms.Select(attrs={
            'hx-get': reverse_lazy('check-subject'),
            'hx-target': '#div_id_subject',
            'hx-trigger': 'change'
        })
    )
    date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'type': 'date', 'max': datetime.now().date()}))

    class Meta:
        model = User
        fields = ('username', 'password', 'date_of_birth', 'subject')
        widgets = {
            'password': forms.PasswordInput(),
            'username': forms.TextInput(attrs={
                'hx-get': reverse_lazy('check-username'),
                'hx-target': '#div_id_username',
                'hx-trigger': 'keyup[target.value.length > 3]'
            })
        }

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) <= 3:
            raise forms.ValidationError("Username is too short")
        return username

    def clean_subject(self):
        subject = self.cleaned_data['subject']
        if User.objects.filter(subject=subject).count() > 3:
            raise forms.ValidationError("There are no spaces on this course")
        return subject


    def save(self, commit=True):
        """ Hash user's password on save """
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user

views.py

def check_username(request):
    form = UniversityForm(request.GET)
    
    if form.is_valid():
        print('Valid')
    else:
        print('No Valid')
        print(form.errors)
        print(form['date_of_birth'])
    context = {
        'field': as_crispy_field(form['username']),
        'valid': not form['username'].errors
    }
    return render(request, 'partials/field.html', context)

错误: 甚至所有领域都被填满; 我的输出 >print('No Valid') >print(form.errors) >print(form['date_of_birth'])如下...

No Valid
<ul class="errorlist"><li>password<ul class="errorlist"><li>This field is required.</li></ul></li><li>date_of_birth<ul class="errorlist"><li>This field is required.</li></ul></li><li>subject<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
<input type="date" name="date_of_birth" max="2022-03-15" required id="id_date_of_birth">

仅在 username 字段上激活用户名检查 HTMX GET 请求。默认情况下,HTMX 不会在请求中包含任何其他父元素,这就是缺少字段错误消息的原因。

要在请求中包含其他元素,您可以使用 hx-include 属性,在其中列出其他字段的 CSS 查询选择器:

class Meta:
    model = User
    fields = ('username', 'password', 'date_of_birth', 'subject')
    widgets = {
        'password': forms.PasswordInput(),
        'username': forms.TextInput(attrs={
            'hx-get': reverse_lazy('check-username'),
            'hx-target': '#div_id_username',
            'hx-trigger': 'keyup[target.value.length > 3]',
            'hx-include': '[name="password"],[name="date_of_birth"],[name="subject"]'
        })
    }

注意:在POST请求中你不必使用这个,因为你把HTMX属性放在最外层的表单元素上,所以默认情况下HTMX会包含每个字段(表单的子元素) 在请求中。