简体   繁体   English

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

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

I have a form that currently works great with the exception that a user can input any value they want into one of the form fields. 我有一个当前可以很好地工作的表单,除了用户可以将他们想要的任何值输入到表单字段之一中。 I would like to first check the field value when the user presses the submit button, before the form is actually submitted. 我想先在用户按下提交按钮时检查字段值,然后才真正提交表单。

Where is the best place to do this, I am assuming in the views.py? 我在views.py中假设最好的地方在哪里?

My objective is to check the customerTag value that the user inputs, and ensure the value they enter exists in the CustomerTag model field. 我的目标是检查用户输入的customerTag值,并确保他们输入的值存在于CustomerTag模型字段中。

for my views.py I currently have: 对于我的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 I have: 我有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'),
            }

The code above works, but allows the user to input anything they like into customerTag . 上面的代码有效,但是允许用户将他们喜欢的任何内容输入到customerTag I'm thinking I need to do something like: 我在想我需要做一些事情:

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

Is this the right direction? 这是正确的方向吗? If so, what is the best way of obtaining the value entered into form by the user? 如果是这样,获得用户输入到表单中的值的最佳方法是什么?

Some of the other posts I found were using javascript to check the form, I would rather use python if possible. 我发现的其他一些帖子都使用javascript检查表单,如果可能的话,我宁愿使用python。

you can access customerTag value in your view with: 您可以使用以下方法在视图中访问customerTag值:

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

and then check if it exists in your database 然后检查它是否存在于您的数据库中

# 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

but if you make an ajax call on form input before user hits submit on form it brings better ux to your website 但是,如果您在用户点击提交表单之前先对表单输入进行ajax调用,则会为您的网站带来更好的用户体验

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

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