0

I tried to select poi(point of interest) to make loi(line of interest), I met two problems on many to many fields:

1.Why I can't post the multiple selected options.

2.How to change the name in the option with the name I want (e.g. 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')

template

<table>
   {% for p in loi_form.poi %}
       <tr>{{p}}</tr>
   {% endfor%}
</table>
max
  • 17
  • 6

1 Answers1

0
  1. You are using commit=False in form.save(). In that case, after loi_form.save() you will need to add loi_form.save_m2m() to save many-to-many fields.

  2. In __unicode__ function you are returning self.POI_date, self.user which shows the result as in image. Instead use:

    def __str__(self):
        return self.POI_title
    

__unicode__ was used in python2, using just __str__ will be enough. Remove __unicode__ function.

Emin Mastizada
  • 1,375
  • 2
  • 15
  • 30
  • By the way, why `self.fields['poi'].widget = forms.widgets.CheckboxSelectMultiple()` didn't chande to checkbox from origin image? – max Mar 11 '17 at 16:59
  • First of all, where you make this change? It needs to be done in `__init__` function of the Form, or directly inside form items (before `class Meta`). Also just writing `forms.CheckboxSelectMultiple()` will be enough, no need for `forms.widgets`. – Emin Mastizada Mar 11 '17 at 23:51
  • Also you wrote `__init__` function inside Meta, that is incorrect. It should be inside `LOIForm` (same line as `class Meta:`) – Emin Mastizada Mar 11 '17 at 23:53