Home > database >  Why i can't update image in django?
Why i can't update image in django?

Time:01-30

modle.py

class Form(models.Model):
name = models.CharField(max_length=40)
email = models.EmailField()
file = models.ImageField(null=True, blank=True)

class Meta:
    db_table: 'django'  # table name

edit.py

<form action="{% url 'update' user.id %}" method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        <div >
          <label for="exampleFormControlInput1" >Name</label>
          <input type="text"  id="exampleFormControlInput1" placeholder="name" name="name" value="{{ user.name }}">
        </div>
        <div >
          <label for="exampleFormControlInput" >Email address</label>
          <input type="email"  id="exampleFormControlInput" placeholder="[email protected]" name="email" value="{{  user.email }}">
        </div>
        <div >
          <label for="exampleFormControlInput2" >Image</label>
          <input type="file"  id="exampleFormControlInput2" name="{{  user.file }}" >
        </div>
        <div >
            <img src="{{ user.file.url }}" alt="" srcset="" style="width:100px">
        </div>
        <button type="submit"  id="liveToastBtn">submit</button>
    </form>

view.py when i try to update from all the fields is all update and also remove old image but it doesn't save new image to directory please help me

def update(request, user_id):
user = Form.objects.get(id=user_id)
form = UserForm(request.POST, request.FILES, instance=user)
if request.method == 'POST':

    if form.is_valid():
        if os.path.exists(user.file.path):
            os.remove(user.file.path)
        form.save()
        return redirect("listing")
    else:  # mean form is invalid
        return render(request, 'edit.html', {'user': user})

CodePudding user response:

In your file tag you have set name="{{ user.file }}" replace that with name="file" as

<input type="file"  id="exampleFormControlInput2" name="file">

The name attributes of your html must be according to the field name of your model.

CodePudding user response:

Error is in this line

<input type="file"  id="exampleFormControlInput2" name="{{  user.file }}">

{{user.file}} is data of user so it only show you data if you want to edit file change

   <input type="file"  id="exampleFormControlInput2" name="file">
  •  Tags:  
  • Related