Oma*_*lla 6 python django views django-views django-1.3
我试图在Django 1.3中使用UpdateView保存表单,似乎遇到了问题.当我保存表单时,它POST到当前URL并且成功url是相同的url.
保存表单时,数据似乎已更改,因为页面上的所有字段都已更新,但是当我刷新时,所有内容似乎都会恢复.
表单是一个模型表单,这是我的观点:
class UserProfileView(UpdateView):
context_object_name = 'profile'
def get_template_names(self):
return ['webapp/user_profile.html']
def get_queryset(self):
pk = self.kwargs.get('pk', None)
if pk is not None:
user = User.objects.get(pk=pk)
else:
raise AttributeError(u"Could not locate user with pk %s"
% pk)
if user.contributor_profile.all():
queryset = Contributor.objects.filter(user__pk=pk)
else:
queryset = Member.objects.filter(user__pk=pk)
return queryset
def get_object(self, queryset=None):
if queryset is None:
queryset = self.get_queryset()
return queryset.get()
Run Code Online (Sandbox Code Playgroud)
我看不出会出现什么问题,因为Django通过UpdateView类保存表单,并且它扩展了Mixin.有没有人遇到过这个问题?
找出解决方案.问题出现了,因为没有报告的形式有错误.这似乎发生在需要以某种方式设置的隐藏字段以使表单有效.
解决方案非常简单.您只需要覆盖任何隐藏字段的post函数和帐户:
def post(self, request, *args, **kwargs):
pk = self.kwargs.get('pk', None)
if pk is not None:
user = User.objects.get(pk=pk)
else:
raise AttributeError(u"Could not locate user with pk %s"
% pk)
if user.contributor_profile.all():
contributor = Contributor.objects.get(user=user)
form = ContributorForm(request.POST, instance=contributor)
else:
member = Member.objects.get(user=user)
form = MemberForm(request.POST, instance=member)
if form.is_valid():
self.object = form.save()
return HttpResponseRedirect(self.get_success_url())
else:
return self.render_to_response(self.get_context_data(form=form))
Run Code Online (Sandbox Code Playgroud)