无法将所有者作为我的模型的外键 - django

时间:2017-08-22 16:42:34

标签: django

我正在尝试做一个表单,以便用户可以上传视频,问题是我无法获取当前用户或者我的视频模型上的外键ID

错误:IntegrityError 例外值:(1048,“列'owner_id'不能为空”)

我怎么能解决这个问题,我看了django文档,但找不到答案。

我的models.py:

class Videowtm(models.Model):
      name = models.CharField(max_length=50, blank=True)
      description = models.CharField(max_length=255, blank=True)
      uploaded_at = models.DateTimeField(auto_now_add=True)
      owner = models.ForeignKey(User)
      video = models.FileField(upload_to='videos/')

我的forms.py:

class VideowtmForm(forms.ModelForm):
class Meta:
    model = Videowtm
    fields = ('name', 'description', 'video', )

我的观点:

@login_required
def model_form_upload(request):
    if request.method == 'POST':
       form = VideowtmForm(request.POST, request.FILES)
       form.owner = request.user
       if form.is_valid():
          form.save()
          return redirect('home')
    else:
       form = VideowtmForm()
    return render(request, 'model_form_upload.html', {
    'form': form
    })

1 个答案:

答案 0 :(得分:3)

试试这个:

首先向模型中的所有者添加blank=True

###如果您不在表单字段中包含它,则不需要这样做###

class Videowtm(models.Model):
    name = models.CharField(max_length=50, blank=True)
    description = models.CharField(max_length=255, blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)
    owner = models.ForeignKey(User, blank=True)
    video = models.FileField(upload_to='videos/')

然后:

<强> views.py:

@login_required
def model_form_upload(request):
    if request.method == 'POST':
       form = VideowtmForm(request.POST, request.FILES)
       if form.is_valid():
          video = form.save(commit=False)
          video.owner = request.user
          video.save()
          return redirect('home')
    else:
       form = VideowtmForm()
    return render(request, 'model_form_upload.html', {
    'form': form
    })