বাংলায় জ্যাঙ্গো

 

বাংলায় জ্যাঙ্গো টিউটোরিয়াল সিরিজের আজকের পর্বে আমরা যে কোন পোষ্ট বা অবজেক্ট এডিট করা শিখব। প্রথমে আমাদের এপ এর url এর মধ্যে এডিট এর url যুক্ত করি।

# cost_management/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('list/', views.my_expense, name='cost-list'),
    path('add/', views.add_expense, name='add-expense'),
    path('edit/<int:expense_id>/', views.edit_expense, name='edit-expense'),
]

localhost:800

{% extends 'base.html' %}

{% block content %}
<table class="table  table-striped">
<thead>
<tr>
    <th>Purpose</th>
    <th>Amount</th>
    <th>Date</th>
    <th>Action</th>
</tr>
</thead>
<tbody>
{% for expense in expenses %}
<tr>
    <td>{{ expense.purpose }}</td>
    <td>{{ expense.amount }}</td>
    <td>{{ expense.date }}</td>
    <td><a class="btn btn-primary" href="#">Edit</a></td>
</tr>
{% endfor %}
</tbody>
</table>
<a class="btn btn-primary" href=" {% url 'add-expense' %}">Add New Expense</a>
{% endblock %}

 

# cost_management/views.py

def edit_expense(request, expense_id):
    expense = Expense.objects.get(id=expense_id)
    if request.method == 'POST':
        print("post request")
    else:
        form = ExpenseForm(instance=expense)
    context = {'form':form}
    return render(request, 'cost/edit_expense.html', context)

 

<td>
    <a class="btn btn-primary" href="{% url 'edit-expense' expense.id %}">Edit</a>
</td>

 

# templates/cost/edit_expense.html

{% extends 'base.html' %}

{% block content %}
    <form method="POST" class="form-horizontal"> {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-default">Save</button>
    </form>

{% endblock %}

 

 

# cost_management/views.py

def edit_expense(request, expense_id):
    expense = Expense.objects.get(id=expense_id)
    if request.method == 'POST':
        form  = ExpenseForm(request.POST, instance=expense)
        form.save()
        return redirect('cost-list')
    else:
        form = ExpenseForm(instance=expense)
    context = {'form':form}
    return render(request, 'cost/edit_expense.html', context)

Delete: 

# templates/cost/expense.html

<td>
        <a class="btn btn-primary" href="{% url 'edit-expense' expense.id %}">Edit</a>
        <a class="btn btn-danger" href="{% url 'delete-expense' expense.id %}">Delete</a>
    </td>

 

# cost_management/urls.py

path('edit/<int:expense_id>/', views.edit_expense, name='edit-expense'),
path('delete/<int:expense_id>/', views.delete_expense, name='delete-expense'),

 

# cost_management/views.py

def delete_expense(request, expense_id):
    expense = Expense.objects.get(id=expense_id)
    expense.delete()
    return redirect('cost-list')

 

 

4
Leave a Reply

avatar
0 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
0 Comment authors
Recent comment authors
  Subscribe  
newest oldest most voted
Notify of