1

I have a webpage where you can add a new computer/ip to the database, or choose a previously added from a dropdown list. Everything works fine, except that what I get after the user is selecting an item from the list is the index of it, and not its name. How can I get the name? I am trying to access the queryset as a vector as seen here, but I get a TypeError.

views.py:

d = DropDownList(request.POST or None)
    if d.is_valid():
        c = request.POST.get('current')
        return HttpResponse(d.qs[c-1])

models.py:

class DropDownList(forms.Form):
    qs = Computer.objects.all().order_by('name')
    current = forms.ModelChoiceField(qs, widget=forms.Select(attrs={"onChange":'submit()'}))    

class Computer(models.Model):
    name = models.CharField(max_length=200, default='')
    ip = models.CharField(max_length=200, default='')
    def __unicode__(self):
        return self.name

home.html:

<form method="post">
    {{ current }}
</form>
Community
  • 1
  • 1
toni
  • 713
  • 3
  • 7
  • 17

1 Answers1

1

The whole point of using a form is that it takes care of validation and data conversion, so in your view you should get the data from the form, not from the POST itself.

if d.is_valid():
    c = d.cleaned_data['current']
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895