我正在尝试在我的模型中保存一个表单,但是该表单无法正常工作。 当我第一次填写字段并按“提交”按钮时,页面正在重新加载。当我第二次尝试时,出现此错误:
django.db.utils.OperationalError: table user_profile_product has no column named product_user_id
我的代码:
Views.py
def post_product(request):
form = ProductForm()
template_name = 'user_profile/add_product.html'
if request.method == 'POST':
form= ProductForm(request.POST)
if form.is_valid():
name = form.cleaned_data['product_name']
description = form.cleaned_data['product_description']
price = form.cleaned_data['product_price']
user = request.user
product = Product(product_name=name, product_description=description, product_price=price, product_user=user)
product.save()
return render(request, 'home_page/home.html', {'product': product})
else:
form = ProductForm()
return render(request, template_name, {'form':form})
Models.py
class Product(models.Model):
product_name = models.CharField(max_length=150 )
product_description = models.CharField(max_length=300)
product_price = models.DecimalField(max_digits=6, decimal_places=2)
product_user = models.ForeignKey(User, on_delete=models.CASCADE)
Forms.py
class ProductForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(ProductForm, self).__init__(*args, **kwargs)
product_name = forms.CharField(max_length=150, required=True)
product_description = forms.CharField(max_length=300, required=True)
product_price = forms.DecimalField(max_digits=6, decimal_places=2)
class Meta:
model = Product
fields = ('product_name', 'product_description', 'product_price')
迁移文件
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('product_name', models.CharField(max_length=150)),
('product_description', models.CharField(max_length=300)),
('product_price', models.DecimalField(decimal_places=2, max_digits=6)),
('product_user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
更新:
当我删除外键product_user时,可以将表单保存在模型中,但是当我尝试使用外键保存该表单并指定request.user时,该表单将无法正常工作。我在模型中做错了吗?