开发者

Django prepopulate form with the fields from the database

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('开发者_StackOverflow中文版/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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜