0

So im trying at add a simple validator that checks against a postcode and returns a validation error if the user inputs non alphanumberics. But after trying i cant seem to get even the most basic validation message to show up.

Here is my form i used the example field validation just to try get it to show up but it doesn't

class CartAddShippingDetailsForm(forms.Form):

    first_name = forms.CharField(max_length=100)
    last_Name = forms.CharField(max_length=100)
    email = forms.EmailField()
    address1 = forms.CharField(max_length=100)
    town = forms.CharField(max_length=100)
    postcode = forms.CharField()
    country = LazyTypedChoiceField(choices=countries)
    additional_note = forms.CharField(max_length=100, required=False)

    def clean_postcode(self):
        data = self.cleaned_data['postcode']
        if "fred@example.com" not in data:
            raise forms.ValidationError("You have forgotten about Fred!")

        else:
            return postcode

This my views.py

def shipping_details(request):
    cart = Cart(request)
    shipping_form = CartAddShippingDetailsForm()    
    if request.method == 'POST':
        shipping_form = CartAddShippingDetailsForm(request.POST)
        if shipping_form.is_valid():        
            return redirect(reverse('test_order'))
    else:           
        return render(request, 'shippingdetails.html', {'cart': cart, 'shipping_form': shipping_form})

and the html

{% extends "base.html" %}

{% load static %}
{% block title %}Shipping{% endblock %}
{% block content %}

<form action="{% url 'test_order' %}" method="post">
    <div class="colcontainer">
    {% csrf_token %}    
    {{ shipping_form }}
    <input type="submit" name="Submit"> 
    </div>
</form>

{% endblock %}

i have also tried using the validator because i just want to check that the field contains only alphanumeric symbols

postcode = forms.CharField(validators=[validators.validate_slug])

but nothing shows up at all, the forms passes validation and redirects sucessfully. I have tried everything and nothing seems to work. Do i need extra html code to show the validation errors? i cant find anything about it in the documentation and its driving me crazy!

  • Check [this](https://stackoverflow.com/questions/14647723/django-forms-if-not-valid-show-form-with-error-message) – Abdul Niyas P M Jan 23 '18 at 03:11
  • Thanks for looking, but my code is the same in the examples the post you linked, the issue is that the form is considered valid, like the clean_postcode method is not run at all? the form is validating even though i am not inputting "fred@example.com"?? – Kai Forward Jan 23 '18 at 03:22

0 Answers0