我正在尝试保存模型的实例,但无济于事。
以下是我的模特;
class AudioFile(models.Model):
name = models.CharField(max_length=100,default='')
audio_file = models.FileField()
uploader = models.ForeignKey(User,default='')
def __unicode__(self):
return self.name
我有以下表格;
class AudioFileForm(forms.ModelForm):
class Meta:
model = AudioFile
fields = ['name', 'audio_file']
def clean_audio_file(self):
audio = self.cleaned_data['audio_file']
if audio:
if audio._size > 5*1024*1024:
raise ValidationError("File too large ( > 5mb )")
if os.path.splitext(audio.name)[1] != ".mp3":
raise ValidationError("We only support mp3!")
return audio
else:
raise validationError("Couldn't read uploaded file")
我有以下视图来处理提交的表格;
form = AudioFileForm(request.POST, request.FILES)
if form.is_valid():
form.cleaned_data['uploader'] = request.user //view requires login
form.save()
return HttpResponseRedirect(
reverse('home_audio',kwargs={'pk':audio_file.pk})
)
else:
return HttpResponse(form.errors)
但是在提交时我得到了错误; IntegrityError at /uploadaudio
NOT NULL constraint failed: stationrunner_audiofile.uploader_id
/uploadaudio
是与视图对应的网址,stationrunner
是我应用的名称。
有人请帮忙。
答案 0 :(得分:4)
尝试更改视图:
form = AudioFileForm(request.POST, request.FILES)
if form.is_valid():
audio_file = form.save(commit=False) // This will not hit the database, and no IntegrityError will be raised
audio_file.uploader = request.user // Tack on the user,
audio_file.save()
return HttpResponseRedirect(
reverse_lazy('home_audio',kwargs={'pk':audio_file.pk}) // Use reverse lazy to prevent circular import issues.
)
else:
return HttpResponse(form.errors)
此外,您可以解决该模型的一些问题:
from django.conf import settings
from django.db import models
class AudioFile(models.Model):
name = models.CharField(max_length=100) // If the field is not allowed to be blank, the default blank does not make sense.
audio_file = models.FileField(upload_to="audio_files") // Without this parameter file field does not work.
uploader = models.ForeignKey(settings.AUTH_USER_MODEL) // This should reference the user model declared in your settings file.
def __unicode__(self):
return self.name