本文介绍了Django使用数据库中的字段预填表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个隐私表格,我正在选择什么应用程序应该隐藏,当一个人访问用户的个人资料。 该表单包含几个复选框,用户检查他想要隐藏的内容。我想要的是,当用户访问此表单时,表单将被保存为已保存的隐私表单的实例(如果存在)。 我的意思是,如果我已经检查了隐藏应用程序1,当我再次访问该表单时,将检查相应的复选框。
我的代码: / p>
def save_privacy(request): if request.method =='POST': try:u = Privacy.objects.get(user_privacy = request.user) form = PrivacyForm(request.POST,instance = u)除了ObjectDoesNotExist: form = PrivacyForm(request.POST ,request.FILES)如果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 =请求上下文(请求))和我的表单:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $''''''''''''''''''''''''''''''''''''''''''' ,'restrict_followers','restrict_following']解决方案
在实例化else子句中的表单时,需要设置实例,就像您在POST中一样。
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']解决方案
You just need to set the instance when you instantiate the form in the else clause, just like you do for the POST.
更多推荐
Django使用数据库中的字段预填表
发布评论