繁体   English   中英

发布表单之前如何检查表单字段值-Django

[英]How to check form field value before posting form - Django

我有一个当前可以很好地工作的表单,除了用户可以将他们想要的任何值输入到表单字段之一中。 我想先在用户按下提交按钮时检查字段值,然后才真正提交表单。

我在views.py中假设最好的地方在哪里?

我的目标是检查用户输入的customerTag值,并确保他们输入的值存在于CustomerTag模型字段中。

对于我的views.py我目前有:

def usersignup(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            email_subject = 'Activate Your Account'
            message = render_to_string('activate_account.html', {
                'user': user,
                'domain': '127.0.0.1:8000',
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            send_mail(email_subject,
                    message,
                    'example@example.com',
                    [to_email,],
                    fail_silently=False)
            return render(request, 'confirm.html',)
    else:
        form = CustomUserCreationForm()
    return render(request, 'signup.html', {'form': form})

我有forms.py

class CustomUserCreationForm(UserCreationForm):

    def __init__(self, *args, **kwargs):# for ensuring fields are not left empty
        super(CustomUserCreationForm, self).__init__(*args, **kwargs)
        self.fields['email'].required = True
        self.fields['first_name'].required = True
        self.fields['customerTag'].required = True

    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'first_name', 'last_name', 'email', 'customerTag',)
        labels = {
            'customerTag': ('Customer ID'),
        }
        help_texts = {
            'customerTag': ('Please contact Support if you do not have your customer ID'),
            }

上面的代码有效,但是允许用户将他们喜欢的任何内容输入到customerTag 我在想我需要做一些事情:

def usersignup(request):
    customerTags = CustomUser.objects.values_list('customerTag', flat=True)
    userInput = #user inputted value into form
    match = False
    for tag in CustomerTags:
        if userInput == tag:
            match = True
    if match == True:
        #submit form

这是正确的方向吗? 如果是这样,获得用户输入到表单中的值的最佳方法是什么?

我发现的其他一些帖子都使用javascript检查表单,如果可能的话,我宁愿使用python。

您可以使用以下方法在视图中访问customerTag值:

customerTag = request.POST.get('customerTag')

然后检查它是否存在于您的数据库中

# we retrieved customerTag in the code above sample so we pass it to filter params
match = CustomUser.objects.filter(customerTag=customerTag).exists()

# and then continue with the stuff u wanted
if match:
     #submit form

但是,如果您在用户点击提交表单之前先对表单输入进行ajax调用,则会为您的网站带来更好的用户体验

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM