chris-ho
chris-ho

Reputation: 21

Disable validation when calling form for the first time

I am struggling a bit with my Django forms. When I call my form site, always validation errors appear (this field is required). I'd prefer to see this message after clicking the submit button, if a field is not filled like a javascript function would do. In addition I'm using regex for validation, which is working fine.

I am working with CVBs. Here is some code:

models.py

 class Institute(models.Model):
    name = models.CharField(max_length=50)
    timestamp = models.DateTimeField(auto_now_add=True)  

views.py

class InstituteCreate(CreateView):
    model = Institute
    form_class = InstituteForm
    success_url = reverse_lazy('institute_list')

forms.py

class InstituteForm(forms.ModelForm):

    name= forms.CharField(error_messages={'required': 'Own Error Text'}, validators=[RegexValidator(regex='^[a-zA-ZäüößÄÜÖ]*$', message='forbidden string', code='string_invalid')])

    class Meta:
        model = Institute
        fields = ['name']

Hope someone has an idea on how to fix it.

edit1:

my template is quite simple

{% block pagetitle %}Institutes{%endblock %}
{% block content %}
    <form class="form-horizontal" name="form_group" method="post">
        {% csrf_token %}
            <div>
                {{ form.as_p }}
            </div>
            <input class="btn btn-primary" type="submit" value="click me" />
    </form>
{% endblock %}

and my url config:

urlpatterns = patterns('',  
    url(r'^institute_create/$', views.InstituteCreate.as_view(), name='institute_create'),
)

I'm new to Django development so i'll try to explain the problem more detailed:

On my website, when i open the link www.exampleurl.com/institute_create my form is shown. Then i see the field where i have to enter the name for the institute. Above this field the text "this field is required" is displayed. But i don't want to see this, until i try to submit an empty form.

When i enter some text which doesnt match and i press submit button the error text field changes its message to forbidden string as expected.

Upvotes: 2

Views: 2695

Answers (3)

Kartik
Kartik

Reputation: 53

As Brandon mentioned, your form gets validated on a POST request. So ensure that during the first visit of the page, the Form doesn't get bound to a POST request.

For example, don't do this :

def register(request):
    form = RegistrationForm(request.POST)
    if request.method == 'POST':
        if form.is_valid():
            # Do something
    return render(request, 'register.html', {'form': form}) 

You should bind the form to a POST request only if the page is accessed via a POST request. This should help:

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            # DO something
    else :
        form = RegistrationForm()
    return render(request, 'register.html', {'form': form}) 

Upvotes: 0

Vamshi
Vamshi

Reputation: 74

I know this is a very old question, but I don't see it answered. I am a beginner in django too and I was following the Django tutorial when I faced the same issue. I resolved it this way:

if 'voteButton' in request.POST:
    context = {
        'question': question,
        'error_message': "You didn't select a choice"
    }
    return render(request, 'polls/details.html', context)
elif:
    # do something else. Display error message

voteButton is the name of the 'submit' button in your form. Hope this helps! Please do let me know if this approach is wrong.

Upvotes: 0

Brandon Taylor
Brandon Taylor

Reputation: 34553

Unless you're using a POST request to your view, form validation won't be triggered. There's likely an error somewhere else in your code, however, there are couple of things about your code that you'll want to address:

Classes in Python should always begin with an upper-case letter and follow the CapWords convention:

class Institute(models.Model):
    name = models.CharField(max_length=50)

    # just use the built-in `auto_now_add` argument
    timestamp = models.DateTimeField(auto_now_add=True)

class InstituteCreate(CreateView):
    model = Institute
    form_class = InstituteForm
    success_url = reverse_lazy('institute_list')

class InstituteForm(forms.ModelForm):

    # All Django model/form fields are required by default, so you
    # can drop the `required=True` here
    name= forms.CharField(validators=[RegexValidator(regex='^[a-zA-ZäüößÄÜÖ]*$',
        message='forbidden string', code='string_invalid')])

class Meta:
    model = Institute
    fields = ['name']

Otherwise, it's impossible to tell the difference between the class definition and an instance of the class, and you're a lot less likely to run into collisions.

Just out of curiosity, are you seeing in-browser HTML5 validation errors versus errors from Django? If you can add your template code to your question it might help.

Upvotes: 3

Related Questions