Django UserProfile表单

时间:2014-03-24 01:07:23

标签: python django

我有一个Django表单,允许用户保存他们的UserProfile详细信息,但它只允许这种情况发生一次。鉴于额外的保存请求创建新条目,但我在用户字段和用户UserProfile字段之间存在一对一的关系。

创建用户时,不会创建UserProfile条目。相反,在填写这些详细信息之前,他们无法访问他们的帐户。

当学生第二次访问表单时,我想用现有数据预先填充表单。

def student_details(request):
    #this is a form
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = DetailsForm(request.user, request.POST, request.FILES)
            if form.is_valid():
                note = form.save(commit=False)
                note.user = request.user
                note.completed_form = True
                note.save()
                return HttpResponseRedirect('/student-portal/')
        else:
            if request.user.get_profile():
                pass
                form = DetailsForm(request.user)
            else:
                form = DetailsForm(request.user)
        return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
    return HttpResponseRedirect('/')

1 个答案:

答案 0 :(得分:0)

对不起,伙计们刚刚发现了如何做到这一点:

def student_details(request):
    #this is a form
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = DetailsForm(request.user, request.POST, request.FILES)

            if form.is_valid():
                note = form.save(commit=False)
                user_profile = UserProfile.objects.get(user=request.user)
                if user_profile:
                    note.id = user_profile.id
                note.user = request.user
                note.completed_form = True
                note.save()
                return HttpResponseRedirect('/student-portal/')
        else:
            try:
                user_profile = UserProfile.objects.get(user=request.user)
                form = DetailsForm(request.user, instance=user_profile)
            except:
                form = DetailsForm(request.user)
        return render_to_response("student-details.html", {'form': form}, context_instance=RequestContext(request))
    return HttpResponseRedirect('/')

这里的想法是查询链接到该用户的user_profile是否已经存在,然后指定该条目的ID。