SilentDev
SilentDev

Reputation: 22747

django how to create and use form from existing model

I'm trying to learn Django, and I am reading this link right now: https://docs.djangoproject.com/en/1.5/topics/forms/modelforms/

If you scroll down in the link provided, it says that there are two main steps involved in validating a form and that the first step is 'validating the form' which leads to this link: https://docs.djangoproject.com/en/1.5/ref/forms/validation/#form-and-field-validation

It says that the first step in every validation is to use the to_python() method on a field. I don't understand what they mean when they say

"It coerces the value to correct datatype and raises ValidationError if that is not possible. This method accepts the raw value from the widget and returns the converted value."

So suppose I have a model like this

class User(models.Model):
    user_id = models.AutoField(unique=True, primary_key=True)
    username = models.SlugField(max_length=50, unique=True)
    first_name = models.CharField(max_length=50)

I created a form like so

class UserForm(forms.ModelForm):
    class Meta:
        model = User

now, how exactly do I use to_python() method? Do I use it in a view? Or do I have to use it in the forms.py file? If I use it in a view, what would the function be called?

Upvotes: 0

Views: 422

Answers (2)

kkd
kkd

Reputation: 95

You don't need to worry about the to_python() unless you are creating a custom field. If you are going to use the ModelForm to create simple forms, you can use the clean methods.

If you want to validate only one field, you can do this:

class UserForm(forms.ModelForm):

    def clean_username(self):
        username = self.cleaned_data['username']
        if len(username) > 10:
            raise forms.ValidationError("Please shorten your username")

        # Always return the cleaned data, whether you have changed it or
        # not.
        return username

if you want to clean multiple fields, you can do this:

class Userform(forms.Form):
    # Everything as before.
    ...

    def clean(self):
        cleaned_data = super(UserForm, self).clean()
        username = cleaned_data.get("username")
        first_name = cleaned_data.get("first_name") 

        if len(username) > 10:
            raise forms.ValidationError("Please shorten your username")

        if len(first_name) < 1:
            raise forms.ValidationError("First name is too short")

        # Always return the full collection of cleaned data.
        return cleaned_data

Upvotes: 0

mariodev
mariodev

Reputation: 15519

Django does validates and deserializes fields input automatically.

Example view when posting form:

def my_view(request):
   form = UserForm() 
   if request.method == 'POST':
       form = UserForm(request.POST)

        if form.is_valid(): # here to_python() is run for each field
            form.save()
            # redirect

   return render_to_response('home.html', { 'form': form })

Upvotes: 3

Related Questions