Model Choice Field - get the id
<p>I am busy trying to get the id only in integer format preferably for the ModelChoiceField. I get the list to display but get's returned in a string format. Please helping me in retrieving the id of ModelChoiceField. I think I need to do this in the view. </p>

<pre><code>forms.py
class ProjectForm(forms.ModelForm):
    items = forms.ModelChoiceField(queryset=Project.objects.all())

    class Meta:
        model = Project
        fields = ['items']

models.py
class Project(models.Model):
    items = models.IntegerField(default=0, blank=True, null=True)

views.py
def ProjectView(request):
    form = ProjectForm(request.POST)

    if request.method == 'POST':
        if form.is_valid():
            save_it = form.save(commit=False)
            save_it.save()
            return HttpResponseRedirect('/')       
    else:
        form = ProjectForm()

return render(request, 't.html', {'form': form })
</code></pre>

<p>From what I can tell, <code>items</code> should never be an <code>IntegerField</code>. Your usage has it set up to be a <code>ForeignKey</code> to a <code>Project</code> so you should just make that explicit</p>

<pre><code>items = models.ForeignKey('self', null=True, blank=True)
</code></pre>

<p>Possibly with a better descriptive name than items.</p>

<p>Then, you don't need to define anything on the form, it just becomes a standard model form, with a standard model form usage.</p>

python django django-models django-forms