Django prepopulate form with the fields from the database

妖精的绣舞 提交于 2019-12-07 19:01:16

问题


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']

回答1:


You just need to set the instance when you instantiate the form in the else clause, just like you do for the POST.



来源:https://stackoverflow.com/questions/3095229/django-prepopulate-form-with-the-fields-from-the-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!