[英]how to save foreign key from django html template
我想从 django 中的 html 模板 select 字段中保存数据。
html 示例代码:
<label for="type" style="color:red;">Short Name *</label>
<input type="text" name="short_name" class="form-control" required placeholder="">
<br> <br>
<select style='bakground-color:red' name="category" required class="form-control show-tick">
<option value="" selected="selected">---------</option>
{% for cat in category %}
<option value="{{ cat }}">{{ cat }}</option>
{% endfor %}
</select>
Django 代码:
Views.py
def addBooks(request):
template = 'admin_panel/add_books.html'
category = Category.objects.all()
book_details = BookDetails.objects.all()
context = {
"page_title": "Add Book",
"category": category,
"book_details" :book_details,
}
if request.method == "POST":
short_name = request.POST.get('short_name', None)
category = request.POST.get('category',None)
book_details = BookDetails.objects.create(short_name=short_name, category=category)
return render(request, template,context)
模型.py
class BookDetails(models.Model):
id = models.AutoField(primary_key=True)
short_name = models.CharField(max_length=50, unique=True, db_index=True)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE
)
错误显示:/superadmin/add_books/ 处的 ValueError 无法分配“'Story'”:“BookDetails.category”必须是“Category”实例。
如何解决这个问题呢?
在模板option value={{cat.id}}
鉴于:
BookDetails.objects.create(short_name=short_name, category_id=category)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.