2016-12-27 12 views
0

のような形は、私はフラスコで働いていますジャンゴとフラスコビューで、私は単純にクラスをインスタンス化し、このようにそのvalidity.Somethingを確認することができるように、クラスのような形をジャンゴ必要です。私の見解では、クラス

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) 

私はこの

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

問題を行いたいのです: ので、私たちのメインのFormクラスのコンストラクタに(継承されます1)を、ユーザー名、電子メールなどのようなすべてのフィールドを取得する方法これらのフィールドは、数

答えて

1

Djangoのドキュメントは、フォームに関する多くの情報が含まれて可変できるよう、私はその属性にいくつかの検証を適用することができ、hereを開始します。例えば

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}) 

は、詳細は上記のリンクを参照してください。