0

i have bulit a books management app in django-rest framework with UI in html css and bootstrap. But when i'm trying to add new authors to the database doing a post request i'm getting this multivalue dict error even though i checked the name in the form.

traceback

Environment:


Request Method: POST
Request URL: http://127.0.0.1:8000/authors/postform/

Django Version: 3.2.9
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'genebox',
 'rest_framework']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__
    list_ = super().__getitem__(key)

During handling of the above exception ('Name'), another exception occurred:
  File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Online Test\GeneBOX full stack (27th)\myproject\genebox\views.py", line 58, in author_save
    name = request.POST['Name']
  File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)

Exception Type: MultiValueDictKeyError at /authors/postform/
Exception Value: 'Name'

```urls.py```

    urlpatterns = [
    path('', views.home, name='home'),
    path('authors/', views.Author_list, name='all_author'),
    path('authors/postform/', views.author_save, name='authsave'),
    path('books/', views.Book_list, name='all_books'),
    path('authorcsv/', views.author_csv, name='author_csv'),
    path('bookcsv/', views.book_csv, name='book_csv')
    ]

models.py

class Authors(models.Model):
Gender_choice = (
    ('M', 'Male'),
    ('F', 'Female'),
    ('Other', 'Others'),
)
Name = models.CharField(max_length=70)
Age = models.IntegerField()
Gender = models.CharField(max_length=20, choices=Gender_choice)
Country = models.CharField(max_length=70)

def __str__(self) -> str:
    return self.Name

author.html

    <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="staticBackdropLabel">Add New Author</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          
            <form action='{% url 'authsave' %}' method='post'>
                {% csrf_token %}
                <div class="form-group">
                  <label for="exampleInputEmail1">Author's Name</label>
                  <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Author Name" name="Name" value="{{ Name }}">
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Age</label>
                  <input type="number" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Age" value="{{Age}}" name="Age">
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Gender</label>
                  <select id="inputState" class="form-control" name="Gender" value='{{Gender}}'>
                    <option selected>Choose Gender</option>
                    <option value='Male'>Male</option>
                    <option value='Female'>Female</option>
                    <option value='Other'>Others</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="exampleInputEmail1">Country</label>
                  <input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Country Name" value="{{Country}}" name="Country">
                </div>
                <button type="submit" class="btn btn-primary my-2">Submit</button>
              </form>

        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>  

views.py

@api_view(['GET','POST'])
def Author_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
    print('get')
    authors = Authors.objects.all()
    serializer = AuthorSerializer(authors, many=True)
    context = {
        'author': authors
    }
    print(context)
    return render(request, 'author.html', context)

elif request.method == 'POST':
    print('post')
    serializer = AuthorSerializer(data=request.data)
    # checking if serializer is valid
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializer.py

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
       model = Authors
    fields = ['Name', 'Age', 'Gender', 'Country']

Anyone Help will be apperciated

  • Does this answer your question? [django MultiValueDictKeyError error, how do I deal with it](https://stackoverflow.com/questions/5895588/django-multivaluedictkeyerror-error-how-do-i-deal-with-it) – Ankit Tiwari Feb 27 '22 at 13:30

1 Answers1

0

Use the MultiValueDict's get method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.

is_private = request.POST.get('is_private', False)