关于从 Django 中的表单获取输入并将该数据传输到 SQL 数据库的问题

Question regarding taking input from a form in Django and transferring that data to a SQL database

我设置了 2 个 html/CSS 表单,我还设置了一个 SQL 数据库,其中包含表单上所有内容的值。我需要执行哪些步骤才能确保表单和数据库已链接?

P.S 我已经创建了一个模型并将内容迁移到 SQL 数据库。

您可以使用模型表格。 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()