2017-02-21 24 views
1

我已經存儲在數據庫中幾個項目/列表保存爲['First Form Field', 'Second input Field']如何讓數據庫中的列表到Python中的html - Django?

我想列一個清單,所有這些項目在我的前端HTML 頁我得到的項目,如

ff= form_fields.objects.all() return render(request,'user/index.html',{'message': welcome,'ff': ff})

INDEX:

{% for x in ff%} 
     <tr> 
      <td> 
       {{ x.id}} 
      </td> 
      <td> 
       {{ x.name }} 
      </td> 
      <td> 
       {% for y in x.text_field %} 
       <label>{{ y }}</label> 

        {% endfor %} 
      </td> 
      <td> 

車型

class form_fields(models.Model): 
    id = models.AutoField(primary_key=True) 
    form_name = models.CharField(max_length= 50, null=True) 
    text_field = models.CharField(max_length=255, null= True) 

我想要那個保存的列表作爲列表在該表中。

+0

你可以把你的模型在這裏的細節,你的範圍是什麼? – Cadmus

+0

添加了我的模型類@SnakeFcz – Sidharth

+0

你在哪個colunm中存儲'['First Form Field','Second input Field']'? –

回答

2

創建自己的ListField領域解決這個問題

from django.db import models 
import ast 

class ListField(models.TextField): 
    __metaclass__ = models.SubfieldBase 
    description = "form fields" 

    def __init__(self, *args, **kwargs): 
     super(ListField, self).__init__(*args, **kwargs) 

    def to_python(self, value): 
     if not value: 
      value = [] 

     if isinstance(value, list): 
      return value 

     return ast.literal_eval(value) 

    def get_prep_value(self, value): 
     if value is None: 
      return value 

     return unicode(value) 

    def value_to_string(self, obj): 
     value = self._get_val_from_obj(obj) 
     return self.get_db_prep_value(value) 

class Form_Fields(models.Model): 
    id = models.AutoField(primary_key=True) ## id builtin in django models 
    form_name = models.CharField(max_length= 50, null=True) 
    form_fields = ListField() 


[1]:Form_Fields.objects.create(form_name="test", form_field=['First Form Field', 'Second input Field']) 


{% for x in ff%} 
     <tr> 
      <td> 
       {{ x.id}} 
      </td> 
      <td> 
       {{ x.form_name }} 
      </td> 
      <td> 
       {% for y in x.form_fields %} 
        <label>{{ y }}</label> 
       {% endfor %} 
      </td> 
      <td> 
    </tr> 
{% endfor %} 
1

變化models.py這樣: -

from django_mysql.models import JSONField, Model 

class form_fields(models.Model): 
    id = models.AutoField(primary_key=True) 
    form_name = JSONField() 
    text_field = models.CharField(max_length=255, null= True) 

views.py:-

form_fields.objects.create(id=id, attrs=['First Form Field', 'Second input Field'],text_field='TextField') 

form_fields.objects.filter(attrs=['First Form Field', 'Second input Field']) 

您添加字符數組的字段,所以你會得到每一件事情的character.Other東西無論你有代碼將工作正常。

+0

當我添加ArryField。它顯示錯誤 – Sidharth

+0

此檢查檢測應解析但不包含的名稱。由於動態調度和鴨子打字,這在有限但有用的情況下是可能的。頂級和類級別的項目比實例項目更受支持。 – Sidharth

+0

和我正在使用mysql數據庫 – Sidharth

相關問題