【发布时间】:2012-06-21 17:05:27
【问题描述】:
我需要在运行时使用 ajax 将表单动态添加到我的表单集中,我指的是 Dynamically adding a form to a Django formset with Ajax
我在同一页面上有多个具有不同前缀的表单集。
我的模型是这样设计的: 一个用户可以拥有多部电话。一部电话可以有多条线路(如果需要详细信息) Accessing Many to Many "through" relation fields in Formsets
一旦用户添加了新手机,我会使用 ajax 保存手机。视图如下
def addUserPhone(request, customer_id, location_id, user_id, **kwargs):
error_msg = u"No POST data sent."
context = {}
if request.is_ajax():
if request.method == "POST":
user = End_User.objects.get(id=user_id)
phone_client = PartialPhone_ClientForm(request.POST, prefix='new_client')
instance = phone_client.save()
#associate user to a phone
instance.end_user.add(user)
#Creating an empty lineFormset for a phone
LineFormSet = modelformset_factory(Line, form=Line_Form, can_delete=True)
client_lines = LineFormSet(queryset=Line.objects.none(), prefix='phone_client_'+str(instance.id))
# how to return the two objects instance and client_lines back to the template??
#format = 'json'
#mimetype = 'application/javascript'
#data = serializers.serialize(format, [instance])
#return HttpResponse(data)
#can we return as a context?? this gives me only a string "phoneline_set" in the template
context['phone'] = instance
context['line_set'] = client_lines
return HttpResponse(context)
else:
error_msg = u"Insufficient POST data (need 'Name ' and 'Telephone Number'!)"
else:
error_msg = "Non Ajax"
return HttpResponseServerError(error_msg)
现在返回手机实例和 LineFormSet 返回视图以在模板中呈现的最佳方式是什么??
如果我只返回一个上下文,我的视图只会得到字符串“phoneline_set”。但我想做类似的事情
$.post("addUserPhone/",phoneData,function(data){
$('.scroll').append("<h2> {{ line_set }} </h2>")
});
如果我使用 Json 进行序列化并传递,我如何传递 LineFormSet 并在模板中使用它? 目前,如果我尝试序列化我的 client_lines 表单集,我会收到错误消息 AttributeError: 'LineFormFormSet' 对象没有属性 '_meta'
感谢任何帮助,谢谢!
【问题讨论】:
标签: django http jquery django-templates