Reputation: 317
I'm trying to set initial values in form for editing within views. For example i want to edit book that is allready stored in database setting initial values from database query. Is it possible in django ? For instance:
views.py:
from .models import Book
from .forms import BookForm
def edit_book(request,book_id):
query_book=Book.objects.get(pk=book_id)
Book_form_to_edit =BookForm(initial=query_book)
context={
'book_form':Book_form_to_edit,
}
return render(request,'edit_book.html',context)
Thank you in advance.
Upvotes: 0
Views: 525
Reputation: 673
Yess, it is possible try referring the code below. I have edited your code so you will grab some idea on it.
from .models import Book
from .forms import BookForm
def edit_book(request,book_id):
query_book=Book.objects.get(pk=book_id)
Book_form_to_edit =BookForm(request.POST, instance=query_book)
if Book_form_to_edit.is_valid():
Book_form_to_edit.save()
context={
'book_form':Book_form_to_edit,
}
return render(request,'edit_book.html',context)
and in url.py make sure to get the book_id
path('<int:book_id>/Edit/', views.edit_view, name='edit')
Upvotes: 1