Django编辑模型实例

时间:2017-07-26 18:16:53

标签: python django

我正在处理的Django项目列出了患者详细信息,并允许用户编辑详细信息。我已经能够列出它,但views.py没有链接到更新列表的URL。

views.py

    def update_patient(request, patient_id):
        patient = Patient.objects.get(id=patient_id)
        if request.method != 'POST':
            form = PatientForm(instance=patient)
        else:
            # POST data submitted; process data.
            form = PatientForm(instance=patient, data=request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('patient:patient',
                                            args=[patient.id]))
    context = { 'patient': patient, 'form': form}
    return render(request, 'patient/update_patient.html', context)

models.py

  class Patient(models.Model):
      patientID = models.CharField(max_length=20)
      firstName =models.CharField(max_length=20)
      lastName = models.CharField(max_length=20)
      age = models.IntegerField(max_length=None)
      SSN = models.CharField(max_length=15)
      address = models.CharField(max_length=200)
      date_added = models.DateTimeField(auto_now_add=True)

urls.py

url(r'^patients/(?P<patient_id>\update\d+)/$', views.update_patient, name='update'),

update_patient.html

{% extends "patient/base.html" %} {% block content %}
  <p><a href="{% url 'patient:patient' patient.id %}">{{ patient }}</a>
  </p>
  <p>Update Patient:</p>

  <form action="{% url 'patient:update' patient.id %}" method='post'>
   {% csrf_token %} {{ form.as_p }}
  <button name='submit'>add entry</button>
  </form>
{% endblock content %}

1 个答案:

答案 0 :(得分:0)

您的网址格式错误,您在捕获组中有\update,它不应该是,将模式更改为:

url(r'^patients/(?P<patient_id>\d+)/update/$', views.update_patient, name='update')