user1933205
user1933205

Reputation: 362

KeyError for 'id' field when ModelForm CheckboxSelectMultiple choices are 'id'

I am new to Django. I have a form where I want to have list of 'id's of model items as choices of CheckboxSelectMultiple field. Here is my example

Models.py

class TryDjango(models.Model):
    name    = models.CharField(max_length=120)

Views.py

class trydjango_view(View):
    template_name = 'trydjango.html'
    failed_template = 'generic_error.html'

    viewContext = {
        "title" : "Page title ",
        "columnNames" : ["Name"],
        "url" : 'trydjango',
        'loginInfo' : 'logout',
    }

    def get(self, request):
        self.viewContext['deleteTryDjangoForm'] = \
            deleteTryDjangoForm(prefix='delete')
        login_result = getLogin(request)
        self.viewContext.update({'loginInfo' : login_result['loginInfo']})
        return render(request, self.template_name, self.viewContext)

trydjango.html template

{% block tableHeader %}
  <tr>
    {% if user.is_authenticated %}
    <td>

      <form id="delItem" action="" method="post">
        {% csrf_token %}
        <input type="submit" value="Delete Django"
          name="{{deleteTryDjangoForm.prefix}}"/>
      </form>

    </td>
    {% endif %}
    {% for columnName in columnNames %}
      <th>{{columnName}}</th>
    {% endfor %}
  </tr>

{% endblock %}

ModelForms.py

    class deleteTryDjangoForm(forms.ModelForm):
    myPrefix ='delete-'

    class Meta:
        model = TryDjango
        fields = ['id']

    def __init__(self, *args, **kwargs):
        super(deleteTryDjangoForm,self).__init__(*args, **kwargs)
        sportSeriesList = listOfSportSeries()
        print(sportSeriesList)
        self.fields['id'].widget = \
            forms.CheckboxSelectMultiple(choices=[(1,1)]) #<<-- Line 399 in the error

Finally the error I am getting

KeyError at /trydjango/
'id'
Request Method: GET
Request URL:    http://127.0.0.1:8000/trydjango/
Django Version: 2.0.7
Exception Type: KeyError
Exception Value: 'id'
Exception Location: /Users/sbt/dev/trydjango/src/myPrjApp/modelforms.py in __init__, line 399

Where line 399 is the line "forms.CheckboxSelectMultiple(choices=[(1,1)])" from my form.

The form doesn't give this error if I change the field from 'id' to 'name'. I have few other models whose primary keys are not the 'id' fields. I can delete those model items using the corresponding primary keys. However, the form fails only if the primary key is 'id'.

Please help me with my mistake.

Thanks

Upvotes: 0

Views: 265

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

The id in a model is not editable, so a ModelForm doesn't create a field for it.

You don't need a ModelForm here anyway. That's for creating new instance or editing existing ones. You just want a standard form.

class deleteTryDjangoForm(forms.ModelForm):
    id = fields.MultipleChoiceField(
       choices=[(1,1)],
       widget=forms.CheckboxSelectMultiple
    )

Upvotes: 1

Related Questions