【发布时间】:2016-03-17 07:38:20
【问题描述】:
我是 Django 表单的新手,我需要将一些数据插入/更新到我的数据库中。
我有一些模型,在 django 管理面板中我手动介绍了用户的电话和 IMEI 号码。 之后,我创建了一个表单、一个 template.html 和一个视图。
表格如下:
from django import forms
class Send2phone(forms.Form):
NumberOfCalls = forms.CharField(
min_length=1,
widget=forms.TextInput({'class': 'form-control'})
)
TimeBetweenCalls = forms.CharField(
widget=forms.TextInput({'class': 'form-control'})
)
PSAP = forms.CharField(
min_length=1,
widget=forms.TextInput({'class': 'form-control'})
)
我的看法是:
def phone_config(request):
if request.method == 'POST':
form = Send2phone(request.POST)
if form.is_valid():
cleaned_data = form.cleaned_data
NumberOfCalls = cleaned_data.get('NumberOfCalls')
TimeBetweenCalls = cleaned_data.get('TimeBetweenCalls')
PSAP = cleaned_data.get('PSAP')
phone_model = Phone()
phone_model.id = 1
phone_model.user = donothing
phone_model.imei = donothing
phone_model.num_calls = NumberOfCalls
phone_model.time_btwn_calls = TimeBetweenCalls
phone_model.psap = PSAP
phone_model.save()
return redirect(reverse('gracias'))
else:
form = Send2phone()
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
def gracias_view(request):
return render(request, 'heroconfigurer/gracias.html')
当我创建视图时,我的问题就出现了。首先,我检查该方法是否已发布,并从表单中获取数据。 然后我检查表单是否有效并创建对象电话。之后分配不同的参数并保存它们。 从表单中插入数据效果很好,但如果我没有指定imei和用户ara,它们就会被删除。
如何在存在一些用户和imeis的数据库模型中插入数据?例如,在 id=1 中,我已经有一个用户和一个imei,我想保留它们
【问题讨论】:
-
你需要在模型上使用update方法,而不是save方法。
标签: python django forms django-models django-views