Reputation: 4371
models.py is
from django.db import models
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
class Meta:
db_table = u'Book'
def __unicode__(self):
return "%d %s %s %s" % (self.book_id,self.book_name, self.author_name,self.publisher_name)
forms.py is
from django import forms
from django.forms import ModelForm
from myapp.models import Book
class BookForm(ModelForm):
class Meta:
model = Book
fields=['book_id','book_name','author_name','publisher_name']
my views.py is
def editbook(request,book_id):
queryset = Book.objects.filter(book_id=book_id)
if request.POST:
form=BookForm(request.POST,instance=queryset)
if form.is_valid():
form.save()
return redirect('index')
else:
form=BookForm(instance=queryset)
template = 'editbook.html'
book = { 'form':form }
return render_to_response(template, book , RequestContext(request))
I need to edit and update the already existing row of data in the database.I guess that their is some problem in views.py. So I am not sure my views.py is right. Please check and tell me if any problem and how to proceed.
Thanks
Upvotes: 6
Views: 26074
Reputation:
views.py
if request.POST:
book_form = BookForm(request.POST)
if book_form.is_valid():
book = Book.objects.get(pk=book_id)
book_form = BookForm(request.POST, instance = book)
book_form.save() #cleaned indenting, but would not save unless I added at least 6 characters.
return redirect('/index/')
else:
book = Book.objects.get(pk = book_id)
book_form = BookForm(instance=book)
return render_to_response('editbook.html',{ 'form':book_form }, context_instance=RequestContext(request))
Upvotes: 8