gpt4 book ai didi

python - 用户特定上传 Django 1.7

转载 作者:太空宇宙 更新时间:2023-11-03 17:51:06 24 4
gpt4 key购买 nike

我收到此错误“NOT NULL 约束失败:myfiles_document.user_id”我想做的是将文件附加到用户ForeignKey,以便用户只能看到他们使用此应用程序上传的内容django-file-form这里是项目的代码

模型.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

表单.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()

View .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

最佳答案

除非您手动设置,否则您的外键不会自动设置为当前用户。这就是您收到非空约束错误的原因。尝试修改您的 form_valid 方法,如下所示:

def form_valid(self, form):
form.instance.user = self.request.user
...

阅读Django's documentation on models and request.user 了解详情。

关于python - 用户特定上传 Django 1.7,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29063279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com