vijay shanker
vijay shanker

Reputation: 2673

writing an example django form like class

I am working with flask and need django form like class so that in flask view i can simply instantiate a class and check its validity.Something like this.

class StringField(object):
    def __init__(self, value=None, null=False):
        self.value = value.strip() if value is not None else value
        self.nullable = nullable

    def clean(self):
        if self.null:
            if self.value in ('', None):
                return self.value

        else:
            if self.value in ('', None):
                raise Exception(
                    "Value can not be null or blank"
                )

        try:
            self.value = str(self.value)
        except:
            raise Exception(
                "Value is neithe string nor can be coerced into one"
            )


class MyForm(Form):
    username = StringField(null=True)

in my views i want do this

mf = MyForm(data_dict)
if mf.is_valid():
    # do something...

Problem is: how to get all fields like username, email etc in constructor of our main Form class (one which gets inherited), so that i can apply some validation to its attributes as these fields can be variable in number

Upvotes: 0

Views: 37

Answers (1)

Udi
Udi

Reputation: 30522

Django's docs contains a lot of information regarding forms, start here.

For example:

from django import forms

# your form:
class UserForm(forms.Form):
    username = forms.CharField(max_length=100)
    email = forms.EmailField(null=True, blank=True)

# and your view:
def user_view(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = Userorm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:
            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = UserForm()

    return render(request, 'user.html', {'form': form})

See the link above for more info.

Upvotes: 1

Related Questions