[英]User Specific Uploads Django 1.7
im getting this error "NOT NULL constraint failed: myfiles_document.user_id" what im trying to do is attach files to user ForeignKey so user can only see what they upload im using this app django-file-form here the code for the project 即时通讯收到此错误“ NOT NULL约束失败:myfiles_document.user_id”即时通讯试图做的是将文件附加到用户ForeignKey上,以便用户只能看到他们使用此应用程序django-file-form上传的即时通讯项目的代码
model.py model.py
class Example2(models.Model):
title = models.CharField(max_length=255)
class ExampleFile(models.Model):
fs = FileSystemStorage(location=settings.MEDIA_ROOT)
input_file = models.FileField(max_length=255, upload_to='uploads/%Y.%m.%d' , storage=fs)
user = models.ForeignKey('auth.User')
def get_upload_path(self,filename):
return "static/uploads/"+str(self.user.id)+"/"+filename
forms.py forms.py
class BaseForm(FileFormMixin, django_bootstrap3_form.BootstrapForm):
title = django_bootstrap3_form.CharField()
class MultipleFileExampleForm(BaseForm):
input_file = MultipleUploadedFileField()
def save(self):
example = Example2.objects.create(
title=self.cleaned_data['title']
)
for f in self.cleaned_data['input_file']:
ExampleFile.objects.create(
input_file=f
)
self.delete_temporary_files()
views.py views.py
class BaseFormView(generic.FormView):
template_name = 'example_form.html'
def get_success_url(self):
return reverse('example_success')
def form_valid(self, form):
form.save()
return super(BaseFormView, self).form_valid(form)
class ExampleSuccessView(generic.TemplateView):
template_name = 'success.html'
class MultipleExampleView(LoginRequiredMixin, BaseFormView):
form_class = forms.MultipleFileExampleForm
Your foreign key will not be automatically set to the current user unless you do it manually. 除非手动进行操作,否则您的外键不会自动设置为当前用户。 That's why you are getting the not-null constraint error.
这就是为什么您会收到非空约束错误的原因。 Try modifying your
form_valid
method like this: 尝试像这样修改
form_valid
方法:
def form_valid(self, form):
form.instance.user = self.request.user
...
Read Django's documentation on models and request.user for details. 阅读Django有关模型和request.user的文档以了解详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.