django-how to upload image using ImageField in a model form?

51 views Asked by At

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 ?

1

There are 1 answers

1
sunnah boy On BEST ANSWER

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:

  1. 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.

    if user_form.is_valid():
        # Your code for saving data
    
  2. 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.

    if user_form.is_valid():
        get_user.first_name = first_name
        get_user.last_name = last_name
        get_user.phone = phone
        get_user.profile_picture = profile_picture
        get_user.save()
    
  3. ImageField handling in models: Ensure that the upload_to path is correct and exists in your project structure. The 'static/zzz/xxx/' path should be relative to your MEDIA_ROOT.

    profile_picture = models.ImageField(blank=True, upload_to='zzz/xxx/')
    
  4. Check the enctype attribute in your HTML form: Ensure that your HTML form has the correct enctype attribute set for file uploads.

    <form method="post" enctype="multipart/form-data">
        <!-- Your form fields here -->
    </form>
    

Make these adjustments, and it should help resolve the issue with the image not being saved.