查看错误没有返回HttpResponse对象

时间:2014-03-18 19:12:41

标签: django django-models django-views

我正在为django中的一个视图工作,我目前正在处理一个模型表单:我检查学生是否已经创建,如果它已创建,我将只更新该学生的信息,并在必要时添加条目到某个事件;如果没有,我创建一个学生并添加事件入口。

网页在我创建新学生的情况下运行正常,除了第一次尝试之外,但是当我尝试让学生已经存在时,该页面给出了错误,我没有返回HttpResponse对象。你能帮帮我吗?

def reserve(request, event_id):
  event = get_object_or_404(Event, pk=event_id)

  if request.method == 'POST':
    form = StudentForm(request.POST)

    if form.is_valid():
      try:
        student = Student.objects.filter(UID=form.cleaned_data['UID'])
        #student.first_name=form.cleaned_data['first_name']
        #student.last_name=form.cleaned_data['last_name']
        msg = 'Student found, added to reserve for this event!'
      except Student.DoesNotExist:
        student = Student.objects.create(UID=form.cleaned_data['UID'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
        msg = 'Contact created, reserve successful!'

      obj, created = Reservetoevent.objects.get_or_create(m_event=event, m_student = student)
    return render(request, 'events/reserve.html', {
      'form': form,
      'event': event,
      'msg': msg,
    }) 
  else:
    form = StudentForm()


    return render(request, 'events/reserve.html', {
      'form': form,
      'event': event,
    }) 

1 个答案:

答案 0 :(得分:0)

您的form.is_valid():是假的。因为你在那里的最后一次返回是else(意思是request.method ==" GET"),所以没有回应。 将你的最后一个回归移到左边。这应该解决它。但它无法解决您的表单无效的原因。

def reserve(request, event_id):
  event = get_object_or_404(Event, pk=event_id)

  if request.method == 'POST':
    form = StudentForm(request.POST)

    if form.is_valid():
      try:
        student = Student.objects.filter(UID=form.cleaned_data['UID'])
        #student.first_name=form.cleaned_data['first_name']
        #student.last_name=form.cleaned_data['last_name']
        msg = 'Student found, added to reserve for this event!'
      except Student.DoesNotExist:
        student = Student.objects.create(UID=form.cleaned_data['UID'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'])
        msg = 'Contact created, reserve successful!'

      obj, created = Reservetoevent.objects.get_or_create(m_event=event, m_student = student)
    return render(request, 'events/reserve.html', {
      'form': form,
      'event': event,
      'msg': msg,
    }) 
  else:
    form = StudentForm()


return render(request, 'events/reserve.html', {
  'form': form,
  'event': event,
})