Django 使用数据库中的字段预填充表单
我有一份隐私表格,在其中我选择当访问用户的个人资料时应隐藏哪些应用程序。 该表单包含多个复选框,用户可以选中他想要隐藏的内容。我想要的是,当用户访问此表单时,该表单将成为已保存的隐私表单的实例(如果存在)。 我的意思是,如果我已经选中隐藏应用程序 1,当我再次访问表单时,将选中相应的复选框。
我的代码:
def save_privacy(request):
if request.method == 'POST':
try:
u = Privacy.objects.get(user_privacy = request.user)
form = PrivacyForm(request.POST, instance=u )
except ObjectDoesNotExist:
form = PrivacyForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user_privacy = request.user
new_obj.save()
return HttpResponseRedirect('/accounts/private_profile/')
else:
form = PrivacyForm()
return render_to_response('privacy/set_privacy.html', {
'form': form,
},
context_instance=RequestContext(request))
和我的表格:
class PrivacyForm(ModelForm):
class Meta:
model = Privacy
fields = ['restrict_cv','restrict_blog','friends_of_friends','restrict_followers','restrict_following']
i have a privacy form, in wich i am selecting what application should be hidden when one accesses a user's profile.
The form contains several checkboxes,and the user checks what he wants to be hidden. What i want is, when a user accesses this form, the form to be an instance of the privacy form already saved, if it exists one.
I mean, if i already checked hide application 1, when i am accessing the form again, the corresponding check box to be checked.
my code:
def save_privacy(request):
if request.method == 'POST':
try:
u = Privacy.objects.get(user_privacy = request.user)
form = PrivacyForm(request.POST, instance=u )
except ObjectDoesNotExist:
form = PrivacyForm(request.POST, request.FILES)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.user_privacy = request.user
new_obj.save()
return HttpResponseRedirect('/accounts/private_profile/')
else:
form = PrivacyForm()
return render_to_response('privacy/set_privacy.html', {
'form': form,
},
context_instance=RequestContext(request))
and my form:
class PrivacyForm(ModelForm):
class Meta:
model = Privacy
fields = ['restrict_cv','restrict_blog','friends_of_friends','restrict_followers','restrict_following']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只需要在 else 子句中实例化表单时设置实例,就像对 POST 所做的那样。
You just need to set the instance when you instantiate the form in the else clause, just like you do for the POST.