使用用户ID Django保存表单

时间:2018-07-17 15:10:28

标签: python django

为使问题简单,我有一个表格,用户可以将简历上传到数据库。

我的forms.py

class resume_upload(forms.ModelForm):
    cv = forms.FileField(required = True)
    job_title = forms.CharField(required = True)

    def save(self, commit=False):
       cvs = super(resume_upload, self).save(commit=False)
       cvs.cv = self.cleaned_data['cv']
       cvs.job_title = self.cleaned_data['job_title']

       if commit:
           cvs.save()


    class Meta:
        model = Cv
        fields = ('cv', 'job_title',)

我的模型。py

class Cv(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    cv = models.FileField(upload_to='cvs', default='', validators=[validate_file_extension])
    job_title = models.CharField(max_length=100, default='')

    def __str__(self):
        return self.job_title

和我的views.py

def upload_resume(request):
if request.method == 'POST':
    form = resume_upload(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        return redirect('/')
    else:
        messages.error(request,"Oops! That didn't work. Please try again")
else:
    form = resume_upload()
return render(request, 'upload_resume.html',{'form':form,})

问题是它重定向到主页,但是我无法在管理面板中找到对象

1 个答案:

答案 0 :(得分:4)

您正在像这样覆盖save方法,

 def save(self, commit=False):
   cvs = super(resume_upload, self).save(commit=False)
   cvs.cv = self.cleaned_data['cv']
   cvs.job_title = self.cleaned_data['job_title']

   if commit:
       cvs.save()

因此,您要传递一个可选参数commit,默认情况下该参数为False

如果要实际保存,则在调用save时需要提供一个True参数。

form.save(commit=True)

编辑

此外,您的代码似乎有问题。

def upload_resume(request):
    if request.method == 'POST':
        form = resume_upload(request.POST, request.FILES)
        if form.is_valid():
            cv_form = form.save() # commit is False in this case.
            cv_form.user = request.user
            form.save(commit=True)
            return redirect('/')
        else:
            messages.error(request,"Oops! That didn't work. Please try again")
    else:
        form = resume_upload()
    return render(request, 'upload_resume.html',{'form':form,})

基本上,这里是在将用户实际修补到数据库之前,先对其进行修补。这正是布尔开关commit的目的。

编辑2

要克服'NoneType' object has no attribute 'user'错误,您需要在save覆盖中添加此错误,以返回对象。

def save(self, commit=False):
   cvs = super(resume_upload, self).save(commit=False)
   cvs.cv = self.cleaned_data['cv']
   cvs.job_title = self.cleaned_data['job_title']

   if commit:
       cvs.save()

   return cvs