'how to keep current image file on update form django
I am making an updated profile page that concludes by changing the picture, name, and email. every time I tried to change email or name without changing the picture, it erase the picture column.
How can I prevent this to happen?
I've tried to put a value on the input file, but then I found out that the input file will not read the value and always give back C://fakepath//
forms.py :
class UpdateForm(forms.Form):
name = forms.CharField(
max_length=255, required=True, help_text="Required, name"
)
email = forms.CharField(
max_length=254, help_text="Required. Inform a valid email address."
)
avatar = forms.ImageField(required=False)
views.py :
class Account(LoginRequiredMixin, FormView):
model = CustomUser
form_class = UpdateForm
user = None
template_name = 'settings/account.html'
def get(self, request, *args, **kwargs):
self.user = get_object_or_404(CustomUser, id=kwargs["pk"])
return super(Account, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.user = get_object_or_404(CustomUser, id=kwargs["pk"])
return super(Account, self).post(request, *args, **kwargs)
def form_valid(self, form):
self.user.email = form.cleaned_data["email"]
self.user.name = form.cleaned_data["name"]
self.user.avatar = form.cleaned_data.get('avatar')
self.user.save()
messages.add_message(
self.request, messages.SUCCESS, "Update {} user success".format(self.user.name)
)
return super(Account, self).form_valid(form)
Templates :
<form action="{% url 'Account-list' user.id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input accept="image/*" name="avatar" type='file' id="imgInp" />
<label for="" class="field-label">Full Name</label>
<input type="text" name="name" id="name" class="field-style" value="{{user.name}}"
placeholder="Write name here...">
<label for="" class="field-label">Email Registered</label>
<input type="text" name="email" id="email" class="field-style" value="{{user.email}}"
placeholder="Write email here...">
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
