0

我想将数据添加到 django 表单中提交的数据中。

直到现在我做了这样的事情:

form = NewADServiceAccount(data=request.POST)
if form.is_valid():
   data=request.POST.copy()
   if not 'SVC' in data['Account_Name']:
       data['Account_Name'] = 'SVC_'+data['Account_Name']

   form = NewADServiceAccount(data=data)

这行得通,但我想在一个clean方法中做这个检查,所以我定义了:

def clean_Account_Name(self):
    data = self.cleaned_data['Account_Name']
    if not 'SVC' in self.cleaned_data['Account_Name']:
        data = 'SVC' + data
    return data

但是,当我使用 clean 方法运行此代码时,我看到它clean_data不匹配data,并且我呈现的表单不包含正确的Account_Name(例如,它没有 SVC):

   ipdb> p form.cleaned_data['Account_Name']
   u'SVCoz123'

   ipdb> p form.data['Account_Name']
   u'oz123'

Account_Namefrom是呈现为 HTML 的那个data,我该如何解决这个问题,以便 呈现Account_Namefrom ?cleaned_data

更新:

我找到了另一种方法,但我仍然不确定这是正确的方法:

# inside forms.py
class NewADServiceAccount(NewAccount):

Account_Name = forms.CharField(min_length=3, max_length=21, required=True,
                               #initial="Please write desired name of "
                               #+ "this service account.",
                               help_text="Please write the desired name "
                               + "of this account. The prefix 'SVC_' will"
                               + " be added to this name",)


def set_prefix(self, prefix='SVC_'):
    data = self.data.copy()
    data['Account_Name'] = prefix+data['Account_Name']
    self.data = data 

# in views.py:

if form.is_valid():        
   form.set_prefix()

第二次更新:

在查看了我的解决方案后,我决定我的清洁方法可能会更好一些,所以我做了:

def clean_Account_Name(self):
    data = self.data.copy()
    if not 'SVC' in data['Account_Name']:
        data['Account_Name'] = 'SVC' + data['Account_Name']
    self.data = data

上述解决方案有效,尽管 django 文档说:

无论您是否已更改,始终返回已清理的数据。

所以,现在我很困惑。我找到了一个解决方案,但我需要重申它是一个有效且好的解决方案。如果有人在这里评论它,我会很高兴。

4

1 回答 1

1

If I understood you have been attempts uses the clean method. If I right, you did it a little wrong. Try use def clean() with a form's field:

forms.py

class AccountNameField(forms.CharField):

    def clean(self, value):
        value = u'SVC' + value
        return value


class NewADServiceAccount(forms.Form):

    Account_Name = AccountNameField(min_length=3, max_length=21, required=True,
                                    #initial="Please write desired name of "
                                    #+ "this service account.",
                                    help_text="Please write the desired name "
                                    + "of this account. The prefix 'SVC_' will"
                                    + " be added to this name",)

views.py

form = NewADServiceAccount(request.POST or None)
if form.is_valid():
   ...

prefix is used only into a forms. If I am not mistaken prefix would be assign each fields of the form as prefix-namefield

于 2013-07-14T22:05:01.577 回答