View没有返回HttpResponse

时间:2017-07-10 14:30:59

标签: django python-3.x django-views

我的项目在github Project

我收到此错误。

ValueError at /salesapp/add/ashton-aged-maduro/
The view salesapp.views.add_CartItem didn't return an HttpResponse object. It returned None instead. 

点击“添加到购物车”后,我收到此错误消息我的singleproduct.html模板上的按钮,调用ProductAddToCart表单。视图为add_CartItem

当我最初没有设置表单值时,我也会收到错误Field is required。我现在才被卡住了。

这是models.py

class Product(models.Model):
    itemid = models.CharField(max_length=128, unique=True)
    itemname = models.CharField(max_length=128)
    brand = models.CharField(max_length=128)
    image = models.ImageField(upload_to='static/images/')
    notes = models.CharField(max_length=250)
    price = models.IntegerField()
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.itemname)
        super(Product, self).save(*args, **kwargs)

    def __str__(self):
        return self.itemname

class CartItem(models.Model):
    cart_id = models.CharField(max_length=50)
    date_added = models.DateTimeField(auto_now_add=True)
    quantity = models.IntegerField(default=1)
    itemid = models.ForeignKey('Product', unique=False)

    class Meta:
        db_table = 'cart_items'
        ordering = ['date_added']

    def name(self):
        return self.product.name

我的forms.py

 class ProductAddToCartForm(forms.ModelForm):
        cart_id = forms.CharField(max_length=50)
        date_added = forms.DateTimeField()
        quantity = forms.IntegerField()
        slug = forms.CharField(widget=forms.HiddenInput(), required=False)

        #itemid = models.ForeignKey('Product', unique=False)

        class Meta:
            model = CartItem
            fields = ('cart_id', 'date_added', 'quantity', 'slug', 'itemid', )

我的views.py

def add_CartItem(request, product_name_slug):
        print('In add_CartItem --------------------')
    form = ProductAddToCartForm(request.POST)

    p = Product.objects.get(slug=product_name_slug)
    form = ProductAddToCartForm(initial={'cart_id': 123, 'date_added':date.date.today(), 'quantity': 1, 'slug':p.slug, 'id':p.id, 'itemid':p.itemid})
    form.save(commit=False)
    print(form)
    print(p.slug)
    print(p.id)
    print(p.itemid)

    if form.is_valid():
        print(p)
        print('In form.is_valid()--------------------------------')

        ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)

        form.save(commit=True)
        return index(request)
    else:
        print(form.errors) #return render(request, 'salesapp/errors.html', {'form': form})

我的urls.py

from django.conf.urls import url
from salesapp import views

    urlpatterns = [
        url(r'^$', views.index, name='index'),
        url(r'about/', views.about, name='about'),
        url(r'customers/', views.customers, name='customers'),
        url(r'products/', views.products, name='products'),
        url(r'^add_product/$', views.add_product, name='add_product'),
        url(r'^add_customer/$', views.add_customer, name='add_customer'),
        url(r'items/(?P<product_name_slug>[\w\-]+)/$', views.show_product, name='show_product'),
        url(r'^add/(?P<product_name_slug>[\w\-]+)/$', views.add_CartItem, name='add_CartItem'),
        #url(r'^cart/$', views.show_cart, name='show_cart'),
        #url(r'^register/$', views.register, name='register'),
        #url(r'^login/$', views.user_login, name='login'),
        #url(r'^logout/$', views.user_logout, name='logout'),
        #url(r'^restricted/', views.restricted, name='restricted'),
    ]

和我的模板,我想显示ProductAddToCartForm但是将产品添加到CartItem表。

<!DOCTYPE html>
{% extends 'salesapp/base.html' %}
{% load staticfiles %}

{% block title_block %}
    {{ product.itemname }}
{% endblock %}

{% block body_block %}

    <div>
        <div>
            <ul style="list-style:none; text-align:center;">
                <li style="float:left; width:25%; margin:20px;">
                        <img src="/{{ product.image }}"/>
                    <div>
                        <b>{{ product.itemname }}</b><br/>
                        Price per cigar:<br/>
                        <b>${{ product.price }}</b>
                        <p>{{ product.notes }}</p>
                    </div>

                    <form method="post" action="/salesapp/add/{{ product.slug }}/" class="cart">
                        {% csrf_token %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                        {% for field in form.visible_fields %}
                            {{ field.errors }}
                            {{ field.help_text }}
                            {{ field }}
                        {% endfor %}
                         <br />
                         <input type="submit" value="Add To Cart" name="submit" alt="Add To Cart" />
                    </form>
                    <div class="cb"></div>
                </li>
            </ul>
        </div>
    <!-- More code -->
    </div>

{% endblock %}

4 个答案:

答案 0 :(得分:2)

django中的视图函数应该返回一个json或dict,或者可以返回一个网页 您可以执行以下操作之一 1)返回一个json或dict

return {"value1":"value","value2":"value"}

2)重定向到网页

return redirect('/some/url/')

3)返回Http响应

return HttpResponse(status=<status code>,content="some content")

4)渲染模板

t = loader.get_template('myapp/index.html')
c = {'foo': 'bar'}
return HttpResponse(t.render(c, request), 
content_type='application/xhtml+xml')

答案 1 :(得分:1)

因为您没有向视图返回任何响应,

根据docs

  

视图函数只是一个Python函数   接受Web请求并返回Web响应。

您需要返回使用render方法进行表单的初始呈现,并且要重定向到另一个视图,您可以使用Django的redirect方法。

答案 2 :(得分:1)

视图函数必须返回HttpResponse。例如,如果流程成功并且您不想返回任何内容,则可以返回HttpResponse(status=200)

当视图处理表单时,您必须拆分GET和POST请求。在GET部分中,您需要实例化没有数据的表单。在POST部分中,您使用request.POST数据填写表单。此数据必须包含所有必填字段。处理表单的典型视图函数方案如下:

def view(request):
   if request.method == "GET":
       form = MyForm()
       return ...
   if request.method == "POST":
       form = MyForm(request.POST)
       form.save()
       return ...

在模板中,您必须显示所有表单字段。然后,所有表单字段将与请求一起传递。如果你不这样做,你需要填写视图中的表单字段。

答案 3 :(得分:1)

首先删除打印件,几乎在你提出问题时,在Django中无用

def add_CartItem(request, product_name_slug):
    form = ProductAddToCartForm(request.POST)

    if request.method == 'POST':
        if form.is_valid():    
            ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)
            ci.save()#you save your model changes, not your form
            return HttpResponseRedirect(reverse('your:url'))#your return the success url or the same
        else:
            #here error, if form isn't valid
    else:
        form = ProductAddToCartForm(request.POST)
        return render(request, 'your/template.html', {'form': form})

这是在Django中使用表单的正确方法,首先你必须发一个if语句询问浏览器是否是发布请求或正常请求,如果是发布请求,从表单中获取数据并添加如果没有,Django会返回一个空的模板表单。

如果您解决问题,请告诉我