写一个基于django框架的增删改查代码
时间: 2024-05-06 22:15:09 浏览: 95
下面是一个基于Django框架的增删改查的代码示例:
## models.py
```
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.name
```
## views.py
```
from django.shortcuts import render, get_object_or_404, redirect
from .models import Item
from .forms import ItemForm
def item_list(request):
items = Item.objects.all()
return render(request, 'item_list.html', {'items': items})
def item_detail(request, pk):
item = get_object_or_404(Item, pk=pk)
return render(request, 'item_detail.html', {'item': item})
def item_new(request):
if request.method == "POST":
form = ItemForm(request.POST)
if form.is_valid():
item = form.save(commit=False)
item.save()
return redirect('item_detail', pk=item.pk)
else:
form = ItemForm()
return render(request, 'item_edit.html', {'form': form})
def item_edit(request, pk):
item = get_object_or_404(Item, pk=pk)
if request.method == "POST":
form = ItemForm(request.POST, instance=item)
if form.is_valid():
item = form.save(commit=False)
item.save()
return redirect('item_detail', pk=item.pk)
else:
form = ItemForm(instance=item)
return render(request, 'item_edit.html', {'form': form})
def item_delete(request, pk):
item = get_object_or_404(Item, pk=pk)
item.delete()
return redirect('item_list')
```
## forms.py
```
from django import forms
from .models import Item
class ItemForm(forms.ModelForm):
class Meta:
model = Item
fields = ('name', 'description', 'price')
```
## item_list.html
```
{% extends 'base.html' %}
{% block content %}
<h1>Item List</h1>
<p><a href="{% url 'item_new' %}">Add a new item</a></p>
<ul>
{% for item in items %}
<li><a href="{% url 'item_detail' pk=item.pk %}">{{ item.name }}</a></li>
{% endfor %}
</ul>
{% endblock %}
```
## item_detail.html
```
{% extends 'base.html' %}
{% block content %}
<h1>{{ item.name }}</h1>
<p>Description: {{ item.description }}</p>
<p>Price: {{ item.price }}</p>
<p><a href="{% url 'item_edit' pk=item.pk %}">Edit this item</a></p>
<form action="{% url 'item_delete' pk=item.pk %}" method="post">
{% csrf_token %}
<input type="submit" value="Delete this item">
</form>
{% endblock %}
```
## item_edit.html
```
{% extends 'base.html' %}
{% block content %}
<h1>{% if form.instance.pk %}Edit{% else %}New{% endif %} Item</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save">
</form>
{% endblock %}
```
在这个示例中,我们定义了一个名为Item的模型,它具有名称,描述和价格属性。我们还定义了与模型相关的表单,用于创建和编辑项目。视图中包含为各种操作定义的函数,例如列出项目,显示项目详细信息,创建新项目,编辑项目和删除项目。模板文件定义了如何呈现数据,例如列表和详细信息页面。
阅读全文