0

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

1 回答 1

2

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

于 2013-03-25T00:28:38.233 回答