图像上传字段在Django中不起作用

时间:2021-09-09 02:49:58

I am trying to render a form which will upload image. But I am not getting it.

我正在尝试渲染一个将上传图像的表单。但我没有得到它。

Here models.py:

profile_picture = models.ImageField(_('profile picture'),upload_to="profile_pictures" , blank=True, null=True,default="static/images/person.jpg")

in forms.py:

class UploadProfilePictureForm(forms.Form):
    profile_picture=forms.ImageField(label='Select an Image')

in views.py:

def add_profile_picture(request):
if request.method=='POST':
    form=UploadProfilePictureForm(request.POST,request.FILES)
    p=FearUser(profile_picture=request.FILES['profile_picture'])
    p.save()
    return HttpResponseRedirect(reverse('profile:my_profile'))
else:
    form=UploadProfilePictureForm
return render_to_response('partials/_add_profile_picture.html',{'form':form},context_instance=RequestContext(request))

in urls.py:

url(r'^profile/update-pp/$','profiles.views.add_profile_picture',name='pp_update')

finally in _add_profile_picture.html:

最后在_add_profile_picture.html中:

            <form action="{% url 'profile:pp_update' %}" role="form" method="post" enctype="multipart/form-data">
                {% csrf_token %}

                <p>{{ form.profile_picture.label_suffix }}</p>
                <p>
                    {{ form.profile_picture.error_messages }}
                    {{ form.profile_picture }}
                </p>
                <div class="text-right">
                    <button type="button" class="btn btn-default custom_btn cancel_btn"
                            style="padding:5px 20px" data-dismiss="modal">Cancel
                    </button>
                    <button type="submit" class="btn btn-default custom_btn submit_btn"
                            style="padding:5px 20px">Submit
                    </button>
                </div>
            </form>

Can anyone explain me what I have done wrong?

谁能解释一下我做错了什么?

4 个解决方案

#1


0  

Without some more specific debugging info from you I cannot be entirely sure what you mean by "not getting it".

如果没有您的某些更具体的调试信息,我无法完全确定您的意思是“没有得到它”。

Some things you might try:

你可能尝试的一些事情:

1) Actually validate the form (good practice).

1)实际验证表格(良好做法)。

2) Pull the image from the validated form. (also good practice).

2)从验证表格中提取图像。 (也是很好的做法)。

if form.is_valid():
    form = UploadProfilePictureForm(request.POST, request.FILES)
    p = FearUser(profile_picture=form.cleaned_data['profile_picture'])
    p.save()

To help debug any actual image uploading issues, put in a print statement after the save like so:

为了帮助调试任何实际的图像上传问题,请在保存后输入print语句,如下所示:

print p.profile_picture.url and see what that outputs. If it's None, or not what you expect, than something is not right with your saving.

打印p.profile_picture.url并查看输出内容。如果它是无,或不是你所期望的,那么你的储蓄就不对了。

You can also print request.FILES and make sure the actual upload is working.

您还可以打印request.FILES并确保实际上传正常。

If you comment with the results I can try to help narrow it down.

如果您对结果发表评论,我可以尝试帮助缩小范围。

#2


0  

Dou you have Pillow installed?

你有枕头安装吗?

#3


0  

Because you haven't used form.is_valid() your form is unbound and form.cleaned_data does not exist. Once you run form.is_valid() only then will you have access to cleaned_data.

因为您尚未使用form.is_valid(),所以表单未绑定且form.cleaned_data不存在。一旦运行form.is_valid(),您就可以访问cleaning_data。

#4


0  

Most likely your problems belong to wrong settings inside your settings.py. This is what I have in my project, which is working, try to replicate it, and try in the admin first if it's working. At least we will know if the problem is in your settings/model or in your view.

您的问题很可能属于settings.py中的错误设置。这就是我在我的项目中所拥有的,它正在工作,尝试复制它,并且如果它正在工作则首先尝试管理员。至少我们会知道问题是在您的设置/模型中还是在您的视图中。

Create the path appdirectory/static/images, cause not sure if Django is creating it in case doesn't exists.

创建路径appdirectory / static / images,导致不确定Django是否创建它以防不存在。

settings.py

PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()

add in 'django.contrib.staticfiles' in your installed apps.

在已安装的应用中添加'django.contrib.staticfiles'。

models.py

   Pic = models.ImageField(upload_to='images/WaterMeterPictures/', blank=False, null=False) 

Once you get the admin working fine, the form generation should be straight forward.

一旦你使管理员工作正常,表单生成应该是直截了当的。

#1


0  

Without some more specific debugging info from you I cannot be entirely sure what you mean by "not getting it".

如果没有您的某些更具体的调试信息,我无法完全确定您的意思是“没有得到它”。

Some things you might try:

你可能尝试的一些事情:

1) Actually validate the form (good practice).

1)实际验证表格(良好做法)。

2) Pull the image from the validated form. (also good practice).

2)从验证表格中提取图像。 (也是很好的做法)。

if form.is_valid():
    form = UploadProfilePictureForm(request.POST, request.FILES)
    p = FearUser(profile_picture=form.cleaned_data['profile_picture'])
    p.save()

To help debug any actual image uploading issues, put in a print statement after the save like so:

为了帮助调试任何实际的图像上传问题,请在保存后输入print语句,如下所示:

print p.profile_picture.url and see what that outputs. If it's None, or not what you expect, than something is not right with your saving.

打印p.profile_picture.url并查看输出内容。如果它是无,或不是你所期望的,那么你的储蓄就不对了。

You can also print request.FILES and make sure the actual upload is working.

您还可以打印request.FILES并确保实际上传正常。

If you comment with the results I can try to help narrow it down.

如果您对结果发表评论,我可以尝试帮助缩小范围。

#2


0  

Dou you have Pillow installed?

你有枕头安装吗?

#3


0  

Because you haven't used form.is_valid() your form is unbound and form.cleaned_data does not exist. Once you run form.is_valid() only then will you have access to cleaned_data.

因为您尚未使用form.is_valid(),所以表单未绑定且form.cleaned_data不存在。一旦运行form.is_valid(),您就可以访问cleaning_data。

#4


0  

Most likely your problems belong to wrong settings inside your settings.py. This is what I have in my project, which is working, try to replicate it, and try in the admin first if it's working. At least we will know if the problem is in your settings/model or in your view.

您的问题很可能属于settings.py中的错误设置。这就是我在我的项目中所拥有的,它正在工作,尝试复制它,并且如果它正在工作则首先尝试管理员。至少我们会知道问题是在您的设置/模型中还是在您的视图中。

Create the path appdirectory/static/images, cause not sure if Django is creating it in case doesn't exists.

创建路径appdirectory / static / images,导致不确定Django是否创建它以防不存在。

settings.py

PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = path.join(PROJECT_ROOT, 'static').replace('\\', '/')
STATIC_URL = '/static/'
STATICFILES_DIRS = ()

add in 'django.contrib.staticfiles' in your installed apps.

在已安装的应用中添加'django.contrib.staticfiles'。

models.py

   Pic = models.ImageField(upload_to='images/WaterMeterPictures/', blank=False, null=False) 

Once you get the admin working fine, the form generation should be straight forward.

一旦你使管理员工作正常,表单生成应该是直截了当的。