2017-06-04 62 views
0

我是Django的新手,並已完成他們的網站上的7部分教程。他們的教程的Part four在頁面details上引入了一個表單,該表單發佈到votes(不顯示任何內容的視圖),然後在成功時返回results,否則返回detailsDjango:正確的方式來處理與POST到同一頁面的形式

但是,如果您有一個您想要發佈給自己的頁面(例如,更新與該頁面相關的值(這是計算的服務器端)的值)。

注:我已經得到了這個工作,但我想知道我是否正確,因爲我對一些事情感到困惑。

所以對於我的網頁代碼目前看起來是這樣的:

def post_to_self_page(request, object_id): 

    obj = get_object_or_404(Obj, pk=object_id) 

    # if update sent, change the model and save it 
    model_updated = False 
    if 'attribute_of_obj' in request.POST.keys(): 
     obj.attribute_of_obj = request.POST['attribute_of_obj'] 
     obj.save() 
     model_updated = True 

    # do some stuff with obj 

    # specify the context 
    context = { 
    'obj': obj, 
    } 
    if model_updated: 
     # good web practice when posting to use redirect 
     return HttpResponseRedirect(reverse('my_app:post_to_self_page', args=(object_id,))) 
    return render(request, 'my_app/post_to_self_page.html', context) 

所以在這種情況下,當圖。首先叫我搶的對象,如果它的存在。然後檢查POST中是否有屬性:如果是,我更新模型。然後,如果模型已更新,我使用HttpResponseRedirect到相同的頁面,否則我發送只使用渲染(第一次調用)

這是正確的嗎?

回答

1

你可以做這樣的事情,

def post_to_self_page(request, object_id): 
    obj = get_object_or_404(Obj, pk=object_id) 
    if request.method == 'POST': 
     obj.attribute_of_obj = request.POST['attribute_of_obj'] 
     obj.save() 
    context = { 'obj': obj, } 
    return render(request, 'my_app/post_to_self_page.html', context) 
相關問題