我在尝试将表单数据插入表单时收到错误,对象没有属性'is_valid'。下面是我的代码的结构:
Views.py:
def add_user(request):
form = Car(request.POST)
if request.method == 'POST' and form.is_valid():
last_store = form.cleaned_data.get['value']
make = request.POST.get('make', '')
model = request.POST.get('model', '')
..
car_obj = Car(last_store = last_store, make = make, model = model, series = series, series_year = series_year, price_new = price_new, engine_size = engine_size, fuel_system = fuel_system, tank_capacity = tank_capacity, power = power, seating_capacity = seating_capacity, standard_transmission = standard_transmission, body_type = body_type, drive = drive, wheelbase = wheelbase, available = available)
car_obj.save()
return HttpResponseRedirect('/inventory/add/')
else:
form = Car()
return render(request, 'cars/inventory-add.html', {})
班级:
class Car(models.Model):
make = models.CharField(max_length=200, null=False)
model = models.CharField(max_length=200, null=False)
series = models.CharField(max_length=200, null=False)
series_year = models.IntegerField(null=False)
price_new = models.IntegerField(null=False)
..
last_store = models.ForeignKey(Store, on_delete=models.DO_NOTHING, related_name="last_store")
available = models.BooleanField(null=False, default=True)
def __str__(self):
return(self.make + " " + self.model)
CarForm(forms.py)
class CarForm(forms.ModelForm):
class Meta:
model = Car
fields = ['last_store', 'make', 'model', 'series', 'series_year', 'price_new', 'engine_size', 'fuel_system', 'tank_capacity', 'power', 'seating_capacity', 'standard_transmission', 'body_type', 'drive', 'wheelbase', 'available']
与last_store
一样,错误也位于form.is_valid()
内,显然我无法使用form.cleaned_data
,但是form.is_valid()
似乎根本不存在?如上课所示,last_store
是外键类型,因此当用户在表单中输入输入时,我正在努力为其设置默认值。 last_store
变量正在尝试从包含SELECT选项的输入表单数据中获取值。
答案 0 :(得分:3)
您的模型和表单之间都存在冲突,它们都名为Car
。通常,您可以通过重命名格式CarForm
来解决此问题。
请注意,您通常不需要使用car_obj = Car(...)
创建对象。如果您使用,则可以将代码简化为car_obj = form.save()
。您还应该在CarForm(request.POST)
检查中移动if request.method == 'POST'
,并将form
包含在模板上下文中。放在一起,你会得到类似的东西:
def add_user(request):
if request.method == 'POST':
form = CarForm(request.POST)
if form.is_valid():
car_obj = form.save()
return HttpResponseRedirect('/inventory/add/')
else:
form = CarForm()
return render(request, 'cars/inventory-add.html', {'form': form})