django: DoesNotExist at / accounts / profile / edit /

advertisements

Keep getting DoesNotExist at /accounts/profile/edit/

I think the issue because a new user's RegisterTruckFrom is empty - hasn't been filled yet.

How do I get this function to display a blank new RegisterTruckFrom for the new user?

@login_required
def profile_edit(request):
    truck_name = Product.objects.get(user=request.user)
    try:
        truck_form = RegisterTruckForm(instance=truck_name)

    except ObjectDoesNotExist:
        truck_form = RegisterTruckForm()

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

    elif request.method == 'POST':
        if truck_name is not None:
           truck_form = RegisterTruckForm(request.POST, request.FILES,instance=truck_name)
        else:
           truck_form = RegisterTruckForm(request.POST, request.FILES)

        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_to_response('accounts/profile_edit.html', {'truck_form': truck_form}, context_instance=RequestContext(request))


You can simply write your code like this for request.method == GET:

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

and remove the code before request.method == GET, this is unnecessary.