python – I need to update the database how can I do it?-ThrowExceptions

Exception or error:

I have been trying to create a to do list app and there has been no problems until when i was adding an edit button, when i press the edit button, it shows the edit page with the text that has to be edited but the submit button that is suposed to change the database is not working, I think I need to add something to the views.py file but I dont know what.

viws.py

def edit(request, id):
created_items = Create.objects.get(id=id)
return render(request, 'my_app/edit.html', {"created_items": created_items})

urls.py

urlpatterns = [
path('edit/<int:id>/', views.edit, name='edit'),
]

models.py

class Create(models.Model):
added_date = models.DateTimeField()
text = models.CharField(max_length=200)

edit.html

{% extends 'index.html' %}

{% block body %}
    <div align="center">
        <h1>Edit your post!</h1>
        <div class="container form-group">
            <h1>↓</h1>
            <form method="POST">{% csrf_token %}
                <textarea class="form-control" name="content" id="id" rows="3" style="text-align: center;">{{ created_items.text }}</textarea>
                <button type="submit" class="btn btn-outline-success" style="margin-top: 5px;">Submit</button>
            </form>
        </div>
    </div>
{% endblock %}
How to solve:

You will send POST request when you click submit and need to catch that request in some function like:

if request.method == 'POST':
  edited_text = request.POST.get('text') ## 'text' might be changed. I don't know how you handle the request.

  related_id = request.POST.get('id') ## You need to take updated id. (somehow?)
  Create.objects.filter(id=related_id).update(text=edited_text) ## That will do the job.

Hope it helps,

Leave a Reply

Your email address will not be published. Required fields are marked *