How to Solve Error Message MultiValueDictKeyError at /url_name/ in Django

Posted on

This is another article referring on the error message triggered upon executing a page based on Django framework. The error message is shown in the title of this article which is “MultiValueDictKeyError at /link_name/’. Below is the actual image of the error related to the error specified in the title of the article :

How to Solve Error Message MultiValueDictKeyError at /url_name/ in Django
How to Solve Error Message MultiValueDictKeyError at /url_name/ in Django

 

The error is actually specified in the above image in a real condition. The link_name or url_name specified in the above image as the example for solving the error is ‘network_add’. The error is actually happened on accessing an url name ‘network_add’ specified in the URL which is defined in a file named ‘urls.py’ :

url(r'^network_add/$', network_views.add, name='network_add'),

The actual definition of the above snippet code will direct the execution to a view named ‘network_views’ and with the method named ‘add’. Basically the method content is shown as follows :

@login_required
def add(request):
    network_device = NetworkDevice(serial_number=request.POST['serial_number'])
    template = 'network/add.html'
    context = locals()
    return render(request, template, context)

So, the main problem which is executing the method actually because of the first line inside the method as shown below :

network_device = NetworkDevice(serial_number=request.POST['serial_number'])

The actual execution is considered to be an error since the rendering process of the page ‘add.html’ located in a folder named ‘network’. The problem is in the above line where the variable named ‘network_device’ is executed, it is actually receiving an argument from a POST request method. So, since there is no actual POST request method, it will generate an error as shown in the above. To solve the actual problem, the only thing which is considered as a solution and it is a logical one is by adding a line for detecting the POST request method and several modifications as shown below :

def add(request):
        if request.method == 'POST'
       network_device = NetworkDevice(serial_number=request.POST['serial_number'])
       context = locals('network_device' : network_device)
        else
           context = locals()

    template = 'network/add.html'
    return render(request, template, context)

By adding a certain condition for checking the POST request method, the line will not executed unless there is an actual POST request method fired from the URL called which in the context of this article, it is ‘network_add’.

Leave a Reply