如何在Django中上传图像

时间:2022-04-05 03:41:11

I'm creating a new app in django environment. I want to upload image of user when he/she sign-up's in my app and i want to use the same image when he/she posts any comment in my app. So how to integrate image-uploading code into my app code?

我正在django环境中创建一个新的应用程序。我想在他/她在我的应用程序中注册时上传用户的图像,并且当他/她在我的应用程序中发布任何评论时我想使用相同的图像。那么如何将图像上传代码集成到我的应用代码中呢?

1 个解决方案

#1


1  

You should be using UserProfile as has been answered here Django user profile and have the ImageField in there.

您应该使用UserProfile,因为这里已经回答了Django用户配置文件,并在那里有ImageField。

Then create a ModelForm for the UserProfile and render it wherever you want the user to setup their profile and add a user image. The Model form will render the ImageField as a file upload field and have default handles for it. Make sure you have MEDIA_URL configured in your settings.py. You would also need PIL installed in your path for the image upload to work.

然后为UserProfile创建一个ModelForm,并将其呈现在您希望用户设置其配置文件并添加用户图像的任何位置。 Model表单将ImageField呈现为文件上载字段,并具有默认句柄。确保在settings.py中配置了MEDIA_URL。您还需要在路径中安装PIL才能使图像上传生效。

You can access the UserProfile instance for your user doing user.get_profile in your templates and as a callable elsewhere.

您可以为模板中的user.get_profile和其他地方的callable访问UserProfile实例。

#1


1  

You should be using UserProfile as has been answered here Django user profile and have the ImageField in there.

您应该使用UserProfile,因为这里已经回答了Django用户配置文件,并在那里有ImageField。

Then create a ModelForm for the UserProfile and render it wherever you want the user to setup their profile and add a user image. The Model form will render the ImageField as a file upload field and have default handles for it. Make sure you have MEDIA_URL configured in your settings.py. You would also need PIL installed in your path for the image upload to work.

然后为UserProfile创建一个ModelForm,并将其呈现在您希望用户设置其配置文件并添加用户图像的任何位置。 Model表单将ImageField呈现为文件上载字段,并具有默认句柄。确保在settings.py中配置了MEDIA_URL。您还需要在路径中安装PIL才能使图像上传生效。

You can access the UserProfile instance for your user doing user.get_profile in your templates and as a callable elsewhere.

您可以为模板中的user.get_profile和其他地方的callable访问UserProfile实例。