gpt4 book ai didi

django-models - Django-编辑和更新数据库中的现有数据

转载 作者:行者123 更新时间:2023-12-04 15:01:00 25 4
gpt4 key购买 nike

模型.py是

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 是
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']

我的 views.py 是
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))

我需要编辑和更新数据库中已经存在的数据行。我猜它们是views.py 中的一些问题。所以我不确定我的 views.py 是否正确。请检查并告诉我是否有任何问题以及如何进行。

谢谢

最佳答案

View .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))

关于django-models - Django-编辑和更新数据库中的现有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15247646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com