如何循环表单字段选择并显示关联的模型实例字段 [英] How to loop over form field choices and display associated model instance fields

查看:125
本文介绍了如何循环表单字段选择并显示关联的模型实例字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有多选字段的ModelForm。选择是属于特定俱乐部的徒步旅行者的填充实例。



我想通过在第一列包含的表格中显示选项来自定义我的表单显示方式复选框和更多列显示每个徒步旅行者的详细信息。所以例如列是(checboxes,名字,年龄,最喜爱的远足径)。



我不知道如何处理这个。如何使用模板中的关联模型实例字段访问和显示表单域选择。任何人都知道Django的做法吗?

 #models.py 
class Club(models.Model):
title = models.CharField()
hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
name = models.CharField()
age = models.PositiveIntegerField()
favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
def __init __(self,* args,** kwargs):
club_pk = kwargs ['club_pk']
del kwargs ['club_pk']
super(ClubForm,self).__ init __(* args,** kwargs)
choices = [(ts.pk,ts.name)for hiker in Club.objects.filter(pk = club_pk)]
self.fields ['hikers']。 = choice

class Meta:
model = Club
fields =('hikers',)
widgets = {'hikers':forms.CheckboxSelectMultiple}


解决方案

最简单的是我您可以在HTML模板中定义整个表单。你应该可以在一个这样的模板中迭代一个字段的值:

  {%for value,text in form.hikers .field.choices%} 
{{value}}:{{text}}
{%endfor%}


I have a ModelForm with a multiple choice field. The choices are populated instances of Hikers belonging to a specific Club.

I want to customize the way my form displays, by displaying the choices in a table where the 1st column contains checkboxes, and a few more columns display the details of each hiker. So for example the columns are (checboxes, name, age, favourite hiking trail).

I'm not sure how to approach this. How do I access and display the form field choices with it's associated model instance fields in my template. Anybody know of the Django way to do this?

#models.py
class Club(models.Model):
    title = models.CharField()
    hikers = models.ManyToManyField(Hikers)

class Hiker(models.Model):
    name = models.CharField()
    age = models.PositiveIntegerField()
    favourite_trail = models.CharField()

#forms.py
class ClubForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        club_pk = kwargs['club_pk']
        del kwargs['club_pk']
        super(ClubForm, self).__init__(*args, **kwargs)
        choices = [(ts.pk, ts.name) for hiker in Club.objects.filter(pk=club_pk)]
        self.fields['hikers'].choices = choices

    class Meta:
        model = Club
        fields = ('hikers',)
        widgets = {'hikers': forms.CheckboxSelectMultiple}

解决方案

Easiest would be if you define the whole form in a HTML template. You should be able to iterate over a field's values in a template like that:

{% for value, text in form.hikers.field.choices %}
    {{ value }}: {{ text }}
{% endfor %}

这篇关于如何循环表单字段选择并显示关联的模型实例字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆