我正在使用django创建图像上传功能。 但是,它没有上传。 我不知道代码错误,所以我想告诉你。 我尝试了各种方法,但是如果我为imagefiled指定默认值, 默认值将被应用。
#form
class RecordCreateForm(BaseModelForm):
class Meta:
model = URC
fields = ('image','UPRC','URN',)
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(RecordCreateForm,self).__init__(*args, **kwargs)
self.fields['URN'].queryset = UPRM.objects.filter(user=user)
#view
class RecordCreate(CreateView):
model = URC
form_class = RecordCreateForm
template_name = 'records/urcform.html'
success_url = reverse_lazy('person:home')
def get_form_kwargs(self):
kwargs = super(RecordCreate, self).get_form_kwargs()
# get users, note: you can access request using: self.request
kwargs['user'] = self.request.user
return kwargs
def form_valid(self, form):
user = self.request.user
form.instance.user = user
form.instance.group = belong.objects.get(user=user).group
return super().form_valid(form)
#model
def get_upload_path(instance, filename):
n = datetime.now()
prefix = "records/"
ymd='/'.join([n.strftime('%Y'), n.strftime('%m'), n.strftime('%d'), ""]) + "/"
directory=str(instance.user.id) + "/"
name=str(uuid.uuid4()).replace("-", "")
extension=os.path.splitext(filename)[-1]
return ''.join([prefix, directory, ymd, name, extension])
class URC(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
group = models.ForeignKey(group, on_delete=models.CASCADE, null=True)
URN = models.ForeignKey(UPRM, on_delete=models.CASCADE)
UPRC = models.CharField(max_length=300)
image = models.ImageField(upload_to=get_upload_path)
def __str__(self):
return self.UPRC
#urls
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我将发布任何其他必要的代码。 对不起,英语不好。
后记
页面被重定向,没有任何错误显示。 但是管理员屏幕可以上传。
class BaseModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super(BaseModelForm, self).__init__(*args, **kwargs)
#template
<form method="post" action="">
{% csrf_token %}
{{form.image.label_tag}}
{{form.image}}
{{form.UPRC.label_tag}}
{{form.UPRC}}
{{form.URN.label_tag}}
{{form.URN}}
<input class="btn btn-primary" type="submit" value="submit">
</form>
答案 0 :(得分:1)
您的<form>
标记缺少enctype
,如here所述:
<form method="post" enctype="multipart/form-data">
答案 1 :(得分:-1)
您可以看一下此示例。 https://www.pythonsetup.com/simple-file-uploads-django-generic-createview/
def form_valid(self, form):
self.object = Author(photo=self.get_form_kwargs().get('files')['photo'])
self.object = form.save()
return HttpResponseRedirect(self.get_success_url())