我是Web开发和Django的新手。我很难找到正确的方法来更新Django项目中模型的记录(对象)。您能看看我的代码并帮助我修复它吗?
运行下面的代码后,我得到对象已存在的错误。 (是的,应该是,我要更新它!!!)我的猜测是is_valid()是问题所在。
我有以下模型:
class QA_machine_DB(models.Model):
QAmachine = models.CharField( max_length = 64, unique=True)
status = models.CharField(max_length=32,null=True, blank=True)
def __str__(self):
return "%s" % (self.id)
我有以下视图:
def formreport(request):
Booking= BookingForm(request.POST)
if request.method == 'POST':
if Booking.is_valid():
print('############## VALIDATION GOOD ######################### ')
machine_name= Booking['QAmachine']
print('Name',Booking.cleaned_data['QAmachine'])
print("Status: ",Booking.cleaned_data['status'])
to_book =QA_machine_DB.objects.get(QAmachine= machine_name) # if I hard code the machine_name it works . !? I guess is_valid is the problem ....
#to_book =QA_machine_DB.objects.get(QAmachine= 'ali' )
to_book.status='free'
to_book.save()
return index(request)
else:
print('Form not valid', Booking.errors)
return render(request,'QA_interface_app/form_page.html', { 'Booking': Booking})
我真的看不到,如果您能帮助我,那太好了。预先感谢
答案 0 :(得分:0)
您可以尝试更改吗?
to_book =QA_machine_DB.objects.get(QAmachine= machine_name)
上
to_book =QA_machine_DB.objects.get(QAmachine=Booking.cleaned_data['QAmachine'])
答案 1 :(得分:0)
首先,我没有通过is_valid()做到这一点,但我找到了解决方法,目前对于我的项目已经足够了:
if request.method == 'POST':
post_request_dict = (dict(request.POST)) # get the query set into dict
# then I use the data to do the update.
print('++++++ PK ++++++:',post_request_dict['QAmachine'][0])
TT=QA_machine_DB.objects.get(QAmachine=post_request_dict['QAmachine'][0])
TT.status=post_request_dict['status'][0]
TT.save()
if Booking.is_valid():
return index(request)
else:
print('Form not valid', Booking.errors)
这是很难看的,但它对pk或实例有效,但不适用于我。 请让我知道替代方法...。