我是 Django 的初學者,我想在資料庫中保存表單資料,但我無法保存,也跟著一些教程。
表單.py:
from django.forms import ModelForm
from .models import *
class listsForm(ModelForm):
class Meta:
model = todo
fields = "__all__"
視圖.py:
from django.shortcuts import render
from .models import *
from .form import *
def index(request):
lists = todo.objects.all()
form = listsForm()
context = {
'lists':lists,
'form':form,
}
if request.method == 'POST':
form = listsForm(request.POST)
if form.is_valid:
form.save()
return render(request, 'index.html', context)
模型.py:
from django.db import models
class todo(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
created = models.DateField(auto_now_add=True)
def __str__(self):
return self.title
uj5u.com熱心網友回復:
為什么要渲染listForm?您的表單應該在未呈現的模板中!
在 中index.html,您的表單應如下所示:
<form action="{% url 'create_todo' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" class="form-control" id="title" required></div>
<div class="form-group">
<label for="Description">Description</label>
<textarea name="description" class="form-control" id="description" ></textarea></div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
在 views.py
def index(request):
return render(request, 'index.html')
def create_todo(request):
if request.method == 'POST':
form = listsForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
在 urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('create_todo/', views.create_todo, name='create_todo')
]
您仍然需要渲染現有的待辦事項,最好在另一個模板中。
所以在 views.py
def alltodos(request):
todos = Todo.objects.all()
return render(request, 'index.html', {'todos':todos})
在index.html, 上面或后面, 沒有關系, 只是為了清晰可見
<div class="row justify-content-center mt-5">
<div class="col-md-10">
{% if todos %}
<div class="list-group">
{% for todo in todos %}
<a class="list-group-item list-group-item-action><b>{{ todo.title }}</b>{{ todo.description|truncatechars:30 }}{% endif %}</a>
{% endfor %}
</div>
{% else %}
<div hljs-string">r">
<h2>Looks like you don't have any todos!</h2>
<br>
</div>
{% endif %}
</div>
</div>
在urls.py加
path('todos', views.alltodos, name='alltodos'),
高級專案礦井
uj5u.com熱心網友回復:
我已經找出它不起作用的原因,
我正在使用<input type="button">提交按鈕,但是當我將其更改為<button type="submit">有效時。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/334392.html
上一篇:django.core.exceptions.FieldError:無法將關鍵字“productcategory_id”決議為欄位。選項有:國家/地區、country_id、id、名稱、供應商?
