My form doesn't save the uploaded image in the path given, my code:
models.py:
class MyClass(models.Model):
user = models.OneToOneField(SomeClass, on_delete=models.CASCADE)
address_line_1 = models.CharField(blank=True, max_length=100)
address_line_2 = models.CharField(blank=True, max_length=100)
profile_picture = models.ImageField(blank=True, upload_to='static/zzz/xxx/')
forms.py
class edit_profile_form(forms.Form):
profile_picture = forms.ImageField(label='Avatar',widget=forms.FileInput(
attrs={
'class': 'form-control input_data',
'placeholder': 'Upload',}))
views.py
def validate_edit_profile(request):
template = loader.get_template('account/edit_.html')
user_form = edit_profile_form(request.POST,request.FILES)
userprofile = EcomCustomerProfile.objects.get(user_id=request.user.id)
#if user submit
if request.POST:
if user_form.is_valid():
# get the data
first_name = user_form.cleaned_data['first_name']
last_name = user_form.cleaned_data['last_name']
phone = user_form.cleaned_data['phone']
profile_picture = user_form.cleaned_data['profile_picture']
#change db
get_user = EcomCustomer.objects.get(id = request.user.id)
get_user.first_name = first_name
get_user.last_name = last_name
get_user.phone = phone
get_user.profile_picture = profile_picture
user_form.save()
get_user.save()
return HttpResponse(template.render({'userprofile':userprofile}, request))
I'm using two forms: one for text, the other for uploading the image. But it doesn't upload anything.
What's the problem ?
It looks like there might be an issue in your views.py where you are trying to save the form data and the user instance. Here are a few suggestions to troubleshoot the problem:
Check the form validation: Ensure that the form is valid before trying to access its cleaned data. Use
is_valid()before attempting to access the cleaned data.Handling the image upload: In your code, you are trying to save the form data and user instance separately. Instead, you should save the user instance with the associated profile picture.
ImageField handling in models: Ensure that the
upload_topath is correct and exists in your project structure. The 'static/zzz/xxx/' path should be relative to your MEDIA_ROOT.Check the enctype attribute in your HTML form: Ensure that your HTML form has the correct
enctypeattribute set for file uploads.Make these adjustments, and it should help resolve the issue with the image not being saved.