【发布时间】:2022-01-18 00:06:11
【问题描述】:
我设置了 2 个 html/CSS 表单,还设置了一个 SQL 数据库,其中包含表单上所有内容的值。我需要执行哪些步骤来确保表单和数据库已链接?
P.S 我已经创建了一个模型并将东西迁移到 SQL 数据库。
【问题讨论】:
标签: django postgresql django-models django-views
我设置了 2 个 html/CSS 表单,还设置了一个 SQL 数据库,其中包含表单上所有内容的值。我需要执行哪些步骤来确保表单和数据库已链接?
P.S 我已经创建了一个模型并将东西迁移到 SQL 数据库。
【问题讨论】:
标签: django postgresql django-models django-views
您可以使用模型表单。 https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#modelform
EG
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but dont save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
然后从 .这将具有必要的字段。
或者您可以创建一个表单,其中包含您为其创建 html/css 表单的字段,然后呈现它。提交后,单独保存到模型中 例如
class CommentForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
body = forms.CharField(required=False,widget=forms.Textarea)
if request.method == 'POST':
# Form was submitted
form = CommentForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
comment = Comment(
name = cd['name'],
email = cd['email'],
body = cd['body'],
)
comment.save()
else:
form = EmailPostForm()
【讨论】: