from django.shortcuts import render, get_object_or_404
# form imports here
# model imports here
# get all objects
def get_view(request):
objects = YourModel.objects.all()
return render(request, 'all-objects.html', {'objects': objects}
# make a new object
def make_new_obj(request):
form = YourForm(request.POST or None)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request, 'make-new-obj.html', {'form': form}
# get an object by id
def get_single_object_view(request, id):
obj = get_object_or_404(YourModel, pk=id)
return render(request, 'obj-detail.html', {'obj': obj}
# update an object
def update_obj(request, id):
obj = get_object_or_404(YourModel, pk=id)
form = YourForm(request.POST or None, instance=obj)
if request.method == 'POST':
if form.is_valid():
form.save()
return render(request, 'update-obj.html',
{'obj': obj, 'form': form}
# delete an object
def delete_obj(request, id):
obj = get_object_or_404(YourModel, pk=id)
obj.delete()
# do something else like redirect to the object index, etc
# you'll probably want to make this a two-step process
显然,这里有很多代码可以组合,所以可以根据需要进行混合和匹配。所有这些代码在Django文档中都有很好的介绍。。。你知道吗
模型实例引用:https://docs.djangoproject.com/en/1.5/ref/models/instances/
使用窗体:https://docs.djangoproject.com/en/1.5/topics/forms/
相关问题 更多 >
编程相关推荐