jQueryとjQuery AjaxFormプラグインを使用するようにセットアップしたdjangoモデルフォームがあります。
送信されたデータはすべて正確に処理され、エラーが表示されるか保存されますが、送信が成功した後に更新されたデータがフォームに再入力されることはありません。
これが私のコードです:
@login_required
@transaction.commit_on_success
def edit(request, pk):
a = get_object_or_404(Item.objects.select_related(), pk=pk)
b = Status.objects.all() # was select_related()
currentsec = a.integrity_hash
item_ct = ContentType.objects.get_for_model(Item).id
try:
last_viewed = request.session['last_viewed']
if pk not in last_viewed:
if len(last_viewed) > 19:
last_viewed.pop(0)
last_viewed.append(pk)
request.session['last_viewed'] = last_viewed
except KeyError:
request.session['last_viewed'] = [pk]
if request.method == 'POST':
f = ItemForm(request.POST, instance=a)
if f.is_valid():
editted_item = f.save(commit=False)
# check for changes to item before save
if currentsec == editted_item.integrity_hash:
editted_item.integrity_hash = form_hmac(f)
# lock item row for updating
Item.objects.select_for_update().filter(pk=pk)
editted_item.save()
m = Modification.objects.create(
content_object = a,
object_id = pk,
action = 1,
modifier = request.user,
)
m.save()
messages.success(request, 'Item editted successfully.')
if request.is_ajax():
response_dict = serialize('json', (editted_item,))
else:
return HttpResponseRedirect(reverse('edit', kwargs={'pk': pk,}))
else:
messages.error(request, 'Item could not be saved. It has been modified whilst you were working on it.')
response_dict = json.dumps({'errors': dict([(k, [unicode(e) for e in v]) for k,v in f.errors.items()])})
else:
messages.error(request, 'Item could not be saved.')
response_dict = json.dumps({'errors': dict([(k, [unicode(e) for e in v]) for k,v in f.errors.items()])})
else:
f = ItemForm(instance=a)
f.fields["item_maker"].queryset = ItemMaker.objects.filter(Q(end_date__isnull=True) | Q(pk = a.item_maker.id) | Q(end_date__gte=a.date_due))
variables = RequestContext(request, {
'item': a,
'form': f,
'itemstatus': b,
'item_ct': item_ct,
})
if request.is_ajax():
return HttpResponse(response_dict, mimetype="application/json")
return render_to_response('items/item_edit.html', variables)