Ad

Get() Takes From 2 To 3 Positional Arguments But 4 Were Given. Why Is This Error Occuring? What Is The Solution For This?

I was working on a comment of a blog project. When I typed the code to handle the POST request in the views.py but was getting a error. This was the error 'get() takes from 2 to 3 positional arguments but 4 were given'.

models.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

views.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'})


This is the form :

<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>

I want to get the data from POST request and save it to the database. But writing this code gives me error 'get() takes from 2 to 3 positional arguments but 4 were given'.

Ad

Answer

You can not obtain multiple elements with:

data = request.POST.get('name', 'email', 'comment')

The QueryDict.get(..) method [Django-doc] takes one or two explicit parameters. The first value is the key, and the second one is an optional default (if you do not provide one, None will be used).

You thus can obtain the data with:

name = request.POST.get('name')
email = request.POST.get('email')
comment = request.POST.get('comment')
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()
)
Ad
source: stackoverflow.com
Ad