Django - 如何在CRUD应用程序中正确处理路由和重定向

时间:2018-02-22 16:27:23

标签: django

我有一个小应用程序,它有索引/视图/创建/删除/存储约会功能。

对于我的商店功能,它只是将新的约会条目添加到数据库,我如何处理网址,因此不需要/ store。我想我正在寻找一种方法来严格定义路线是否是一个获取/发布/删除。

urls.py

from django.urls import path
from . import views

app_name = "appointments"

urlpatterns = [

    path('', views.index, name="index"),
    path('<int:appointment_id>/', views.detail, name="detail"),
    path('create/', views.create, name="create"),
    path('store/', views.store, name="store"),
    path('<int:appointment_id>/', views.delete, name="delete"),

]

views.py

from django.shortcuts import get_object_or_404, render, redirect
from django.http import HttpResponse

from .models import Appointment

# Create your views here.
def index(request):

    appointments = Appointment.objects.all()

    context = {
        'appointments': appointments
    }

    return render(request, 'appointments/index.html', context)

def detail(request, appointment_id):

    appointment = get_object_or_404(Appointment, pk=appointment_id)

    context = {
        'appointment': appointment
    }

    return render(request, 'appointments/detail.html', context)

def create(request):
    return render(request, 'appointments/create.html')

def store(request):

    make = request.POST['make']
    model = request.POST['model']
    description = request.POST['description']
    date_time = request.POST['date_time']

    appointment = Appointment(make=make, model=model, description=description, date_time=date_time)
    appointment.save()

    return redirect('/appointments')

def delete(request, appointment_id):

    appointment = get_object_or_404(Appointment, pk=appointment_id)
    appointment.delete()

    return redirect('/appointments')

0 个答案:

没有答案