I want to save data to the database. I have two tables as shown in the models.py. Every book has several publication. I wish to insert the price of each pub in the form and update thereafter the database. The problem now when I input the price it adds anything on the table Version
, another point is that at the beginning the user has no book that is at the time that he adds money it creates a book.
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)
my 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>
Question : 1 The problem now when I input the price it adds anything on the table Version. ?
Solution : do form validation correctly
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()
Question : 2 The beginning the user has no book that is at the time that he adds money it creates a book. ?
Where is the money came from ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.