Rajat Saxena
Rajat Saxena

Reputation: 3935

Access form's instance in django

I have a form which has is an instance of some model X.Now how can I access the form's instance in a view provided that I'm handling form submission(POST) in another view.One view is used to create the form and other view is used to process the form.

Upvotes: 0

Views: 223

Answers (2)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You can simply pass the form object off to the secondary view:

def view_one(request, slug):
    if request.method == 'POST':
        obj = get_object_or_404(Model, slug=slug)
        model_form = MyModelForm(request.POST, instance = obj)
        return view_two(request, form=model_form) 

def view_two(request, form=None):
    if form:
        obj = form.save(commit=False)
        obj.some_attribute = "Foo"
        obj.save()
        return render_to_response(...)

Upvotes: 0

Burhan Khalid
Burhan Khalid

Reputation: 174748

From the documentation

Also, a model form instance bound to a model object will contain a self.instance attribute that gives model form methods access to that specific model instance.

def myview(request):
    if request.method == "POST":
        form = MyModelForm(request.POST,request.FILES)
        # form.instance -- this is the model

Upvotes: 1

Related Questions