Django ModelForm线程安全?

时间:2013-03-25 00:20:00

标签: python django thread-safety django-forms

我在这里失去理智。显然我有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)

1 个答案:

答案 0 :(得分:2)

如果您真的想让_links_to_create成为该类每个实例的私有成员,则需要在__init__方法中创建该变量。