无法使用自定义html输入字段执行更新和删除操作

icnyk63a  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(194)

我是 Django 的初学者。我现在正在做一个小项目,我在做更新和删除操作时遇到了一个问题。我使用的是forms.py,但使用的是html文件中的自定义输入字段。我尝试了许多方法,但都返回错误。当我尝试更新时,它会创建一个新条目,而不是更新。当我执行DELETE时,没有任何React。请检查下面的代码,并帮助我解决这个问题。

urls.py

from django.urls import path
    from . import views

    urlpatterns = [
       path('', views.home, name='home'),
       path('contacts', views.contacts, name='contacts'),
       path('update/', views.update, name='update'),
       path('delete/', views.delete, name='delete'),
    ]

views.py

def update(request, contact_id):
       details = Contact.objects.filter(id=contact_id)
       if request.method == 'POST':
           form = ContactForm(request.POST or None, instance=details)
           if form.is_valid():
               form.save()
               return redirect('contacts')
       else:
           return render(request, 'update.html', {'details':details})

    def delete(request, contact_id):
       contact = Contact.objects.all()
       if request.method == 'POST':
           details = Contact.objects.get(id=contact_id)
           details.delete()
           return redirect('contacts')
       return render(request, 'contacts.html', {'contact':contact})

联系人.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row mt-5">
            <div class="col-sm-8">
                <a href="{% url 'home' %}" class="btn btn-primary mb-3">Home ></a>
                <table class="table">
                  <thead>
                    <tr>
                      <th scope="col">#</th>
                      <th scope="col">First</th>
                      <th scope="col">Last</th>
                      <th scope="col">Handle</th>
                      <th scope="col">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                  {% for item in contact  %}
                    <tr>
                      <th scope="row">{{item.id}}</th>
                      <td>{{item.name}}</td>
                      <td>{{item.email}}</td>
                      <td>{{item.mobile}}</td>
                      <td><a href="{% url 'update' item.id %}" class="btn btn-success">Edit</a>
                          <a href="{% url 'delete' item.id %}" class="btn btn-danger">Delete</a>
                      </td>
                    </tr>
                  {% endfor %}  
                  </tbody>
                </table>
            </div>
        </div>
    </div>

      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>
</body>
</html>

update.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-5 mt-5">
                <a href="{% url 'contacts' %}" class="btn btn-primary mb-3">Contacts ></a>
                <form action=" url '{{details.id}}' " method="post" autocomplete="off">
                    {% csrf_token %}
                    {% for item in details %}
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="name" placeholder="full name" name="name" value="{{item.name}}">
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" placeholder="name@name.com" name="email" value="{{item.email}}">
                    </div>
                    <div class="mb-3">
                        <label for="mobile" class="form-label">Mobile</label>
                        <input type="number" class="form-control" id="mobile" placeholder="Eg: 0546321023" name="mobile" value="{{item.mobile}}">
                    </div>
                    {% endfor %}
                    <button type="submit" class="btn btn-primary mt-2">Update</button>
                </form>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a+RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>
</body>
</html>

forms.py

from django.forms import ModelForm
    from .models import Contact

    class ContactForm(ModelForm):
        class Meta:
            model = Contact
            fields = ['name','email','mobile']

Models.py

from django.db import models

    # Create your models here.
    class Contact(models.Model):
        name = models.CharField(max_length=100)
        email = models.EmailField(max_length=50)
        mobile = models.IntegerField()

        def __str__(self):
            return self.name
0dxa2lsx

0dxa2lsx1#

在urls.py中进行以下更改:

from django.urls import path
from . import views

urlpatterns = [
   path('', views.home, name='home'),
   path('contacts', views.contacts, name='contacts'),
   path('update/<str:contact_id>/', views.update, name='update'),
   path('delete/<str:contact_id>/', views.delete, name='delete'),
]

您的UPDATE和DELETE视图运行良好,但它们之前没有获得任何联系人ID。现在,通过进行这些更改,假设请求https://localhost:8000/update/1,则urlDispatcher将匹配URL并调用视图函数,如下所示

update(request,contact_id='1')
delete(request,contact_id='1')

尝试阅读Django Docs的这一部分:https://docs.djangoproject.com/en/4.1/intro/tutorial03/#writing-more-views

相关问题