首页 > 解决方案 > Django python AttributeError异常值:'WSGIRequest'对象没有属性'shop'

问题描述

我正在编写 Django 购物网站的模块,用户可以添加商店和产品

当用户填写添加产品的表格并点击提交时,django 会给出此错误,如果有人能说明问题,那将非常有帮助,谢谢。

错误

'WSGIRequest' object has no attribute 'shop'

Request Method:     POST
Request URL:    http://127.0.0.1:8000/15/add_product/
Django Version:     2.1.2
Exception Type:     AttributeError
Exception Value:    

'WSGIRequest' object has no attribute 'shop'

Exception Location:     C:\Users\MILAN\PycharmProjects\DjangoProject\shopsurfer\views.py in form_valid, line 191
Python Executable:  C:\Users\MILAN\PycharmProjects\DjangoProject\venv\Scripts\python.exe
Python Version:     3.7.0
Python Path:    

['C:\\Users\\MILAN\\PycharmProjects\\DjangoProject',
 'C:\\Users\\MILAN\\PycharmProjects\\DjangoProject\\venv\\Scripts\\python37.zip',
 'C:\\Users\\MILAN\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
 'C:\\Users\\MILAN\\AppData\\Local\\Programs\\Python\\Python37\\lib',
 'C:\\Users\\MILAN\\AppData\\Local\\Programs\\Python\\Python37',
 'C:\\Users\\MILAN\\PycharmProjects\\DjangoProject\\venv',
 'C:\\Users\\MILAN\\PycharmProjects\\DjangoProject\\venv\\lib\\site-packages',
 'C:\\Users\\MILAN\\PycharmProjects\\DjangoProject\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.7.egg']

Server time:    Tue, 12 Feb 2019 14:37:12 +0000

product_form.html

这是生成表单的所有html代码从输入

{% extends 'shopsurfer/base.html' %}
{% block title %}Add a New Product{% endblock %}
{% block album_active %}active{% endblock %}

{% block body %}
    <div class="container=fluid">
        <div class="row">
            <div class="col-sm-12 col-md-7">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
                            {% csrf_token %}


{% for field in form %}
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
            <span class="text-danger small">{{ field.errors }}</span>
        </div>
        <label class="control-label col-sm-2" for="song_title">{{ field.label_tag }}</label>
        <div class="col-sm-10">{{ field }}</div>
    </div>
{% endfor %}

                            <div class="form-group">
                                <div class ="col-sm-offset-2 col-sm-10">
                                    <button type="submit" class="btn btn-success">submit</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}

Models.py文件包含存储在 sqlite 默认数据库中的 Shop、Product、User 模型

class Product(models.Model):
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE)
    name = models.CharField(max_length=128)
    category = models.CharField(max_length=32)
    lot = models.DecimalField(max_digits=16, decimal_places=0)
    specs = models.CharField(max_length=5120)
    price = models.FloatField(max_length=16)
    product_logo = models.FileField(default='')


    def get_absolute_url(self):
        return reverse('shopsurfer:detail', kwargs={'pk': self.pk})

    def __str__(self):
        return self.name

Forms.py这是用于为模型创建表单的表单字段

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'category', 'lot', 'specs', 'price', 'product_logo']

Views.py这里是 AddProduct 的代码,我的东西包含错误,但我找不到什么。

class AddProduct (LoginRequiredMixin, CreateView):
    login_url = '/login_user'
    redirect_field_name = 'redirect_to'
    model = Product
    fields = ['name', 'category', 'lot', 'specs', 'price', 'product_logo']

    def form_valid(self, form):
        object_product = form.save(commit=False)
        object_product.shop = self.request.shop
        object_product.save()
        return super(AddProduct, self).form_valid(form)

标签: pythondjangodjango-formsdjango-views

解决方案


使用kwargs我们可以获得主键的值,我们可以使用该值来获取对象Shop

网址.py

 url(r'^(?P<pk>[0-9]+)/add_product/$', views.AddProduct.as_view(), name='add_product'),

视图.py

pk = self.kwargs['pk']
object.shop = get_object_or_404(Shop, pk=pk)

通过这样做,我们可以将值存储到数据库中。

顺便谢谢你帮助@malberts


推荐阅读