Using an instance on form "doesn't raise an HttpResponse object" even though the object exists in the database
Question: I'm trying to fetch forms for floorplans for individual property's. I can
check that the object exists in the database, but when I try to create a form
with an instance of it I receive this error:

    
    
    Traceback:
    File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      130.                                  % (callback.__module__, view_name))
    
    Exception Type: ValueError at /dashboard-property/253/
    Exception Value: The view properties.views.dashboard_single_property didn't return an HttpResponse object. It returned None instead.
    

My models.py:

    
    
    class Property(models.Model):
        user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='user')
        name = models.CharField(max_length=120, help_text="This is the name that will display on your profile")
        image = models.ImageField(upload_to='properties/', null=True, blank=True)    
        options=(('House', 'House'),('Condo','Condo'),('Apartment','Apartment')) 
        rental_type = models.CharField(max_length=120, blank=True, null=True, choices=options, default='Apartment')
        address = models.CharField(max_length=120)
        phone_number = models.CharField(max_length=120, blank=True, null=True)
        email = models.EmailField(max_length=120, blank=True, null=True)
        website = models.CharField(max_length=250, blank=True, null=True)
        description = models.CharField(max_length=500, blank=True, null=True)
        lat = models.CharField(max_length=120, blank=True, null=True)
        lng = models.CharField(max_length=120, blank=True, null=True)
        coordinates =models.CharField(max_length=120, blank=True, null=True)
        slug = models.SlugField(unique=True, max_length=501)
        active = models.BooleanField(default= True)
        date_added = models.DateTimeField(auto_now_add=True)
    
        def save(self):
            super(Property, self).save()
            max_length = Property._meta.get_field('slug').max_length
            slug_name = slugify(self.name)
            self.slug = '%s-%d' % (slug_name, self.id)  
            self.coordinates = geo_lat_lng(self.address)
            self.lat = self.coordinates[0]
            self.lng = self.coordinates[1]
            super(Property, self).save()
    
        def __unicode__(self):
            return '%s-%s-%s' % (self.id, self.name, self.address)
    
        def get_absolute_url(self):
            return reverse("single_property", kwargs={"slug": self.slug})
    
        def get_dashboard_url(self):
            return reverse("dashboard_single_property", kwargs={"id": self.id})
    
    class FloorPlan(models.Model):
        property_name = models.ForeignKey(Property, related_name='property_name')
        floor_plan_name = models.CharField(max_length=120, blank=True, null=True)
        numbers = (('0','0'),('1','1'),('2','2'),('3','3'),('4','4'),('5','5'),('6+','6+'),)
        bedrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
        bathrooms = models.CharField(max_length=120, blank=True, null=True, choices=numbers)
        sqft = models.IntegerField(max_length=120, blank=True, null=True)
        min_price = models.IntegerField(max_length=120, blank=True, null=True)
        max_price = models.IntegerField(max_length=120, blank=True, null=True)
        availability = models.DateField(null=True, blank=True, help_text='Use mm/dd/yyyy format')
        image = models.ImageField(upload_to='floor_plans/', null=True, blank=True)    
    
        def __unicode__(self):
            return '%s' % (self.property_name)
    

My views.py:

    
    
    def dashboard_single_property(request, id):
        if request.user.is_authenticated():
            user = request.user
            try:
                single_property = Property.objects.get(id=id)
                user_properties = Property.objects.filter(user=user)
                if single_property in user_properties:
                    user_property = Property.objects.get(id=id)
                    #Beginning of Pet Policy Instances 
                    user_floor_plan = FloorPlan.objects.select_related('Property').filter(property_name=user_property)
                    if user_floor_plan:
                        print user_floor_plan
                        plans = user_floor_plan.count()
                        plans = plans + 1
                        FloorPlanFormset = inlineformset_factory(Property, FloorPlan, extra=plans)
                        formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
                        print "formset_floor_plan is True"
                    else:
                        floor_plan_form = FloorPlanForm(request.POST or None)
                        formset_floor_plan = False
                        print 'formset is %s' % (formset_floor_plan)
                    #End
                    #Beginning of Pet Policy Instances 
                    user_pet_policy = PetPolicy.objects.select_related('Property').filter(property_name=user_property)
                    print user_pet_policy
                    if user_pet_policy:
                        print user_pet_policy
                        #pet_policy_form = PetPolicyForm(request.POST or None, instance=user_pet_policy)
                        pet_policy_form = PetPolicyForm(request.POST or None)
                    else:
                        pet_policy_form = PetPolicyForm(request.POST or None)
                    #End
                    basic_form = PropertyForm(request.POST or None, instance=user_property)
                    context = {
                    'user_property': user_property,
                    'basic_form': basic_form,
                    'floor_plan_form': floor_plan_form,
                    'formset_floor_plan': formset_floor_plan,
                    'pet_policy_form': pet_policy_form,
                    }
                    template = 'dashboard/dashboard_single_property.html'
                    return render(request, template, context)
                else:
                    return HttpResponseRedirect(reverse('dashboard'))
            except Exception as e:
                raise e
                #raise Http404
                print "whoops"
        else:
            return HttpResponseRedirect(reverse('dashboard'))
    

**EDIT:** Took Vishen's tip to make sure the error was raised, updated the
views and now I'm getting this error. Here's the full traceback:

    
    
    Environment:
    
    
    Request Method: GET
    Request URL: http://localhost:8080/dashboard-property/253/
    
    Django Version: 1.7.4
    Python Version: 2.7.5
    Installed Applications:
    ('django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     'django.contrib.messages',
     'django.contrib.sites',
     'django.contrib.sitemaps',
     'django.contrib.staticfiles',
     'base',
     'properties',
     'renters',
     'allauth',
     'allauth.account',
     'crispy_forms',
     'datetimewidget',
     'djrill',
     'import_export',
     'multiselectfield')
    Installed Middleware:
    ('django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     'django.middleware.locale.LocaleMiddleware')
    
    
    Traceback:
    File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/Users/balrog911/Desktop/mvp/mvp_1_live/src/properties/views.py" in dashboard_single_property
      82.             raise e
    
    Exception Type: AttributeError at /dashboard-property/253/
    Exception Value: 'QuerySet' object has no attribute 'pk'
    

**EDIT:** Per Vishen's suggestion, removed the try statement to see if the
error would be made more clear. It looks like the issues is with line 51:

    
    
    formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
    

Here's the traceback:

    
    
    Traceback:
    File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
      111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/Users/balrog911/Desktop/mvp/mvp_1_live/src/properties/views.py" in dashboard_single_property
      51.                 formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)
    File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/forms/models.py" in __init__
      855.         if self.instance.pk is not None:
    
    Exception Type: AttributeError at /dashboard-property/253/
    Exception Value: 'QuerySet' object has no attribute 'pk'
    


Answer: The problem is that if an `Exception` gets raised inside the `try` statement,
you catch it, print "whoops" and then the function ends without returning
anything; where it needs to return an `HttpResponse`. There is a few ways to
solve this, but I suggest making the `except` the following

    
    
    except Exception as e:
        raise e # This will throw a 500
    

I am guessing that something in the `try` statement is error'ing but you are
silencing it. But you should throw the error so you can see and fix whatever
is breaking.

