无法改变模型实例

时间:2016-11-29 05:26:23

标签: django django-models

views.py

def patient_num(request):
    if request.method == 'POST':
        form = EditToBeSaveForm(request.POST)
        if form.is_valid():
            num = form.cleaned_data['病人编号']
            new_p = Patient.objects.get(p_number=num)
            if new_p:
                new_p.p_name = form.cleaned_data['姓名']
                new_p.p_sex = form.cleaned_data['性别']
                new_p.p_age = form.cleaned_data['年龄']
                new_p.p_tel_number = form.cleaned_data['电话号码']
                new_p.save()
                return render(request, 'polls/patient_edit.html')
    else:
        form = EditToBeSaveForm()
        return render(request, 'polls/patient_num.html', {'form': form})

models.py

class Patient(models.Model):
    sex_choice = (
        ('男', '男'),
        ('女', '女'),
    )
    p_name = models.CharField(max_length=100, default='template')
    p_age = models.IntegerField(default=0)
    p_number = models.IntegerField(default=0)
    p_tel_number = models.IntegerField(default=0)
    p_sex = models.CharField(choices=sex_choice, max_length=2, default='男')

forms.py

class EditForm(forms.Form):
    病人编号 = forms.IntegerField()


class EditToBeSaveForm(forms.Form):
    sex_choice = (
        ('male', '男'),
        ('female', '女'),
    )
    病人编号 = forms.IntegerField(label='你要修改的病人编号')
    姓名 = forms.CharField(max_length=100)
    年龄 = forms.IntegerField()
    电话号码 = forms.IntegerField()
    性别 = forms.ChoiceField(choices=sex_choice)

填充表单并提交后,视图没有更新数据库实例,为什么?

我可以在shell中一个接一个地做到这一点。

update in shell

新的混淆!当我用无效值填充表单时,例如,不存在Patient对象的id,它仍会呈现模板,为什么?

3 个答案:

答案 0 :(得分:0)

在我看来,您的问题是您永远无法访问if form.is_valid()视图的patient_num下的代码。尝试在if form.is_valid()子句后添加一些打印件,并确保您的表单有效。如果您的表单无效,则预计您的模型不会更新。

答案 1 :(得分:0)

您的问题是,您正在将request传递给request.POST

form = EditToBeSaveForm(request.POST) 

答案 2 :(得分:0)

我把一些'印刷品'放在我的视野中并且让人感到震惊......

def patient_num(request):
    print(111)
    if request.method == 'POST':
        print(2222)
        form = EditToBeSaveForm(request.POST)
        if form.is_valid():
            print(3333)
            num = form.cleaned_data['病人编号']
            new_p = Patient.objects.get(p_number=num)
            if new_p:
                print(4444)
                new_p.p_name = form.cleaned_data['姓名']
                new_p.p_sex = form.cleaned_data['性别']
                new_p.p_age = form.cleaned_data['年龄']
                new_p.p_tel_number = form.cleaned_data['电话号码']
                new_p.save()
                return render(request, 'polls/patient_edit.html')
    else:
        form = EditToBeSaveForm()
        return render(request, 'polls/patient_num.html', {'form': form})

我只能在shell输出中看到111.看来该视图甚至没有收到post请求。我检查我的html文件并找到问题。表单的目的地直接指向另一个视图函数......就这样了愚蠢,我很抱歉浪费你的时间!