Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms - How to Not Validate?

Say I have this simple form:

class ContactForm(forms.Form):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

And I have a default value for one field but not the other. So I set it up like this:

default_data = {'first_name','greg'}
form1=ContactForm(default_data)

However now when I go to display it, Django shows a validation error saying last_name is required:

print form1.as_table()

What is the correct way to do this? Since this isn't data the user has submitted, just data I want to prefill.

Note: required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.

like image 462
Greg Avatar asked Nov 14 '08 18:11

Greg


People also ask

How do I override a Django form?

You can override forms for django's built-in admin by setting form attribute of ModelAdmin to your own form class. See: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.form.

How do I check if a form is valid in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is clean method in Django?

The clean() method on a Field subclass is responsible for running to_python() , validate() , and run_validators() in the correct order and propagating their errors. If, at any time, any of the methods raise ValidationError , the validation stops and that error is raised.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.


2 Answers

Form constructor has initial param that allows to provide default values for fields.

like image 92
Alex Koshelev Avatar answered Sep 25 '22 15:09

Alex Koshelev


From the django docs is this:

from django import forms
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)

The "required=False" should produce the effect you're after.

like image 22
Jack M. Avatar answered Sep 25 '22 15:09

Jack M.