私はここで私の心を失っています。Django の ModelForms でスレッド セーフの問題が発生しているようですが、その理由がわかりません。以下のコードでは、_links_to_create を AddTaskForm クラスのプライベート メンバーとして設定しています。ビューでform = AddTaskForm(request.POST)をインスタンス化しますが、追加の呼び出しごとに _links_to_create リストはまだ設定されています。アイデアはありますか?
class AddTaskForm(forms.ModelForm):
class Meta:
model = Task
fields = ('text', 'created_by', 'task_list',)
widgets = {
'created_by' : forms.HiddenInput(),
'task_list' : forms.HiddenInput(),
'text': forms.Textarea(attrs = {
'class': 'autogrow',
'placeholder': 'Enter a task...',
'maxlength' : 140
}),
}
tags = forms.CharField(required = False, widget = PillAutoCompleteInput(
format = '{key}:{id}:{value}',
attrs = {'placeholder' : 'Add people, lists, dates, etc...'}))
_links_to_create = []
def __init__(self, *args, **kwargs):
super(AddTaskForm, self).__init__(*args, **kwargs)
print self.fields['tags'].widget.source
self.fields['text'].label = False
self.fields['task_list'].required = False
self.fields['tags'].label = False
self.fields['tags'].widget.source = reverse('smart-complete')
# TODO, form was not resetting. This might be a possible thread safety issue
print self._links_to_create
#self._links_to_create = []
def clean(self):
user = self.cleaned_data['created_by']
items = self.cleaned_data['tags'].split(';')
task_lists = None
team_members = None
for item in items:
if not item: continue
key, id, value = item.split(':')
if key == 'list':
if not task_lists:
task_lists = TaskList.objects.get_all_lists_for_user(user).values_list('id', flat = True)
id = int(id)
if id in task_lists:
self.cleaned_data['task_list'] = TaskList.objects.get(id = id)
elif key == 'user':
if not team_members:
team_members = user.teams.get_members(implied = True).values_list('id', flat = True)
id = int(id)
if id in team_members:
self._links_to_create.append(id)
return self.cleaned_data
def save(self, *args, **kwargs):
task = super(AddTaskForm, self).save(*args, **kwargs)
user = self.cleaned_data['created_by']
if len(self._links_to_create):
self._links_to_create = [TaskLink(user_id = id, task = task) for id in self._links_to_create]
else:
self._links_to_create.append(TaskLink(user = user, task = task))
TaskLink.objects.bulk_create(self._links_to_create)