Django CRUD:更新功能不起作用



我在django中制作了CRUD。在创建和删除视图时,更新不起作用。请解决我的问题。告诉我我缺少什么。

这是views.py:

from  .import models
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render
from .forms import readerRegistrationForm
from .models import Reader, books
from django.views.generic import TemplateView,RedirectView,UpdateView
from django.views import View
# Create your views here.
def done(request):
return render(request,'done.html')
class addshowView(TemplateView):
template_name='add&show.html'
def get_context_data(self,*args,**kwargs):
context= super().get_context_data(**kwargs)
fm=readerRegistrationForm()
stu=Reader.objects.all()
cone=books.objects.all()
context={'str':stu,'form':fm,'con':cone}
return context

def post(self,request):
fm=readerRegistrationForm(request.POST)
if fm.is_valid():
fm.save()
return HttpResponseRedirect('/')    
class userdeleteview(RedirectView): 
url='/'
def get_redirect_url(self, *args, **kwargs):
p=kwargs['id']
Reader.objects.get(pk=p).delete()
return super().get_redirect_url(*args, **kwargs)
class Updateview(UpdateView):
def get(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(instance=pi)
return render(request,'updateit.html',{'form':fm})
def post(self,request,id):
pi=Reader.objects.get(pk=id)
fm=readerRegistrationForm(request.POST,instance=pi)
if fm.is_valid():
fm.save()
return render(request,'updateit.html',{'form':fm})`

这是forms.py:

from django.forms import fields, widgets
from .models import books,Reader
class readerRegistrationForm(forms.ModelForm):
class Meta:
model=Reader
fields=['name','email','comment']

这是models.py:

from django.db.models.deletion import CASCADE
#Create your models here.
class books(models.Model):
name=models.CharField(max_length=200)
gener=models.CharField(max_length=200)
author=models.CharField(max_length=200)
isbn=models.BigIntegerField()
def __str__(self) :
return self.name
class Reader(models.Model):
name=models.CharField(max_length=200)
email=models.EmailField(max_length=200)
comment=models.TextField()
def __str__(self) :
return self.comment

这是urls.py:

from django.contrib import admin
from django.urls import path
from boom import views
urlpatterns = [
path('', views.addshowView.as_view() , name='show'),
path('updated/',views.done,name='done'),
path('delete/<int:id>/', views.userdeleteview.as_view() , name='doNow'),
path('update/<int:id>/', views.Updateview.as_view() , name='UpNow'),
path('admin/', admin.site.urls),
]

这是updateit.html

{% extends 'index.html' %}
{% block body_block %}
<div class="container">
<h1>Welcome to Reader Update Page!!</h1>
<form method="POST">
{% csrf_token %}
{{form.as_p}}
<a href="{% url 'done' %}"><button type="button" class="btn btn-success">Update</button></a>
</form>
</div>

{% endblock %}

这是index.html

<!DOCTYPE html>
{%load static%}
<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>Base</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="alert alert-danger" role="alert">
<div class="blockquote text-center"><h1 class="alert">Welcome!!</h1>
<h1>This is My Virtual Book Stall!</h1>
</div>
</div>
<div class="jumbotron">
{% block body_block %}
{% endblock %}
</div>
</div>

</body>
</html>

这是add&show.html

{% extends 'index.html' %}
{% block body_block %}
<div style="text-align: center;">
<h1 class="alert alert-secondary" role="alert"><em>This is The Library U can Grab!!</em></h1> 
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Author</th>
<th>Gener</th>
</tr>
</thead>
<tbody>
{% for st in con %}
<tr>
<th>{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.author}}</td>
<td>{{st.gener}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<form method="POST" class="table table-primary">
{% csrf_token %}
<div class="row justify-content-between">
<div class="col-4">
<h3 class="alert alert-secondary" role="alert">Add member</h3>
{{form.as_p}}
<input class="btn btn-primary" type="submit" value="Register">
</div>
<div class="col-8">

<h3 style="text-align: center;" class="alert alert-secondary" role="alert">Show Data</h3>
{% if str %}
<table class="table  ">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col"><strong>Name</strong> </th>
<th scope="col"><strong> Email</strong></th>
<th scope="col"><strong> Comment</strong></th>
<th scope="col"><strong> Action</strong></th>
</tr>
</thead>
<tbody>
{% for st in str %}
<tr>
<th scope="row">{{st.id}}</th>
<td>{{st.name}}</td>
<td>{{st.email}}</td>
<td>{{st.comment}}</td>
<td><a href="{% url 'UpNow' st.id %}"><button type="button" class="btn btn-success">Edit</button></a>
<a href="{% url 'doNow' st.id %}"><button type="button" class="btn btn-danger">Delete</button></a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h3>NO RECORDS NOW</h3>
{% endif %} 
</div>
</div>
</form>
{% endblock %}

这是done.html

{% extends 'index.html' %}
{% block body_block %}
<div class="jumbotron">
<h3>Information updated Successfully!!</h3>
<a href="{% url 'show' %}">Click Me</a>
</div>
{% endblock %}

您不需要分别使用两个函数进行更新。使用此:

class Updateview(UpdateView):    
def update(request, pk):
pi=Reader.objects.get(pk=id) 
fm = readerRegistrationForm(instance=pi)      
if request.method == 'POST':
fm = readerRegistrationForm(request.POST, instance=pi)
if fm.is_valid:
fm.save()
return redirect('home')
context = {'form':fm}
return render(request,'updateit.html', context )

最新更新