【问题标题】:Question regarding taking input from a form in Django and transferring that data to a SQL database关于从 Django 中的表单获取输入并将该数据传输到 SQL 数据库的问题
【发布时间】:2022-01-18 00:06:11
【问题描述】:

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

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

【问题讨论】:

    标签: django postgresql django-models django-views


    【解决方案1】:

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

    【讨论】:

    • 这样设置了,但是当我提交某些内容时,它以 GET 而不是 POST 的形式出现,知道为什么或如何更改它吗?
    • 。随着'动作属性..添加“方法如图所示..即在模板中
    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 2020-09-29
    相关资源
    最近更新 更多