3

我似乎無法訪問我的django模板中的請求對象。訪問Django模板中的RequestContext?

這是我的settings.py文件的一部分:

import django.conf.global_settings as DEFAULT_SETTINGS 
TEMPLATE_CONTEXT_PROCESSOR = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.request', 
) 

urls.py

urlpatterns = patterns('', 
    url(r'^event/create/$', EventCreateView.as_view(), name='create_event'), 
    url(r'^event/update/(?P<pk>\d+)/$', EventUpdateView.as_view(), name='update_event'), 
    url(r'^event/delete/(?P<pk>\d+)/$', EventDeleteView.as_view(), name='delete_event'), 
) 

views.py

from django.views.generic import CreateView, UpdateView, DeleteView 
from events.models import Event 
from events.forms import EventForm 

class EventCreateView(CreateView): 
    model = Event 
    form_class = EventForm 

class EventUpdateView(UpdateView): 
    model = Event 
    form_class = EventForm 

class EventDeleteView(DeleteView): 
    model = Event 

forms.py

from django.forms import ModelForm 
from events.models import Event 

class EventForm(ModelForm): 
    class Meta: 
     model = Event 

event_form.html(用於CreateView的/更新視圖)

{% block content %} 
    <form action='{{ request.get_full_path }}' method='post'> 
     {% csrf_token %} 
     <table> 
      {{ form.as_table }} 
     </table> 
     <input type='submit' value='Create event!' /> 
    </form> 
{% endblock %} 

以上,似乎的request.session什麼也不做。我試過看文檔和類似的問題,但似乎沒有任何工作。有任何想法嗎?

在此先感謝。

+0

request.session是字典的類型,而不是URL。 form action =「」需要成爲一條路徑。 – karthikr

+0

是的。我的意思是request.get_full_path。抱歉。現在有什麼想法? –

+0

我不太瞭解基於類的視圖。但希望這有助於:http://www.gregaker.net/2012/apr/19/how-do-django-class-based-views-work/ – karthikr

回答

3

你有一個錯字,在TEMPLATE_CONTEXT_PROCESSORS結尾缺少'S',或許就在你的問題中?設置應該是:

TEMPLATE_CONTEXT_PROCESSORS = ("django.contrib.auth.context_processors.auth", 
"django.core.context_processors.debug", 
"django.core.context_processors.i18n", 
"django.core.context_processors.media", 
"django.core.context_processors.static", 
"django.core.context_processors.tz", 
"django.contrib.messages.context_processors.messages", 
"django.core.context_processors.request",) 

,而不是TEMPLATE_CONTEXT_PROCESSOR = ...。我更喜歡完全覆蓋設置,所以清楚了什麼是活動的(例如,您可能想禁用生產中的調試)。

+0

這是一個愚蠢的錯誤...感謝您的幫助! –

1

你使用Django的Session框架嗎?那麼是的,request.session將不會執行任何操作,因爲會話是類似字典的對象,模板引擎不知道如何呈現它。

+0

對不起。我的意思是request.get_full_path。我會編輯它。 –