Issue
Initially i am loading a modelform with an instance in the template end. But i have to change the instance upon some action using ajax and then refresh the form in the template end. Please suggest me is there any way to do that?
Solution
Normally, the server view uses a ModelForm
to render a HTML snippet representing an instance of a Model
(i.e. {{ myform.as_p }}
or similar) that is then placed in a larger template representing an entire HTML document and finally sent to the client.
You need to create a second view that will render and return only the HTML snippet representing the form. From your original template you can then create an ajax call to your new view, which will return the forms HTML. You can replace your existing form with this via jQuery.
view:
def my_second_form(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
...
else:
form = MyForm()
return render(request, 'my_second_form.html', {
'form': form,
})
template:
<form action="/url/to/my_second_form/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
Answered By - Timmy O'Mahony
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.