python - get() 接受 2 到 3 个位置参数,但给出了 4 个。为什么会出现这个错误?解决这个问题的办法是什么?

标签 python django python-3.x post django-models

我正在对一个博客项目进行评论。当我在views.py 中键入处理 POST 请求的代码时,却收到错误。这是错误“get() 采用 2 到 3 个位置参数,但给出了 4 个”。

模型.py

class commenttable(models.Model):
    comment_id = models.AutoField(primary_key=True, default=0)
    blog = models.TextField()
    comment_name = models.CharField(max_length=200)
    comment_email = models.EmailField()
    comment_Text = models.TextField()
    comment_date = models.DateField()

    def __str__(self):
        return self.comment_Text

View .py

from .models import commenttable

...

def post_comment(request, blog_id):
    if request.method == 'POST':
        data = request.POST.get("name", "email", "comment")
       # blog = get_object_or_404(Blog_tables, pk=blog_id)
        p = commenttable(blog= data.name, comment_name=data.email, comment_email= data.email, comment_Text= data.comment, comment_data = timezone.now())
        p.save()
        return HttpResponseRedirect('/thanks/')
    else:
        return render(request, '/blogs/' + blog_id + '/comment', {'error_message': 'Error'})


这是表格:

<form action="/blogs/{{blog_id}}/comment" method ="post">
            {% csrf_token %}

            <input type="text" name="name" id="name" placeholder="Enter Your Name"/>
            <input type="text" name="email" id="email" placeholder="Enter Your Email"/>
            <input type="text" name="comments" id="comments" placeholder="Comments here"/>

            <input type="submit" value="Post"/>
        </form>

我想从POST请求中获取数据并将其保存到数据库中。 但是编写此代码会出现错误“get() 需要 2 到 3 个位置参数,但给出了 4 个”。

最佳答案

您无法通过以下方式获取多个元素:

data = request.POST.<s>get('name', 'email', 'comment')</s>

QueryDict.get(..) method [Django-doc]采用一两个显式参数。第一个值是,第二个值是可选默认值(如果您不提供,则将使用None)。

因此,您可以通过以下方式获取数据:

name = request.POST.<b>get('name')</b>
email = request.POST.<b>get('email')</b>
comment = request.POST.<b>get('comment')</b>
blog = get_object_or_404(Blog_tables, pk=blog_id)
p = commenttable.objects.create(
    blog=blog,
    comment_name=name,
    comment_email=email,
    comment_Text=comment,
    comment_data=timezone.now()
)

关于python - get() 接受 2 到 3 个位置参数,但给出了 4 个。为什么会出现这个错误?解决这个问题的办法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362596/

相关文章:

python - 从与 BeautifulSoup 中的特定模式匹配的页面中提取所有 URL

python - 为什么使用 fast_executemany=True 调用 cursor.executemany() 会导致段错误?

django - 从 django-rest-framework 返回 CSV 格式?

python - Bokeh 对数轴格式为十进制

python - 为什么 s7 ="hello",'world' ; Python 中的 print(s7) 发出 ('hello' 、 'world' )?

python - 退出 0 与返回 0 Python 首选项

python - 计算 2D 插值积分时出错。比较 numpy 数组

python - Django,来自 USStateField 的完整州名

python - 是否可以从字符串制作 Django urlpatterns?

python - 一页上的多个表单 Python FLASK