我已经尝试解决这个问题几个小时了。我似乎看不出导致错误的原因:(
views.py
@login_required
def create_brand(request):
template_name = "poc/brand_add.html"
context = {}
context["form"] = forms.BrandForm()
if request.method == "POST":
form = forms.BrandForm(request.POST)
if form.is_valid():
print(form.cleaned_data)
form.save()
return render(request, template_name, context=context)
else:
return render(request, template_name, context=context)
表格.py
class BrandForm(forms.ModelForm):
class Meta:
model = models.Brand
fields = ('brand_id' , 'brand_name', 'company')
模型.py
class Brand(models.Model):
brand_id = models.AutoField(primary_key=True)
brand_name = models.CharField(max_length=255)
company = models.ForeignKey('Company', models.DO_NOTHING)
date_created = models.DateTimeField(auto_now_add=True, blank=True)
class Meta:
managed = False
db_table = 'brand'
def __str__(self):
return f"{self.brand_name}"
模板:brand_add.html
{% extends 'base.html' %}
<body>
{% block content %}
<div class="container">
<h1>Create new Brand</h1>
<form action="{% url 'poc:list_brand' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Create">
</form>
</div>
{% endblock %}
</body>
url.py
path('brand/', views.BrandListView.as_view(), name='list_brand'),
path('brand_add/', views.create_brand, name='create_brand'),
path('brand/<int:pk>', views.BrandDetailView.as_view(), name='detail_brand'),
仍然无法添加“品牌” 是因为使用基于函数的视图而不是 CBV 吗?
您正在将表单提交到列表视图地址:
action="{% url 'poc:list_brand' %}"
,列表视图可能不会收到 POST 请求!