请帮我在使用表单使用访问在Django模板的M2M字段值形式
我的模型访问模板中的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 %}
请帮帮我!
你应该向我们展示EventForm和LocationForm的定义 – Alvaro
我已经更新了模型表单,请看看@Alvaro – user4k