使用表单上的实例“不会引发HttpResponse对象”,即使该对象存在于数据库中

时间:2015-04-30 05:17:27

标签: python django django-forms django-views django-queryset

我正在尝试为个人财产获取平面图的表格。我可以检查数据库中是否存在该对象,但是当我尝试使用它的实例创建表单时,我收到此错误:

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.

我的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)

我的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'))

编辑:提出Vishen的提示以确保错误被​​引发,更新了视图,现在我收到此错误。这是完整的追溯:

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'

修改 根据Vishen的建议,删除了try语句以查看错误是否会更清楚。看起来问题出在第51行:

formset_floor_plan = FloorPlanFormset(instance=user_floor_plan)

这是追溯:

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'

2 个答案:

答案 0 :(得分:0)

问题在于,如果在Exception语句中引发try,则会抓住它,打印"呐喊"然后函数结束而不返回任何东西;需要返回HttpResponse的地方。有几种方法可以解决这个问题,但我建议将except设为以下

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

我猜测try语句中的某些内容是错误的,但您正在对其进行静音。但是你应该抛出错误,这样你就可以看到并修复任何破坏的东西。

答案 1 :(得分:0)

您需要为第一个if语句返回一些内容。您收到该错误,因为如果该语句有效,则不会返回任何内容。

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, num=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:
            #raise Http404
            print "whoops"
        #RETURN SOMETHING HERE ! ! !
    else:
        return HttpResponseRedirect(reverse('dashboard'))