Django使用数据库中的字段预填表

编程入门 行业动态 更新时间:2024-10-24 12:30:51
本文介绍了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使用数据库中的字段预填表

本文发布于:2023-08-05 20:53:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1307994.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   数据库中   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!