0

I have an edit view for one of my models.

@login_required        
def edit(request, id):
    ''' Edit form '''
    if id:
        post = get_object_or_404(Post, pk=id)
        if post.user != request.user:
            return HttpResponseForbidden()
    else:
        post = Post()

    if request.POST:
        form = PostForm(request.POST, instance = post)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('posts_manage'))
    else:
        form = PostForm(instance = post)

    return render_to_response('posts/add.html', {'form':form}, context_instance=RequestContext(request))

Everything works fine, all the post information is loaded correctly, but one of the fields, which is a select box, is not being selected with the value obtained from the DB. Other select boxes are selected to the appropriate value.

The field that is not being populated properly in the model definition:

class Post(models.Model):
    ...
    BATHROOM_CHOICES = ((1,'1'),(1.5,'1.5'),(2,'2'),(2.5,'2.5'),(3,'3'),(3.5,'3.5'),(4,'4'), (4.5,'4.5'),(5,'5+'))
    bathrooms = models.DecimalField(max_digits = 2,decimal_places = 1,choices = BATHROOM_CHOICES)

Relevant section inside add.html:

{{ form.bathrooms|bootstrap}}

forms.py

class PostForm(ModelForm):
    class Meta:
        model = Post
        exclude = ('available','user',)

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        return super(PostForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        kwargs['commit'] = False
        obj = super(PostForm, self).save(*args, **kwargs)
        if self.request:
            obj.user = self.request.user
        obj.save()
        return obj
AlexBrand
  • 11,971
  • 20
  • 87
  • 132

1 Answers1

2

The data in the DB is not being matched by a choice in BATHROOM_CHOICES

BATHROOM_CHOICES = ((1,'1'),(1.5,'1.5'),(2,'2'),(2.5,'2.5'),(3,'3'),(3.5,'3.5'),(4,'4'), (4.5,'4.5'),(5,'5+')) and models.DecimalField(max_digits = 2,decimal_places = 1, are contradicting.

Your model definition expects all values will have a decimal place of at least 1, and probably coerces values like whole number from 1 to 1.0 in the DB (depending on adapter implementation).

so then when it looks for a choice matching the value 1 !== 1.0 and so no value is selected.

Possible fix: BATHROOM_CHOICES = ((1.0,'1'),(1.5,'1.5'),(2.0,'2'),(2.5,'2.5'),(3.0,'3'),(3.5,'3.5'),(4.0,'4'), (4.5,'4.5'),(5.0,'5+'))

Francis Yaconiello
  • 10,829
  • 2
  • 35
  • 54