django:DoesNotExist at / accounts / profile / edit /

时间:2015-05-01 05:15:26

标签: python django python-2.7

继续在/ accounts / profile / edit /

获取DoesNotExist

我认为这个问题是因为新用户的RegisterTruckFrom是空的 - 还没有填补。

如何让此功能为新用户显示空白的新RegisterTruckFrom?

x

2 个答案:

答案 0 :(得分:0)

您可以简单地为request.method == GET编写代码:

if request.method == "GET":
  RegisterTruckForm()

并删除request.method == GET之前的代码,这是不必要的。

答案 1 :(得分:0)

您可以使用 instance = None 添加数据,使用 instance = object 编辑现有数据

@login_required
def profile_edit(request):
    try:     
        truck_name = Product.objects.get(user=request.user)
    except ObjectDoesNotExist:
        truck_name = None

    if request.method == 'GET':
        truck_form = RegisterTruckForm(instance=truck_name)
        return render(request, 'accounts/profile_edit.html'{'truck_form': truck_form})

    else:
        truck_form = RegisterTruckForm(
                         request.POST,request.FILES,instance=truck_name)
        if truck_form.is_valid():
            truck_name = truck_form.save(commit=False)
            truck_name.product = Product.objects.get(user=request.user)
            truck_form.save_m2m()
            truck_name.save()
            return HttpResponseRedirect('/accounts/profile')
        return render('accounts/profile_edit.html', {'truck_form': truck_form})