假设我有一个用于添加/编辑产品的表单(字段“用户”是我的用户的外键),由两个单独的视图函数触发 - 添加/编辑:
def product_add(request):
userprofile = UserProfile.objects.get(user=request.user)
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES,)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm()
return render_to_response('products/product_add.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
def product_edit(request, id):
product = get_object_or_404(Product, id=id, user=request.user)
if product.user.id!=request.user.id:
raise Http404
if request.method == 'POST':
form = ProductAddForm(request.POST, request.FILES, instance=product)
if form.is_valid():
form.save(user=request.user)
else:
form = ProductAddForm(instance=product)
return render_to_response('products/product_edit.html', {
'form':form, 'user':request.user,
}, context_instance=RequestContext(request))
表单的保存方法如下所示:
def save(self, user, *args, **kwargs):
self.instance.user = user
post = super(ProductAddForm, self).save(*args, **kwargs)
post.save()
有人可以一步一步告诉我这个保存方法发生了什么吗?为什么我们在这个表单上调用 super 以及如果函数调用相同,当我们编辑和保存新产品时整个处理有什么区别?