NOT NULL约束失败:instashot_data.user_id

时间:2019-06-14 09:37:07

标签: django django-models django-forms django-views

我正在渲染表单,并且在提交该表单时出现此错误

IntegrityError NOT NULL约束失败:instashot.user_id

models.py

class data(models.Model):
 description = models.CharField(max_length=400)
 user = models.ForeignKey(User,on_delete=models.CASCADE)
 img = models.ImageField(upload_to='images/')

form.py

class info(forms.ModelForm):

 class Meta:
    model = data
    fields = ['description','img', ]

views.py

def detail(request, template_name='website.html'):
 if request.method == 'POST':
    form = info(request.POST, request.FILES)

    if form.is_valid():
        form.save()
 else:
    form = info()
 return render(request, template_name, {'form': form})

.html

<div class="container">
 <div class="jumbotron">
  <form method="post" enctype="multipart/form-data">        
   {% csrf_token %}
      {{ form.as_p }}





    <button type="submit">Upload</button>       
  </form>
 </div>
</div>

我不知道为什么会出现这个错误

1 个答案:

答案 0 :(得分:0)

尝试

def detail(request, template_name='website.html'):
    if request.method == 'POST':
        form = info(request.POST, request.FILES)

        if form.is_valid():
            new_form = form.save(commit=False)
            new_form.user = request.user
            new_form.save() 
    else:
        form = info()
    return render(request, template_name, {'form': form})