Django post 具有表单的 manytomany 字段

Django post manytomany field with form

我尝试select poi(point of interest) 来制作 loi(line of interest),我在多对多领域遇到了两个问题:

1.Why 我不能 post 多个 selected 选项。

2.How 将选项中的名称更改为我想要的名称(例如 POI_title) original name/image

Model.py

class POI(models.Model):
    user = models.ForeignKey(User,on_delete = models.CASCADE)
    poi_id = models.AutoField(primary_key=True)
    POI_title = models.CharField(max_length=10)
    def __unicode__(self):
        return "{}({})".format(self.POI_date, self.user)

class LOI(models.Model):
    user = models.ForeignKey(User,on_delete = models.CASCADE)
    poi = models.ManyToManyField(POI)
    LOI_title = models.CharField(max_length=10)
    loi_id = models.AutoField(primary_key=True)

Form.py

 class LOIForm(forms.ModelForm):
 class Meta:
    model = models.LOI
    fields = ['poi','LOI_title']
    def __init__(self, user, *args, **kwargs):
        super(LOIForm,self).__init__(*args, **kwargs)
        self.fields['poi'].widget = forms.widgets.CheckboxSelectMultiple()
        self.fields['LOI_title'].label= 'title'

Views.py

 if request.method == 'POST':
    request.POST.get("name", request.user.username)
    loi_form = forms.LOIForm(request.POST)
    if loi_form.is_valid():
        loi_form = loi_form.save(commit=False)
        loi_form.user = request.user
        loi_form.save()
        return HttpResponseRedirect('/make_LOI')

模板

<table>
   {% for p in loi_form.poi %}
       <tr>{{p}}</tr>
   {% endfor%}
</table>
  1. 您正在 form.save() 中使用 commit=False。在这种情况下,在 loi_form.save() 之后您将需要添加 loi_form.save_m2m() 以保存多对多字段。

  2. __unicode__ 函数中,您将返回 self.POI_date, self.user,结果如图所示。而是使用:

    def __str__(self):
        return self.POI_title
    

__unicode__在python2中使用,只用__str__就够了。删除 __unicode__ 函数。