Django - 从modelformset_factory创建request.POST对象需要花费大量时间,有时会崩溃服务器

时间:2013-11-13 07:23:38

标签: python django django-forms

我正在使用modelformset_factory并且在我的视图函数中我正在使用form_with_post = FormSet(request.POST)

但是当表单有错误时,即当我不更新必填字段时,需要花费大量时间从request.POST创建forset对象大约2-3分钟

然而,它不会抛出任何异常或错误,但在djano-server的日志中,有时我会观察到以下错误

  

“由< bound方法Command.inner_run”

启动的线程中的nhandled异常

我做错了什么或做错了什么?

我的模型如下所示:

class Un_Verified_bn_in(models.Model):
   id = models.IntegerField(primary_key=True)
   phrase =  models.CharField(max_length=30)
   author =  models.CharField(max_length=30,null=True)
   time = models.DateField(null=True)
   alternate_phrase = models.CharField(max_length=30,null=True)
   verified_by_usr =  models.BooleanField(max_length=30)
   verified_by_admin =  models.BooleanField(max_length=30)
   discard_word =  models.BooleanField(max_length=30)

我的模型形式如下:

class Un_Verified_bn_in_form(ModelForm):

def __init__(self, *args, **kwargs):
    super(Un_Verified_bn_in_form, self).__init__(*args, **kwargs)
    instance = getattr(self, 'instance', None)
    if instance and instance.pk:
        self.fields['phrase'].widget.attrs['readonly'] = True
        self.fields['id'].widget.attrs['readonly'] = True

class Meta:
    model = Un_Verified_bn_in
    fields = ('id','phrase','alternate_phrase','discard_word')
    exclude = ('time','verified_by_usr','verified_by_admin','author')

我的views.py如下:

def user_page(request,lang="bn",locale="bn_in"):

    FormSet =     modelformset_factory(Un_Verified_bn_in,form=Un_Verified_bn_in_form,extra=0)            
    query = Un_Verified_bn_in.objects.all().filter(verified_by_usr=False).filter(verified_by_admin=False)
    paginator = Paginator(query, 10)
    page = request.GET.get('page')
    usr_name = request.user
try:
    objects = paginator.page(page)
except PageNotAnInteger:
    objects = paginator.page(1)
except EmptyPage:
    objects = paginator.page(paginator.num_pages)

if request.method == 'POST':
    form_with_post = FormSet(request.POST)
    if form_with_post.is_valid():
        print "form is valid"
        instances = form_with_post.save(commit=False)
        for instance in instances:
            obj = Un_Verified_bn_in.objects.get(pk=instance.id)
            obj.author = request.user_name
            obj.verified_by_usr = True
            instance.save()
            obj.save()
     context = {'objects':objects,'formset': form_with_post}
     return render_to_response('unverified.html', context,
                              context_instance=RequestContext(request))
 else:
       page_query = query.filter(id__in=[object.id for object in objects])
       formset = FormSet(queryset=page_query)        
       context = {'objects': objects, 'formset': formset}
       return render_to_response('unverified.html', context,
                              context_instance=RequestContext(request))

1 个答案:

答案 0 :(得分:1)

嗯,你正在循环浏览可能很长的对象列表,再次从base调用它们然后保存它们(如果我正确读取它的话两次) - 那就是很多查询。

你能做的是:

1)将作者的值传递给formset,将作者作为字段添加到表单中,将其设置为 init 方法

2)添加verified_to_usr以形成隐藏字段。将其设置为True,格式为 init 方法

3)只需保存表单集。

回应评论 - https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets。如果你没有将queryset作为参数传递给formset,那么它将使用relatedmodel.objects.all()作为默认查询集。 (link)。我想你之前错过了。我说你在那里循环很长的列表 - 我认为这是故意的,你没有将另一个查询集作为值传递给formset。问题来自于我的猜测。

阿兰