Home > front end >  How to add "Edit Function" in django
How to add "Edit Function" in django

Time:01-23

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 > <div > <div >
            <a href="{% url 'gallery' %}" >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}}"  >

            
            </div>
           
            <div>
                <input required name="description"  value="{{photo.description}}" type="text" size="60"></input>
            </div>
            
            <div >
            
            <button type="submit" >Update</button>
            </div>

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

CodePudding user response:

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()

CodePudding user response:

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.

  • Related