Django - while creating object from request.POST from modelformset_factory takes lot of time and sometimes crashes server

Django - while creating object from request.POST from modelformset_factory takes lot of time and sometimes crashes server



I am using modelformset_factory and in my view function I am using form_with_post = FormSet(request.POST)



But when form has errors i.e when I don't update required fields it takes lot of time to create forset object from request.POST approx 2-3 mins



However it does not throw any exception or errors but in djano-server's log sometimes I observe following error



"nhandled exception in thread started by <bound method Command.inner_run of"



Am I doing any mistake or wrong thing?



My Model looks as follows:


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)



My modelform looks as follows:


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')



My views.py is as follows:


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 Answer
1



Well you are looping through potentially very long list of objects, calling them up from base again and then saving them (twice if i read it correctly) - that is alot of queries.



What you could do is:



1) Pass the value of author to formset, add author as field to form, set it in form init method



2) add verified_to_usr to form as hidden field. Set it to True in form init method



3) just save the formset.



In response to comment - https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#model-formsets. THe place where it says that if you do not pass queryset as parameter to formset, then it will use relevantmodel.objects.all() as default queryset. (link). I think you missed that before. I said you are looping through very long list there - i thought it was intentional, that you had not passed another queryset as value to formset. Thats where the problems come from was my guess.



alan





I think problem is in form_with_post = FormSet(request.POST) this line because excution blocks at this point. May be something is wrong in read only attributes
– anish
Nov 13 '13 at 14:53





Changed my asnwer in response to your comment.
– Odif Yltsaeb
Nov 13 '13 at 15:43





i have added this line form_with_post = FormSet(request.POST,queryset=Un_Verified_bn_in.objects.none()) Now i am getting exception [error] IndexError: list index out of range.I am little confused with this behaviour.
– anish
Nov 13 '13 at 16:54






ohh got it form_with_post = FormSet(request.POST,queryset=page_query) solved the problem! thanks!
– anish
Nov 13 '13 at 17:06





Good job. Still - i suggest you implement my ideas to further limit the queries you run in that view.
– Odif Yltsaeb
Nov 13 '13 at 17:29






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

How do I collapse sections of code in Visual Studio Code for Windows?

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ