2016-04-14 45 views
0

我想發送一個變量到使用Django表單和模板的HTML。Django - 診斷問題與類和視圖

這是我的代碼...

class AdminView(TemplateView): 
template_name = 'admin.html' 

def admin(self, request): 
    template = 'admin.html' 
    data = Quiz.objects.all() 
    form = AdminForm(request.POST) 
    context = {"form": form} 
    context['admin'] = data 
    # return render(request, template, context) 
    return render_to_response(context) 

什麼是錯的代碼?變數怎麼沒有出現在網站上。

行上下文= {「form」,form}已經在我的IDE中高亮顯示,並且出錯。

錯誤:此字典創建可能被重寫爲字典文字。

這是怎麼回事?

class AdminView(TemplateView): 
    template_name = 'admin.html' 

def post(self, request): 
    template = 'admin.html' 
    data = Quiz.objects.all() 
    form = AdminForm(request.POST) 
    context = {"form": form} 
    context['admin'] = data 
    return render(request, template, context) 

不幸的是仍然無法正常工作?

這是HTML代碼...

{% if request.user.is_authenticated%} 
    {% if request.user.username == "teacher" %} 
     <!DOCTYPE html> 
     <html lang="en"> 
     <head> 
      {% load staticfiles %} 
      <meta charset="UTF-8"> 
      <title>Admin</title> 
      <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}" /> 
     </head> 
     <body> 
     {% include 'navbar.html' %} 

     Admin Test 

     {{ admin }} 



     </body> 
     </html> 
    {% endif %} 

回答

0

這僅僅是一個風格問題,並沒有任何實際問題。

您的代碼存在一些實際問題。首先,你不能只是定義一個像admin這樣的任意方法,並期望它被調用。您需要在此處定義getpost

第二個是render_to_response需要給模板名稱。您的註釋版本使用render是正確的。

+0

好的,我已經添加了一些問題。這看起來如何?它似乎還沒有工作。 –

0

小心的identation,如果你想發送額外的上下文的模板,你可以使用get_context_data()方法,像這樣:

class AdminView(TemplateView): 
    template_name = 'admin.html' 

    ''' 
    This is for a GET request 
    ''' 
    def get_context_data(self, **kwargs): 
     context = super(AdminView, self).get_context_data(**kwargs) 
     context['admin'] = Quiz.objects.all() 
     context['form'] = AdminForm() 
     return context 

    ''' 
    This is for a POST request 
    ''' 
    def post(self, request, *args, **kwargs): 
     form = AdminForm(request.POST) 
     if form.is_valid(): 
      # do something if form data is valid 
     else: 
      # do something if form data is not valid 
     return render(request, 'admin.html', context) 

但是如果你想proccess一種形式,我建議你使用FormView代替的TemplateView

+0

我想你已經錯過了理解我的目標,我試圖將數據庫中的數據顯示到網站上。 –