Home > database >  I am not able to delete a specific item from a table in Django template/view
I am not able to delete a specific item from a table in Django template/view

Time:11-11

I have a list of wallet addresses in my template. When I tried deleting an address by clicking on the delete button, it returns an error message. I think it is an error from the way my template was structured. But, I don't really know. When I try deleting an address by manually inputting the id of the address in the delete view URL, it gets deleted. Here is the error message that is returned.

Traceback (most recent call last):
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py", line 2018, in get_prep_value
    return int(value)

The above exception (invalid literal for int() with base 10: 'Btc') was the direct cause of the following exception:
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\admin\Documents\Django\crypto\dashboard\views.py", line 275, in del_wallet
    wallet.delete()
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\base.py", line 1137, in delete
    return collector.delete()
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\deletion.py", line 475, in delete
    query.update_batch(
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\subqueries.py", line 78, in update_batch
    self.get_compiler(using).execute_sql(NO_RESULTS)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1819, in execute_sql
    cursor = super().execute_sql(result_type)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1382, in execute_sql
    sql, params = self.as_sql()
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\sql\compiler.py", line 1785, in as_sql
    val = field.get_db_prep_save(val, connection=self.connection)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\related.py", line 1146, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py", line 925, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py", line 2703, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\admin\Documents\Django\env\lib\site-packages\django\db\models\fields\__init__.py", line 2020, in get_prep_value
    raise e.__class__(

Exception Type: ValueError at /dashboard/wallet/2/delete/
Exception Value: Field 'id' expected a number but got 'Btc'.

views.py

@login_required
def wallet(request):
    user = request.user
    wallet=Wallet(user=user)
    object_list = Wallet.objects.filter(user=user)
    # Paginator
    paginator = Paginator(object_list, 2) 
    page = request.GET.get('page')
    try:
        ref = paginator.page(page)
    except PageNotAnInteger:
        ref = paginator.page(1)
    except EmptyPage:
        ref = paginator.page(paginator.num_pages)    
    if request.method == 'POST':
        if 'add' in request.POST:
            form = WalletForm(request.POST, instance=wallet)
            if form.is_valid():
                form.save()
                messages.success(request, ("New wallet address successfully added."))
                return redirect("dashboard:wallet")
    else:
        form = WalletForm(instance=user)
    context = {
        'form': form,
        'ref': ref,
        # 'refe': refe
        # 'del_wallet': del_wallet
    }
    return render(request, 'dashboard/wallet.html', context)


@login_required
def del_wallet(request, pk):
    wallet = get_object_or_404(Wallet, id=pk)
    wallet.delete()
    return redirect("dashboard:wallet")

The first view wallet is responsible for letting users add new wallet, and also responsible for displaying the wallets. The adding wallet logic is done by the use of a popup modal. The second view del_wallet is responsible for handling the delete logic.

urls.py

urlpatterns = [
    path('wallet', wallet, name="wallet"),
    path('wallet/<str:pk>/delete/', del_wallet, name="del_wallet"),
]

By typing out the URL and specifying an id, the wallet address with the id gets deleted. Like, calling http://localhost"5000/wallet/2/delete/ deletes the address with id of 2. But clicking on the delete button attached to each wallet, returns back the error message specified above. I added print statement to check the details of the wallet that pops up each time I click the delete button. It logs the correct wallet being clicked with its id, but yet it returns an error message. I can't seem to figure out what is causing the error.

wallet.html

<h3 >Available Wallets</h3>
            <div >
                <table >
                    <thead>
                        <tr>
                        <th>SN</th>
                        <th>Type</th>
                        <th>Address</th>
                        <th>Delete</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!--  -->
                        {% for i in ref %}
                            <tr>
                                <td style="line-height: 1.3; padding-top: 1.6em;">{{ forloop.counter }}</td>
                                <td style="padding-top: 20px;">{{ i.get_type_display }}</td>
                                <td style="padding-top: 20px;">{{ i.address }}</td>
                                <td  data-bs-toggle="modal" data-bs-target="#wallet{{ i.pk }}">
                                    <a style="text-decoration: none;" href="#wallet{{ i.pk }}">
                                        Delete
                                    </a>
                                </td>
                            </tr>
                            <!-- DELETE MODAL -->
                            <div  id="wallet{{ i.pk }}" tabindex="-1" role="dialog" style="margin-top: 10em;">
                                <div  role="document">
                                    <div  style="background: #141822;">
                                        <div >
                                            <h6>Confirm Delete</h6>
                                            <p>Are you sure you want to delete 
                                                <span style="color: rgb(10, 223, 165);">
                                                    {{ i.type }} - {{ i.address }}
                                                </span> wallet?
                                            </p>
                                                <button type="submit" >
                                                    <a href="/dashboard/wallet/{{ i.pk }}/delete/" style="text-decoration: none;">
                                                        Confirm
                                                    </a>
                                                </button><br>
                                                <button type="button"  data-bs-dismiss="modal">
                                                   Close
                                                </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        {% empty %}
                            <tr>
                                <td>You haven't added a wallet address yet.</td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>

models.py

class Wallet(models.Model):
    wallet = (
        ('Btc', 'Bitcoin'), 
        ('Eth', 'Ethereum'), 
        ('Trc20', 'Tether-UDST'), 
        ('Ltc', 'Litecoin') 
)
    user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    type = models.CharField(choices=wallet, default='Btc') 
    address = models.CharField(max_length=80)

Please, what is likely the cause of the error. I've read up many posts online, but none seems to help in resolving my problem.

CodePudding user response:

At first it should be <int:pk> not <str:pk> and secondly use url tags in anchor tags so:

<a href="{% url 'dashboard:del_wallet' i.pk %}" style="text-decoration: none;">                      

It's better to change the url as:

urlpatterns = [
    path('wallet/', wallet, name="wallet"),
    path('wallet/delete/<int:pk>/', del_wallet, name="del_wallet"),
]

Note: Always add / at the end of every route.

CodePudding user response:

<td  data-bs-toggle="modal" data-bs-target="#wallet{{ i.pk }}">
    <a style="text-decoration: none;" href="{% url 'del_wallet' i.pk %}">
        Delete
    </a>
</td>

only take link like this

<a href="{% url 'del_wallet' i.pk %}" style="text-decoration: none;">
    Confirm
</a>

Remove this

<button type="submit" >
</button>

CodePudding user response:

Simply you can try this way:

<a href="/dashboard/wdelete/{{i.pk}}" style="text-decoration: none;">

And in your urls.py:

path('wdelete/<int:pk>', del_wallet, name="del_wallet"),

And in your views.py:

def del_wallet(request, pk):
    wallet = Wallet.objects.get(id=pk)
    wallet.delete()
    return HttpResponseRedirect("/dashboard/wallet/")

Try and see if it solves your error

  • Related