类型对象'ProductForm'没有属性'cleaned_data'django

时间:2018-09-06 17:00:09

标签: django python-3.x django-models django-forms

我正在使用Django 2.0.x和Python 3.6制作表单,但出现错误

我不确定发生了什么,有人可以帮我吗?谢谢!

  

Product / forms.py

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    title       = forms.CharField(label='',
                    widget=forms.TextInput(attrs={"placeholder": "Your title"}))
    description = forms.CharField(
                        required=False,                         
    widget=forms.Textarea())
    class Meta:
        model = Product
        fields = [
            'title',
            'description',

        ]
  

Product / views.py

from django.shortcuts import *
from django.http import *
from .models import Product
from .forms import ProductForm
import hashlib

# Create your views here.

def home_view(request,slug,*args,**kwargs):
    form= ProductForm(request.POST or None)
    try:
        productobject=Product.objects.get(id=1)
    except Product.DoesNotExist:
        raise Http404

    if form.is_valid():

        newProduct=Product.objects.create(
        title = "jose",

        description=ProductForm.cleaned_data.get["description"]


        )

        if newProduct:
            return HttpResponseRedirect("/)

        else:
            newProduct = ProductForm()

context= {
        "sampletext": "text",
        "form": form,
        "productobject":productobject,

    }
    return render(request, "home.html",context)

代码给了我这个错误

类型对象'ProductForm'没有属性'cleaned_data'

1 个答案:

答案 0 :(得分:1)

您从cleaned_data 获取ProductForm,而不是从{{ 1}}。

因此,您可以改用form来解决它,例如:

ProductForm

但是,话虽如此,工作流不是惯用。例如,form始终会成功,无论这是否是有效的def home_view(request,slug,*args,**kwargs): form= ProductForm(request.POST or None) try: productobject=Product.objects.get(id=1) except Product.DoesNotExist: raise Http404 if form.is_valid(): newProduct=Product.objects.create( title = "jose", description=form.cleaned_data.get["description"] ) if newProduct: return HttpResponseRedirect("/") else: newProduct = ProductForm() context= { "sampletext": "text", "form": form, "productobject":productobject, } return render(request, "home.html",context)if newProduct可能会引发异常。更加惯用的工作流程是:

newProduct