我是web-dev的新手,并被要求使用Django和Ajax编写调查。我在数据库中更新值时遇到了一些麻烦。如图所示
我的SQL值始终为空白,即使打印了值(RxCx是从request.POST.get获得的值)
Models.py
class Office(models.Model):
Office_Space = (
('R1B1', 'R1B1'),
('R2B1', 'R2B1'),
('R3B1', 'R3B1'),
('R1B2', 'R1B2'),
('R2B2', 'R2B2'),
('R3B2', 'R3B2'),
('R1B3', 'R1B3'),
('R2B3', 'R2B3'),
('R3B3', 'R3B3')
)
space = models.CharField(max_length=4, choices=Office_Space)
Forms.py
from django import forms
from Survey.models import Office
class officeForm(forms.ModelForm):
class Meta:
model = Office
fields = ['space',]
视图中的功能(视图编写得很差,但如果我以其他方式执行,则表单最终无效...)
def get_Office(request):
form_class = officeForm
if request.method == 'POST':
space = request.POST.get('result')
response_data = {}
print(space) # here is the RxCx printed for debugging
response_data['space'] = space
form = Office()
form.save()
print (connection.queries) #the SQL log
return JsonResponse(response_data)
else:
form = officeForm()
return render(request, 'Front.html', {'officeform': form})
提前致谢。
答案 0 :(得分:1)
你没有传递form
任何数据(!),这就是为什么它是空的。为了工作,请转到form
response_data
字典。像这样:
form = Office(response_data)
更正:上述行仍然不起作用,因为Office
是模型,您需要声明为form_class
的表单。所以,
form = form_class(response_data)
甚至更好,删除form_class = officeForm
行,然后写下:
form = officeForm(response_data)
答案 1 :(得分:0)
view.py
def get_Office(request):
form_class = officeForm(request.POST or None)
if request.method == 'POST':
if form_class.is_valid():
space = request.POST.get('result')
response_data = {}
print(space) # here is the RxCx printed for debugging
response_data['space'] = space
form_class.save()
print (connection.queries) #the SQL log
return JsonResponse(response_data)
return render(request, 'Front.html', {'officeform': form_class})