2017-09-18 25 views
0

我目前在學習Django/Python。我試圖在html或javascript中使用Django變量,這不符合我的要求。 我的models.py和views.py文件看起來像爲什麼我不能在Javascript中使用Django的字符串變量?

class Student(models.Model): 
    name = models.CharField(max_length=200) 
    password = models.CharField(max_length=200) 

學生的名字是一個字符串變量,如‘田中’或‘吉田’,密碼是一個整型變量,1234或這樣的事情。

views.py

def index(request): 
    all_students = Student.objects.all() 
    context = {'all_students': all_students} 
    template = loader.get_template('aaa/LogIn.html') 
    return render(request,'aaa/LogIn.html', context) 

在login.html的文件中的腳本代碼看起來像

<script> 
{% for student in all_students %} 
     alert({{student.name}}) 
{% endfor %} 
</script> 

我想在此代碼使用student.name,但這不起作用。如果我將student.name更改爲student.password,則按預期工作。問題是爲什麼student.password出現在警報消息中,而student.name不出現。我認爲問題可能與變量類型的名稱和密碼有關。 如何在這種情況下使用Django變量?先謝謝你。

+5

'alert(「{{student.name}}」)' - 您必須**在JavaScript中引用**字符串。 – Pointy

+0

我真的建議你不要將密碼存儲在charfield中......如果你正在製作一個自定義用戶模型,那麼你應該按照django文檔.. – Sayse

+0

這個網站不是我創造的工作或任何嚴重。所以,密碼實際上不是密碼。不過,謝謝你的建議。 – Masa

回答

4

嘗試:

alert("{{student.name}}"); 

注入變量的字符串。

+0

現在有效!哇,我感謝你的幫助。 – Masa

+1

如果它解決了您的問題,請接受答案 – Bestasttung

相關問題