以django形式传递对象列表

时间:2018-03-22 11:06:05

标签: django python-3.x django-models django-forms django-templates

 try:
     degree = get_list_or_404(Degree,education__user__username=username)
except Http404:
     degree = Degree()

将包含多个对象,其中包含用户的所有教育详细信息。现在我想将此degree object发送给表单。我知道如何传递一个对象实例。

views.py

   def profile_edit(request,username):
    profile_edit = get_object_or_404(User,username=username)
    try:
        userprofile  = get_object_or_404(UserProfile,user__username=username)
    except Http404:
        userprofile = UserProfile()
   # education = Education.objects.filter(user__username=username)
    try:
        # wanna send this in template
        degree = get_list_or_404(Degree,education__user__username=username)
    except Http404:
        degree = Degree()
    if request.user == profile_edit and request.user.is_authenticated:
        if request.method == "POST":
            form = EditForm(request.POST,instance=profile_edit)
            form1 = EditForm1(request.POST,instance=userprofile)
            form2 = EditForm2(request.POST,instance=degree) # how to pass degree ?
            if form.is_valid() and form1.is_valid() and form2.is_valid():
                form.save()
                form1.save()
                form2.save()
                return redirect('profile_edit',username=username)
        else:
            form = EditForm(instance=profile_edit)
            form1 = EditForm1(instance=userprofile)
            form2 = EditForm2(instance=degree)
        context = {'form':form,'form1':form1,'form2':form2}
        return render(request,'userprofile/profile_edit.html', context)
    else:
        raise PermissionDenied

forms.py : -

class EditForm2(forms.ModelForm):
    class Meta:
        model = Degree
        fields = ('degree','major','passing_year','college',)

0 个答案:

没有答案