Python 将Django表单中的选定值发送到views.py
我必须向我的数据库发送一些数据,在那里我有一个电话对象。为此,我需要选择所需的电话号码,并将数据插入数据库中。要求显示属于当前登录用户的电话号码 在我的表格中,我有3个文本输入和一个多回音字段,其中显示不同的电话号码。我的问题是:如何在我的view.py上获取所选的phone_num实例并将其发送到我的表单 My view.py:Python 将Django表单中的选定值发送到views.py,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,我必须向我的数据库发送一些数据,在那里我有一个电话对象。为此,我需要选择所需的电话号码,并将数据插入数据库中。要求显示属于当前登录用户的电话号码 在我的表格中,我有3个文本输入和一个多回音字段,其中显示不同的电话号码。我的问题是:如何在我的view.py上获取所选的phone_num实例并将其发送到我的表单 My view.py: def phone_config(request): phone = Phone.objects.get(phone_num = 611111111)
def phone_config(request):
phone = Phone.objects.get(phone_num = 611111111)
phone_nums = Phone.objects.filter(user_id = request.user.id).values_list('phone_num', flat=True)
if request.method == 'POST':
form = phoneForm(phone_nums, request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = phoneForm(phone_nums, instance=phone)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
def gracias_view(request):
return render(request, 'heroconfigurer/gracias.html')
My forms.py:
class phoneForm(ModelForm):
class Meta:
model = Phone
fields = ['phone_num', 'num_calls', 'time_btwn_calls', 'psap']
widgets = {'phone_num': Select(attrs={'class': 'form-control'}),
'num_calls': TextInput(attrs={'class': 'form-control'}),
'time_btwn_calls': TextInput(attrs={'class': 'form-control'}),
'psap': TextInput(attrs={'class': 'form-control'})
}
labels = {
'phone_num': ('Select phone number'),
'num_calls': ('Number of calls'),
'time_btwn_calls': ('Time between calls'),
'psap': ('PSAP'),
}
def __init__(self, phone_nums, *args, **kwargs):
super(tcuForm, self).__init__(*args, **kwargs)
self.fields['phone_num'].queryset = Sim.objects.filter(phone_num__in = phone_nums)
如果表单有效,您只需在表单中访问表单中的任何字段值即可: view.py:
有关更多详细信息,请检查我需要实例选择的电话号码,以便更新数据库中的数据存储
phone\u obj=phone.objects.get(phone\u num=phone\u num)
返回电话实例phone_obj
就是这个例子。我不能在分配之前引用'phone_num'。你是怎么做到的?如果执行'phone_num=form.cleaned_data.get('phone_num')`然后执行'phone_obj=phone.objects.get(phone_num=phone_num)`则无法获得此类错误,除非您在if语句之外的其他位置引用变量:form.is_valid()
。系统不知道要更新数据的电话号码,因此它会在数据库上创建一个新的电话对象,而不是更新所选电话号码上的数据
def phone_config(request):
phone_nums = Phone.objects.filter(user_id = request.user.id).values_list('phone_num', flat=True)
if request.method == 'POST':
form = phoneForm(request.POST)
if form.is_valid():
phone_num = form.cleaned_data.get('phone_num') # here you get the selected phone_num
phone_obj = Phone.objects.get(phone_num=phone_num)
... # the rest of the view