我在Django crud操作中遇到了这个问题。我尝试使用Django创建一个Crud操作。所有操作均正常,但仅更新操作不起作用。因为我试图单击编辑按钮并在编辑表单中显示数据,并且还更改了表单中的数据并单击URL中的更新按钮,所以正在更改此类型(http://localhost:8000/show/6/update/6)。我需要此URL(http://localhost:8000/update/6)。我尝试了很多方法,但都没有出错的地方,任何人都可以运行我的代码并给出注释。如何解决这个问题。
Project
urls.py
from django.contrib import admin
from django.conf.urls import url,include
urlpatterns = [
url('admin/', admin.site.urls),
url(r'^',include('olcapp.urls'))
]
应用程序
urls.py
from django.conf.urls import url
from olcapp import views
urlpatterns = [
url(r'^$',views.get),
url(r'^post/$',views.post),
url(r'^show/([0-9]+)/$',views.getId),
url(r'^update/([0-9]+)/$',views.update,name='update'),
url(r'^delete/([0-9]+)/$',views.delete),
]
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import CrudOperation
from .forms import CrudForm
# Create your views here.
def get(request):
form = CrudForm()
data = CrudOperation.objects.all()
return render(request,'index.html',{'form':form,'data':data})
def getId(request,id):
form = CrudForm()
data = CrudOperation.objects.get(id=id)
return render(request,'edit.html',{'form':form,'data':data})
def post(request):
form = CrudForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse('<h1>post Method</h1>')
def update(request,id):
print(id)
data = CrudOperation.objects.get(id=id)
form = CrudForm(request.POST,instance=data)
if(form.is_valid()):
form.save()
return HttpResponse('<h1>update method</h1>')
def delete(request,id):
data = CrudOperation.objects.get(id=id)
data.delete()
return HttpResponse('<h1>Delete method</h1>')
模板
index.html
<h1> Registration Form </h1>
<form action="post/" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit">
</form>
<h1>List of all user</h1>
<table style="width:100%">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
{% for i in data %}
<tr>
<td>{{ i.name }}</td>
<td>{{ i.email}}</td>
<td><a href="show/{{ i.id }}/">Edit</a></td>
<td><a href="delete/{{ i.id }}/">Delete</a></td>
</tr>
{% endfor %}
</table>
edit.html
<h1> Update Form </h1>
<form action="update/{{ data.id }}" method="POST">
{% csrf_token %}
<label>Name</label>
<input type="textbox" name="name" value="{{ data.name }}">
<label>Email</label>
<input type="textbox" name="email" value="{{ data.email }}">
<input type="submit" value="Update">
</form>
要创建执行CRUD操作的Django应用程序,请执行以下步骤。1.创建一个项目$ django-admin startproject crudexample2.创建一个应用$ python3 manage.py startapp员工3.项目结构
4。运行命令以迁移迁移。
$ python3 manage.py migration
5。运行服务器要运行服务器,请使用以下命令。
$ python3 manage.py runserver
访问浏览器通过输入localhost:8000 / show访问该应用程序,它将显示所有可用的员工记录。最初,没有记录。
添加记录单击添加新记录按钮,然后填写详细信息。
此部分还允许从操作列中更新,删除记录。保存几条记录后,现在我们有了以下记录。
更新记录通过单击“编辑”按钮来更新x的记录。将在编辑模式下显示x的记录。
让我将x更新为x kumar,然后单击更新按钮。它立即更新记录。单击更新按钮,它将重定向到下一页。查看名称已更新。同样,我们也可以通过单击删除链接来删除记录。
删除记录假设我要删除x,可以通过单击删除按钮轻松完成。