2017-08-09 50 views
0

我有2种型号在我的系统:产生的Django模板对象动态

class Display(models.Model): 
    name = models.CharField 
    UE = models.CharField 
    description 

class Register(models.Model): 
    temp1 = models.FloatField() 
    temp2 = models.FloatField() 
    flow = models.FloatField() 

我创建使用的模板中显示,但每次显示的值是注册模型各个现场。我不能使用寄存器循环,因为我只使用行(我不能循环字段)。理解?

看看我的代码:

查看:

def main(request): 
dp_col = Display.objects.all() 
reg = Registers.objects.latest('pk') 
context = { 
    'dp_col': dp_col, 
    'reg':reg 
} 
return render(request,'operation.html',context) 

模板:

{% for dp in dp_col %} 
     <div class='col-md-6'> 
      <div class="display-content"> 
       <div class="display-data"> 
        <h3 class="text-center display-desc">{{dp.name}} 
         <span>:</span> 
         <span class="text-center display-value">I need put the value of each field here</span> 
         <span class='display-unit'> {{dp.UE}}</span> 
        </h3> 
       </div> 
      </div> 
     </div> 
    {% empty %} 
     <!--colocar alguma coisa aqui, caso não tenha nada no for--> 
    {% endfor %} 

任何想法? 非常感谢!

回答

0

这可以通过使用一个Django形式来容易地解决:

yourapp/forms.py

from django import forms 

class DisplayForm(forms.ModelForm): 
    class Meta: 
     model = Display 
     fields = '__all__' 

yourapp/views.py

from .forms import DisplayForm 

def main(request): 
    # if this is a POST request we need to process the form data 
    if request.method == 'POST': 
     # create a form instance and populate it with data from the request: 
     form = DisplayForm(request.POST) 
     # check whether it's valid: 
     if form.is_valid(): 
      # process the data in form.cleaned_data as required 
      # ... 
      # redirect to a new URL: 
      return HttpResponseRedirect('/thanks/') 

    # if a GET (or any other method) we'll create a blank form 
    else: 
     form = DisplayForm() 

    return render(request, 'operation.html', {'form': form}) 

在operations.html:

<form method="post" action=""> 
    {{ form }} 
</form> 

或者如果y OU希望在各个领域的自定义HTML:

<form method="post" action=""> 
    {% for field in form %} 
     {{ field.label_tag }} {{ field }} 
    {% endfor %} 
</form> 

参考: https://docs.djangoproject.com/en/1.11/topics/forms/

+0

我需要这在第一次调用我的看法。这是一个GET方法。我这样做是为了避免在模板中重复显示代码。 – FelipeFonsecabh

+0

请在我的模板中查看此链接:https://i.stack.imgur.com/16BpN.png tittle和UE数据来自Display模型,字段的值来自Register Model。在调用视图之前,我做了一个查询,它从寄存器表返回最后一个寄存器。但我无法迭代这些查询集,因为有1个寄存器。 – FelipeFonsecabh