我正在寻找一个在Django上进行公开简介的教程,但是我对ClaerableFileInput有麻烦。
没有清除图像,我也不知道为什么。
让我告诉您代码:
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to='profiles', null=True)
empresa = models.CharField(max_length=200, null=True, blank=True)
area = models.CharField(max_length=200, null=True, blank=True)
forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['avatar','empresa','area']
widgets = {
'avatar': forms.ClearableFileInput(attrs={'class':'form-control-file mt-3'}),
'empresa': forms.TextInput(attrs={'class':'form-control-file mt-3', 'placeholder':'Empresa'}),
'area': forms.TextInput(attrs={'class':'form-control-file mt-3', 'placeholder':'Area'}),
}
views.py
@method_decorator(login_required, name='dispatch')
class ProfileUpdate(UpdateView):
form_class = ProfileForm
success_url = reverse_lazy('profile')
template_name = "registration/profile_form.html"
def get_object(self):
profile, created = Profile.objects.get_or_create(user=self.request.user)
return profile
profile_form.html
{% extends 'core/base.html' %}
{% load static %}
{% block title %}Perfil{% endblock %}
{% block content %}
<style>.errorlist{color:red;} label{display:none}</style>
<main role="main">
<div class="container">
<div class="row mt-3">
<div class="col-md-9 mx-auto mb-5">
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{form.as_p}}
</form>
</div>
</div>
</div>
</main>
{% endblock %}
渲染
<div class="container">
<div class="row mt-3">
<div class="col-md-9 mx-auto mb-5">
<form action="" method="post" enctype="multipart/form-data"><input type="hidden" name="csrfmiddlewaretoken" value="H1BbxtduaemnAyRktgLpZizjuEbxjOUFu9A7g3Tl1pQb6THvLFoWcLE3fhWvCycu">
<p><label for="id_avatar">Avatar:</label> Actualmente: <a href="/media/profiles/Rami_Oli.png">profiles/Rami_Oli.png</a><br>
Modificar:
<input type="file" name="avatar" class="form-control-file mt-3" accept="image/*" id="id_avatar"></p>
<p><label for="id_empresa">Empresa:</label> <input type="text" name="empresa" class="form-control-file mt-3" placeholder="Empresa" maxlength="200" id="id_empresa"></p>
<p><label for="id_area">Area:</label> <input type="text" name="area" class="form-control-file mt-3" placeholder="Area" maxlength="200" id="id_area"></p>
</form>
</div>
</div>
</div>
花时间阅读