skip to Main Content

I know this question may be duplicates of many in stackoverflow. But those didn’t help me out.
I tried this but didn’t succeed without refreshing.

My models.py is:

class Messages(models.Model):
    id = models.CharField(max_length=8, primary_key=True)
    messages = models.TextField()

This is my html

    <form action="{% url 'messages' %}" method="post" id="new_message_form">
        {% csrf_token %}
        <label for="">message</label><br>
        <textarea id="message" cols="30" rows="10"></textarea><br>
        <button type="submit">Submit</button>
    </form>

This is my views.py:

def messages(request):
    if request.method == "POST":
        message = Messages()
        message.messages = request.POST['message']
        message.save()
        return redirect('messages')

    return render(request, 'app/messages.html', context)

And this is my script:

    $(document).on('submit', '#new_message_form', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/messages/',
            data: {
                message: $('#message').val(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
            },
            success:function(){
                alert("New message created!")
            }
        });
    });

This results in MultiValueDictKeyError

Instead I tried

message.messages = request.POST.get('message', False)

That only gets the value from the input and passes. But I cannot submit it without refreshing. Can anyone help me?

EDIT 1 – MultiValueDictKeyError

Internal Server Error: /messages/
Traceback (most recent call last):
  File "C:UsersmowliAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoutilsdatastructures.py", line 76, in __getitem__
    list_ = super().__getitem__(key)
KeyError: 'message'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersmowliAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersexception.py", line 34, in inner
    response = get_response(request)
  File "C:UsersmowliAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersbase.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:UsersmowliAppDataLocalProgramsPythonPython38-32libsite-packagesdjangocorehandlersbase.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersmowliDesktopProjectsgcepacappviews.py", line 17, in messages
    message.messages = request.POST['message']
  File "C:UsersmowliAppDataLocalProgramsPythonPython38-32libsite-packagesdjangoutilsdatastructures.py", line 78, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'message'
[16/Apr/2020 18:12:30] "POST /messages/ HTTP/1.1" 500 90361

EDIT 2
Actually the form is not even submitted when using this

message.messages = request.POST.get('message', False)

This submits the form with the value ‘False’ in the db. Once the form is submitted I should get an alert right? So please omit this part.

2

Answers


  1. I noticed a problem on your script.

    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken').val(),
    

    If you copied that exactly as it is what’s causing the error. Try this.

    csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(),
    
    Login or Signup to reply.
  2. Solution 1

    Let’s address the problem, There’re 2 solutions. The easy one which is just a better solution to remove useless pain. put the script in your HTML file, And use this line

    csrfmiddlewaretoken: '{%csrf_token%}'
    

    instead of

    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
    

    Solution 2

    The other solution is fixing your own solution. AJAX buttons are not submit buttons, They are just buttons, Remove the action from the form and change the button type to button and it should work.


    EDIT: The problem is not in the csrf_token, However I wanted to show the first solution as an easier way to achieve what you need.


    BUG 2 Why is this not working, I’ve answered this before

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search