简体   繁体   English

如何基于表格中的数据在Django表单上显示项目?

[英]How can I display items on Django form based on data in a table?

I am trying to figure out how to display a form based on data from a table. 我试图弄清楚如何基于表格中的数据显示表单。 I basically want to use the data from one table as a label to enter data that goes into another table. 我基本上想使用一个表中的数据作为标签来输入要进入另一表的数据。

I have two food tables: 我有两个食物表:

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

class Food(models.Model):
  foodtype = models.ForeignKey(FoodType)
  tracktemp = models.BooleanField(verbose_name="Track Temperature?")

and a Temp table like this: 和这样的临时表:

class Temp(models.Model):
  date = models.DateField('Entry Date')
  time = models.TimeField('Entry Time')
  food = models.ForeignKey(Food)
  temp = models.IntegerField(max_length=4, blank=True, null=True)

I have two foods in my Food table (Beans, Sprouts) and tracktemp is set to True for each of them. 我的“ Food表中有两种食物(“豆”,“豆芽”),并且每个Food tracktemp设置为True

In the Temp table I want to be able to add multiple records, each of which has a single temp at a particular time. 在“临时”表中,我希望能够添加多个记录,每个记录在特定时间都有一个临时。 For example: 例如:

Beans  1st Dec 2012 6.00pm     230
Beans  1st Dec 2012 6.04pm     235
Beans  1st Dec 2012 6.10pm     240

To do this I want to be able to render a form like this to enter the temps: 为此,我希望能够渲染这样的表单以输入临时文件:

Beans   [    ]
Sprouts [    ]
[save]

Some notes about the above form: 有关上述形式的一些注意事项:

  • The food names should be labels, not combo boxes. 食物名称应为标签,而不是组合框。
  • I will not show the date/time fields and just programmatically set them. 我不会显示日期/时间字段,而只是通过编程设置它们。

As such I need to find all items in the Food table that have tracktemp set to 'True' and use that to present a form to the user so the user can add a temp for that time. 因此,我需要在Food表中找到所有tracktemp设置为“ True”的项目,并使用该项目向用户展示表单,以便用户可以为该时间添加一个Temp。

How can I do this? 我怎样才能做到这一点?

The tricky part is basically the rendering of the Temp.food as something other than a select widget(which is the default for ForeignKey relationships). 棘手的部分基本上是将Temp.food渲染为选择小部件(这是ForeignKey关系的默认值)以外的东西。

For this you'd have to subclass the Select widget and override the render method to output just a label with the selected value 为此,您必须继承Select小部件并重写render方法,以仅输出具有所选值的标签。

from django.forms.widgets import Select

class MyLabelSelect(Select):
    def render(self, name, value, attrs=None, choices=()):
        # read the django.forms.widgets.Select.render() source to 
        # understand what you have to do here. Not that hard.
        pass

A formset is indeed what you need here, with a caveat: you'll need to pass it a slightly custom form that uses your new widget for the FK relationship. 需要注意的是,实际上确实需要一个表单集,但需要注意:您需要传递一个稍微自定义的表单,该表单使用新的窗口小部件来建立FK关系。

from django import forms
from .widgets import MyLabelSelect
from .models import Temp

class TempForm(forms.ModelForm):
    class Meta:
        model = Temp
        exclude = ('date', 'time')
        widgets = {
            'food': MyLabelSelect
        }

OK now we need to construct the actual formset 好的,现在我们需要构建实际的表单集

from django.forms.models import modelformset_factory
from .forms import TempForm
from .models import Temp

def my_view(request):
    TempFormset = modelformset_factory(
        Temp,
        form = TempForm,
        max_num = Temp.objects.count()
    )

    if request.method == 'POST' and request.POST:
        # I'll just demonstrate the GET request
        pass
    else:
        # Grab the Temp objects we want
        temps = Temp.objects.filter(food__tracktemp=True)
        temp_formset = TempFormset(
            queryset=temps 
        )
    return render_to_response(....)

Haven't actually tested the above code, but something along those lines is what you're after. 尚未实际测试上面的代码,但是您需要遵循的内容。 If I have any glaring errors tell me and I'll correct them. 如果我有任何明显的错误,请告诉我,我将予以纠正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM