marwy
marwy

Reputation: 329

How to use initialize FormModel with request.post and model instance.

So I basically have this code:

@render_to('hello/home.html')
def home(request):
    info = Info.objects.get(pk=1)
    if request.method == "POST":
        form = InfoForm(request.POST, instance=info)
    else:
         form = InfoForm(instance=info)
   return {"info": info, "form": form}

aaand it doesn't work as I guessed it would be. If I initialize form with ONLY either model instance or POST, it works, but not when both. Is there a (nice?) way to create form with data populated from model instance, and update it with data from request.POST?

Upvotes: 0

Views: 331

Answers (1)

The code you are writing is already in the framework.

urls.py

from django.views.generic import UpdateView
from myapp.forms import InfoForm
urlpatterns = patterns('',
    url(r'^info/(?P<pk>[-_\w]+)/update/$', UpdateView.as_view(model= Info,template_name="hello/home.html",form_class=InfoForm), name='info_update'), 
)
# you might need to include a success url in the **kwargs i.e. success_url="/thankyou/"

Upvotes: 1

Related Questions