所以我試圖在這個頁面上添加只有名稱的新類別。但是當我嘗試它時,我只是得到一個“非字串型別”作為名稱。所以它有效,我想只是不接受我在 html 輸入中給出的任何內容。
HTML:
<input type="text" class="form-control" placeholder="Name" id = "category-create-name" name=
"category_name">
<input type="submit" class="login-button" value="Post">
模型:
class Category(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
形式:
class CategoryCreateForm(forms.ModelForm):
class Meta:
model = Category
fields = ('name',)
widgets = {
'category_name': forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Name', 'id':'category-create-name'}),
}
看法:
class CategoryCreateView(CreateView):
form_class = CategoryCreateForm
template_name = 'product/new_category.html'
success_url = '/dashboard/'
uj5u.com熱心網友回復:
我在這里看到了一些事情。首先是你的表格。在 的widgets屬性中class Meta,該字典中的鍵必須是您的fields屬性中的欄位名稱。換句話說,您需要更改'category_name'為'name'. 其次,在用于視圖的模板中。您似乎手動定義了一個單獨的輸入欄位,而不是您的視圖和表單所期望的輸入欄位。您應該像這樣在模板中定義表單:
<form method="POST">
{% csrf_token %}
{{ form_as_p }}
<input type="submit" class="login-button" value="Post">
</form>
在模板{{ form.as_p }}中將采用您提供給視圖的表單,并在呈現到頁面時自動在 html 中創建它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/396959.html
