我的问题是我如何在Django中使用相同的模板和相同的格式保存和显示图像。
模型
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,))
模板
<form style="padding-left: 15px; padding-right:15px;" method="POST" enctype='multipart/form-data'>
{{ form.errors }}
{% csrf_token %}
<h7>Note: Everything added in this section will be public.</h7>
<hr>
<br>
<h3>Profile picture</h3>
<hr>
<div style="text-align:center;" class="row">
<div style="text-align:center;" class="col-lg-12">
<div class="container_image">
<div class="avatar-upload-image">
<div class="avatar-edit-image">
<input type='file' id="imageUpload" name="image" accept=".png, .jpg, .jpeg" />
<label for="imageUpload"></label>
</div>
<div class="avatar-preview">
<div id="imagePreview">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="form-group">
<div class="field">
<label>Full Name<span class="red-txt">*</span></label>
<!-- <input class="form-control" type="text" name="full_name" value="{{ full_name }}" maxlength="60" size="50"> -->
{{ form.full_name }}
</div>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<div class="field">
<label>Email<span class="red-txt">*</span></label>
{{ form.profile_email }}
</div>
</div>
</div>
</form>
JS
function read_profile_image_url(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imagePreview').css('background-image', 'url('+e.target.result +')');
$('#imagePreview').hide();
$('#imagePreview').fadeIn(650);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imageUpload").change(function() {
read_profile_image_url(this);
});