我是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')
当我创建视图时,我的问题就出现了。首先,我检查方法是否发布,我从表单中获取数据。 然后我检查表单是否有效,然后创建对象Phone。之后,分配不同的参数并保存。 从表单中插入数据工作正常,但如果我没有指定,则会删除imei和用户ara。
如何在存在某些用户和imeis的数据库模型中插入数据?例如,在id = 1中,我已经有了一个用户和一个imei,我想保留它们
答案 0 :(得分:1)
您应该检索现有的Phone对象并在必要时进行更新。
if form.is_valid():
number_of_calls = form.cleaned_data.get('NumberOfCalls')
time_between_calls = form.cleaned_data.get('TimeBetweenCalls')
psap = form.cleaned_data.get('PSAP')
phone = Phone.objects.get(pk=1)
phone.num_calls = number_of_calls
phone.time_btwn_calls = time_between_calls
phone.psap = psap
phone.save()
更好的是,将表单设为ModelForm,并仅包含要更新的字段:
class Send2phone(forms.ModelForm):
class Meta:
model = Phone
fields = ['num_calls', 'time_btwn_calls', 'psap']
现在您的观点只是:
phone = Phone.objects.get(pk=1)
if request.method == 'POST':
form = Send2tcu(request.POST, instance=phone)
if form.is_valid():
form.save()
return redirect(reverse('gracias'))
else:
form = Send2tcu(instance=phone)
return render(request, 'heroconfigurer/heroconfigurer.html', {'form': form})
答案 1 :(得分:1)
现有字段已被删除,因为您正在创建具有现有ID的新Phone
对象。您应该检索现有的Phone
模型并更新它:
phone_model = Phone.objects.get(id=1)
phone_model.num_calls = NumberOfCalls
phone_model.time_btwn_calls = TimeBetweenCalls
phone_model.psap = PSAP
phone_model.save()
或使用queryset update方法更新它:
Phone.objects.filter(id=1).update(
num_calls=NumberOfCalls,
time_btwn_calls=TimeBetweenCalls,
psap=PSAP,
)
第一个将触摸数据库两次。一旦加载现有手机,然后保存新值。第二个只触摸数据库一次,更新字段而不触及其余部分。