保存的模型为无

时间:2018-03-16 19:24:01

标签: django views

所以我有一个模型,我正在尝试使用成功提交的表单进行保存,但在Admin中,对象值为None。我知道问题出在视图中,但我无法弄清楚。这是我的代码:

Views.py

def profilecreate(request):
    if request.method == 'GET':
        form = ProfileForm()
    else:
        form = ProfileForm(request.POST)
        if form.is_valid():
            description = form.cleaned_data['description']
            caption= form.cleaned_data['caption']
            photo = form.cleaned_data['photo'] 
            profile = Profile.objects.create(description=description, caption=caption, photo=photo)
            return HttpResponseRedirect(reverse('profile-id', kwargs={'profile_id': profile.id}))

        return render(request, 'profile_form.html', {'form': form})

有人请协助

第二次查看尝试

def profilecreate(request):
  # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = ProfileForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            photo = form.cleaned_data['photo']
            description = form.cleaned_data['description']
            caption = form.cleaned_data['caption']
            form.save(commit=True)

            return HttpResponseRedirect('/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = ProfileForm()

    return render(request, 'profile_form.html', {'form': form})      

0 个答案:

没有答案