用django中的表单更新数据库

时间:2015-01-06 15:15:06

标签: python django django-models django-forms

我想将数据保存到数据库中。我有两个表,如models.py所示。每本书都有几本出版物。我希望在表单中插入每个pub的价格,然后更新数据库。问题是,当我输入价格时,它会在表格Version上添加任何内容,另一点是,在开始时,用户没有任何书籍,在他添加资金时,它会创建一本书。

models.py

class book(models.Model):
        user = models.OneToOneField(User,related_name='user')
        Price_init = models.IntegerField(default=0)
        Date_creation = models.DateTimeField('date creation')

class version(models.Model):
        date_pub = models.DateTimeField('date pub')
        price = models.IntegerField()
        Dprice = models.IntegerField()
        book = models.ForeignKey(book)

我的 view.py

@login_required(login_url='/view/login/')
def addVersion(request,Book_id):
    response={}
    book1 = book.objects.get(id=book_id)
    class AddForm(forms.Form):
        Price = forms.IntegerField()
    if request.method=='post':
       form=AddForm(request.POST)
       if form.is_valid():
           try:
                version1 = Version()
                version1.date_pub= datetime.now()
                version1.price=form.cleaned_data['Price']
                version1.book_id= book_id
                version1.Dprice = -(form.cleaned_data['Price'])
                version1.save()
           except:
                xxx=0
           return render_to_response('addVersion.html')
       else:
           form.errors
           return HttpResponse('form invalid')
    else:
        return render(request,'frontend/addVersion.html',response)
    tr.save()
    return render(request,'frontend/addVersion.html',response)

addVersion.html

<form name="form" method="POST" action="" id="form"> {% csrf_token %}
                        <p style="text-align:center" class="text-error"></p>
                <p style="text-align:center;margin-top:20px"><input id="" name="form" required="required" style="width:100px" value="{{Price}}" type="text"></p>
        <p> <br></p>

1 个答案:

答案 0 :(得分:0)

问题:1 现在当我输入价格时,它会在表格版本上添加任何内容。 ?

解决方案:正确进行表单验证

bookObj = book.objects.get(id=book_id)
if request.method=='POST':
   form=AddForm(request.POST)
   if form.is_valid():
      version1 = Version()
      version1.date_pub= datetime.now()
      version1.price = form.cleaned_data['Price']
      version1.book_id = book_id
      version1.Dprice = form.cleaned_data['Price']
      version1.save()

问题:2 一开始,用户没有在他添加资金时创建图书的书籍。 ?

钱从哪里来?