How to add "Edit Function" in django

I need to add an edit button to my django app but it only redirects me to the homepage and no edit is saved.

this is my views.py code, i think that's where the issue is coming from

def editPhoto (request, pk):
photo = Photo.objects.get(id=pk)
categories = Category.objects.all()

if request.method == 'POST':   
    description = request.FILES.get('description')
    photo.save()
    return redirect ('/')

context = {'categories': categories, 'photo': photo}
return render(request, 'photos/edit.html', context)`

models.py

class Category(models.Model): name = models.CharField(max_length=100, null=False, blank=False)
def __str__(self):
    return self.name

class Photo(models.Model): category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField()
def __str__(self):
    return self.description`

edit.html

<div class="container"> <div class="row justify-content-center"> <div class="col">
            <a href="{% url 'gallery' %}" class="btn btn-dark my-3">Go Back</a>

            <form method='POST' action="" enctype="multipart/form-data">
                {% csrf_token %}
                
            <div style="height: 90vh;">
                <img style="max-width: 100%; max-height: 100%;" src="{{photo.image.url}}" class="center" >

            
            </div>
           
            <div>
                <input required name="description" class="input" value="{{photo.description}}" type="text" size="60"></input>
            </div>
            
            <div class="center">
            
            <button type="submit" class="btn btn-primary m-3; center">Update</button>
            </div>

        </div>
    </div>
</div>`

The problem is that you are not saving any changes in your model.

description = request.FILES.get('description')
    photo.save()

this should be changed to

photo.description = request.POST.get('description')
photo.save()

The problem is You are not passing id of photo you want to edit from your html file.

  1. in Edit.html in form action="{% url photo.id %} , and make changes if needed in urls.py file.

  2. by doing so id would be passed to views.py which acts as pk.

Back to Top