将ImageField保存在UpdateView Django中

时间:2019-03-24 17:23:44

标签: javascript python html django

  • 我的个人资料模型中有一个图像字段。
  • 我无法从模板保存图像。
  • 尝试使用django admin保存图像,它成功保存了 图片并在更新视图中显示图片。

如何从前端而不是从django admin保存图像?

模型

class Profile(models.Model):
    image         = models.ImageField(upload_to='profile_images', null=True, blank=True)
    profile_email = models.CharField(max_length=30, null=True, blank=True)
    biography     = models.CharField(max_length=700, null=True, blank=True)

查看

class ProfileSettingsView(UpdateView):
    model = Profile
    form_class = ProfileSettingsForm
    pk_url_kwarg = 'pk'
    context_object_name = 'object'
    template_name = 'profile_settings.html'

    def get_success_url(self):
          return reverse_lazy('users:profile_settings', args = (self.object.id,))

模板

{% if object.image %}
<a href=""><img style="border-radius:50%; text-align:center; margin-bottom: 20px; border: 2px solid #00a6eb;" class="center" src="{{ object.image.url }}"alt=""></a>
{% endif %}

<label style="display: inline-block" for="file-upload" class="custom-file-upload">
    <i class="fa fa-cloud-upload"></i> Upload Photo
</label>
<input id="file-upload" name="image" onchange="this.form.submit()" type="file"/>

网址

urlpatterns = [
    path('users/', include('users.urls', namespace='users')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

设置

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

表格

class ProfileSettingsForm(forms.ModelForm):

    class Meta:
        model = Profile

        fields = ['image','full_name','biography','profile_email','linked_in','facebook',
                  'twitter','phone','education']

        widgets = {
            'image'          : forms.TextInput({'class': 'form-control'}),
            'full_name'      : forms.TextInput({'class': 'form-control'}),
            'profile_email'  : forms.TextInput(attrs={'readonly': True}),
            'biography'      : forms.Textarea({'rows':'10'}),
            'twitter'        : forms.TextInput({'class': 'form-control'}),
            'linked_in'      : forms.TextInput({'class': 'form-control'}),
            'facebook'       : forms.TextInput({'class': 'form-control'}),
            'phone'          : forms.TextInput({'class': 'form-control'}),
        }

1 个答案:

答案 0 :(得分:1)

将图片窗口小部件更改为FileInput

widgets = {
    'image' : forms.FileInput(attrs={'class': 'input-image-control'}),
    ...