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

发布于 2024-09-06 14:34:20 字数 1141 浏览 6 评论 0原文

我有一份隐私表格,在其中我选择当访问用户的个人资料时应隐藏哪些应用程序。 该表单包含多个复选框,用户可以选中他想要隐藏的内容。我想要的是,当用户访问此表单时,该表单将成为已保存的隐私表单的实例(如果存在)。 我的意思是,如果我已经选中隐藏应用程序 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

却一份温柔 2024-09-13 14:34:20

您只需要在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文