问题是当用户提交图片时我收到此错误。 我想我明白为什么我会收到这个错误,因为即使我选择了一个董事会,董事会保管箱也没有验证。
IntegrityError at /picture/
pet_picture.board_id may not be NULLRequest Method: POST
Request URL:
Django Version: 1.4.3
Exception Type: IntegrityError
Exception Value: pet_picture.board_id may not be NULL
Traceback:
File "C:\o\mysite\pet\views.py" in PictureCreator
106. picture = Picture.objects.create(user=request.user)
我认为问题出在我的PictureCreator函数的views.py
def PictureCreator(request):
if not request.user.is_authenticated():
return HttpResponseRedirect(reverse('pet.views.LoginRequest'))
if request.method == "POST":
form = PictureForm(request.POST , request.FILES)
if form.is_valid():
picture = Picture.objects.create(user=request.user)
picture.image = form.cleaned_data['image']
picture.description = form.cleaned_data['description']
picture.board = form.cleaned_data['board']
picture.save()
return render(request,'picture.html',{'form':PictureForm()})
我认为问题在这个特定的声明中它不对我的电路板保管箱有效。如何使其有效? picture.board = form.cleaned_data ['board']
我的forms.py部分
class PictureForm(forms.ModelForm):
board = forms.ModelChoiceField(queryset=Board.objects.all())
class Meta:
model = Picture
fields = ('image','description','board',)
我的models.py
from django.db import models
from django.db.models.signals import post_save
from django.contrib.auth.models import User
class Person(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
image = models.FileField(upload_to="images/",blank=True,null=True)
def __unicode__(self):
return self.name
class Picture(models.Model):
user = models.ForeignKey(User)
board = models.ForeignKey(Board)
image = models.FileField(upload_to="images/",blank=True,null=True)
description = models.TextField()
def __unicode__(self):
return self.description
我该如何解决这个问题?谢谢你帮助我:D
答案 0 :(得分:2)
picture = Picture(user=request.user)
picture.image = form.cleaned_data['image']
picture.description = form.cleaned_data['description']
picture.board = form.cleaned_data['board']
picture.save()
答案 1 :(得分:1)
看起来您的问题就在这一行:
picture = Picture.objects.create(user=request.user)
根据您的模型,创建Board
时需要Picture
。解决此问题的一种方法是将上述行更改为:
picture = Picture(user=request.user)
现在,您必须在视图中明确调用save
。