MattG
MattG

Reputation: 1932

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?

My objective is to check the customerTag value that the user inputs, and ensure the value they enter exists in the CustomerTag model field.

for my views.py I currently have:

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,
                    '[email protected]',
                    [to_email,],
                    fail_silently=False)
            return render(request, 'confirm.html',)
    else:
        form = CustomUserCreationForm()
    return render(request, 'signup.html', {'form': form})

forms.py I have:

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. 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.

Upvotes: 0

Views: 3199

Answers (1)

Mohammad Moallemi
Mohammad Moallemi

Reputation: 658

you can access customerTag value in your view with:

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

Upvotes: 1

Related Questions