使用表单访问django模板中的m2m字段值

时间:2014-01-23 13:55:29

标签: python django django-forms django-templates

请帮助我使用表单

访问模板中的m2m值

我的模特:

class Opportunity(models.Model):
    sfdc_id = models.PositiveIntegerField(null=True, blank=True)

class Event(models.Model):
    background = models.TextField(null=True, blank=True)
    account = models.ForeignKey(Account)
    opportunities = models.ManyToManyField(Opportunity, null=True, blank=True)

Views.py

def event(request,event_id):
    if request.method == 'GET' :
        eventForm=EventForm(instance=Event.objects.get(pk=event_id))
        locationForm = LocationForm(prefix='location')
        return render(request,'events/event.html', {'eventForm': eventForm, 'locationForm': locationForm})

更新了模型表格:

class EventForm(ModelForm):
    account = ModelChoiceField(queryset=Account.objects.all())
    background = CharField(widget=Textarea(attrs={'class':'form-textarea resizeoff auto-resize js_auto_resize  default'}), required=False)
    opportunities = CharField(label='SalesForce ID', widget=TextInput(attrs={'class' : 'form-input'}), required=False)

在我的模板中,我尝试过以下代码,但不能正常工作

{% for attr in eventForm.opportunities.all %}
      <td>{{ attr.sfdc_id }}</td>
{% endfor %}

我试过这个但仍然无法正常工作

{% for attr in eventForm.opportunities_set.all %}
      <td>{{ attr.sfdc_id }}</td>
{% endfor %}
  

请帮帮我!!!

2 个答案:

答案 0 :(得分:1)

opportunities = ModelMultipleChoiceField(widget=SelectMultiple(attrs={'class' : 'form-input'}),queryset=Opportinuty.objects.all(), label='SalesForce ID', required=False) 

...

答案 1 :(得分:0)

在您的表单中,将商机的定义更改为:

class EventForm(ModelForm):
    account = ModelChoiceField(queryset=Account.objects.all())
    background = CharField(widget=Textarea(attrs={'class':'form-textarea resizeoff auto-resize js_auto_resize  default'}), required=False)
    opportunities = ModelMultipleChoiceField(queryset=Opportinuty.objects.all(), label='SalesForce ID', required=False)

文档here

这将呈现适当的M2M表单控件。 如果您希望将小部件更改为更有用的小部件,我建议您查看django-selectable

它有一个很好的AutocomboboxSelectMultipleWidget我觉得非常有用(而且很棒!)