2015-06-09 75 views
2

前幾天我已經決定學習Python/Django和使用它在我的私人項目的一種實踐。我在builidng'polls'應用程序中完成了djangoproject教程1-6,現在我開始自己做了。以正確的方式的Python/Django的處理HTTP請求

簡單的問題 - 我想查看,創建,編輯和刪除「交易」的端點。

到目前爲止,我已經中views.py

from django.views import generic 
from django.http import HttpResponseRedirect 
from django.views.generic.edit import CreateView 
from django.core.urlresolvers import reverse 

from .models import Deal 

class IndexView(generic.ListView): 
    context_object_name = 'latest_deals_list' 

    def get_queryset(self): 
     return Deal.objects.order_by('-created_date')[:10] 

class DetailView(generic.DetailView): 
    model = Deal 

class DealCreate(CreateView): 
    model = Deal 
    fields = ['title', 'url'] 

    def post(self, *args, **kwargs): 
     title = self.request.POST["title"] 
     url = self.request.POST["url"] 

     try: 
      deal = Deal(tite=title, url = url) 
      deal.save() 
     except Exception as e: 
      print e 

     return HttpResponseRedirect(reverse('deals:detail', args=(deal.id,))); 

下面我urls.py lokks這樣的:

from django.conf.urls import url 

from . import views 

urlpatterns = [ 
    url(r'^$', views.IndexView.as_view(), name='index'), 
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), 
    url(r'^create/$', views.DealCreate.as_view(), name='create') 
] 

這一切工作正常,但我很努力瞭解如何將其組織成更簡潔的類API結構。我可以在路線中只有/交易,然後分別使用不同的模板實現所有方法GET/POST/PUT/DELETE嗎?我會在indexView中做到這一點,只有在其他視圖內打印表格?只是覺得我不適合在/創建POST方法,或者我是否會過度使用這個方法。

任何反饋將不勝感激。

+3

如果你想有一個REST API,你可能希望使用django-rest-framework或不安分。否則,而不是浪費你的時間與Django的「GenericViews」只是寫你自己的做正確的事情。 –

+0

感謝您的提示。我已經意識到'GenericViews'不是一個好的選擇,簡單的功能與ModelForm相結合對於我想要構建的接口來說要好得多.REST API可能是完全不同的故事,當我到達那裏時我會穿過那座橋。 – irwin

回答

0

我意識到最好使用基於功能的方法與ModelForm而不是GenericViews。我與表單驗證工作更新的代碼看起來像這樣:

from django.views import generic 
from django.shortcuts import render, get_object_or_404 
from django.http import HttpResponseRedirect 
from django.core.urlresolvers import reverse 

from .models import Deal 
from .forms import DealForm 

class IndexView(generic.ListView): 
    context_object_name = 'latest_deals_list' 

    def get_queryset(self): 
     return Deal.objects.order_by('-created_date')[:10] 

class DetailView(generic.DetailView): 
    model = Deal 

def add_model(request): 

    form = DealForm(request.POST or None) 
    if form.is_valid(): 
     deal = form.save() 
     return HttpResponseRedirect(reverse('deals:detail', args=(deal.id,))); 

    return render(request, "deals/deal_form.html", {'form': form, 'title': 'Add New Deal'}) 

def update_model(request, pk): 

    deal = get_object_or_404(Deal, pk=pk) 

    form = DealForm(request.POST or None, instance=deal) 
    if form.is_valid(): 
     deal = form.save() 
     return HttpResponseRedirect(reverse('deals:detail', args=(deal.id,))); 

    return render(request, "deals/deal_form.html", {'form': form, 'title': 'Editing "' + deal.title + '"'}) 

def delete_model(request, pk): 

    deal = get_object_or_404(Deal, pk=pk) 

    if request.method == 'POST': 
     deal.delete() 
     return HttpResponseRedirect(reverse('deals:index')); 

    return render(request, "deals/deal_confirm_delete.html", {'object': deal, 'title': 'Confirm deleting "' + deal.title + '"'}) 

urls.py:

from django.conf.urls import url 

from . import views 

urlpatterns = [ 
    url(r'^$', views.IndexView.as_view(), name='index'), 
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), 
    url(r'^create/$', views.add_model, name='create'), 
    url(r'^(?P<pk>[0-9]+)/edit/$', views.update_model, name='update'), 
    url(r'^(?P<pk>[0-9]+)/delete/$', views.delete_model, name='delete') 
] 

和forms.py:

from django.forms import ModelForm 
from .models import Deal 

class DealForm(ModelForm): 
    class Meta: 
     model = Deal 
     fields = ['title', 'url']