2

我有设置表单页面。如果用户填写了一次表格;它必须显示这些值。但是如果没有数据 [第一次] 我得到查询错误。我需要那个查询,因为表单数据必须写成与当前用户[登录]相关。

这是我的观点部分:

@login_required(login_url='/login/')
def profile_page(request,username):
    query = Profile.objects.get(owner__username = username) ##error!
    if request.method == 'POST':
        form = profile_form(request.POST,instance=query)
        form.save()
        return HttpResponseRedirect('/admin/')
    else:
        form = profile_form(instance=query)


    return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))

我想我需要检查模型,如果它是空的,我应该做一些不同的事情。

我被困住了。

谢谢

4

3 回答 3

4

您想使用.exists()queryset 选项

@login_required(login_url='/login/')
def profile_page(request,username):
    form = profile_form()
    if Profile.objects.get(owner__username = username).exists():
        query = Profile.objects.get(owner__username = username)
        if request.method == 'POST':
            form = profile_form(request.POST,instance=query)
            form.save()
            return HttpResponseRedirect('/admin/')
        else:
            form = profile_form(instance=query)

    return render_to_response('profile_save.html',{'form':form},context_instance = RequestContext(request))

有关详细信息,请参阅QuerytSet API 参考

于 2012-09-22T13:22:14.000 回答
0

您只需要将该get查询包装起来try ... except并将实例设置为无,就像这样。

from django.core.exceptions import ObjectDoesNotExist
@login_required(login_url='/login/')
def profile_page(request,username):
    try:
        query = Profile.objects.get(owner__username = username)

    #to be more specific you can except ProfileObjectDoesNotExist
    except ObjectDoesNotExist: 
        query = None  #Doesn't exist, set to None

    if request.method == 'POST':
        form = profile_form(request.POST,instance=query)
        form.save()
        return HttpResponseRedirect('/admin/')
    else:
        form = profile_form(instance=query)

    return render_to_response('profile_save.html',{'form':form},
                              context_instance = RequestContext(request))
于 2012-09-22T13:23:05.223 回答
0

我想我可能为此目的使用了 get_or_create 。

Profile.objects.get_or_create(owner__username = username)
于 2012-09-22T16:00:30.190 回答