[英]How to submit a form without refreshing in django?
I know this question may be duplicates of many in stackoverflow.我知道这个问题可能与stackoverflow中的许多问题重复。 But those didn't help me out.
但这些并没有帮助我。 I tried this but didn't succeed without refreshing.
我试过这个,但没有刷新就没有成功。
My models.py
is:我的
models.py
是:
class Messages(models.Model):
id = models.CharField(max_length=8, primary_key=True)
messages = models.TextField()
This is my html
这是我的
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
:这是我的
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
:这是我的
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这导致 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编辑 1 - MultiValueDictKeyError
Internal Server Error: /messages/
Traceback (most recent call last):
File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\datastructures.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:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\mowli\Desktop\Projects\gcepac\app\views.py", line 17, in messages
message.messages = request.POST['message']
File "C:\Users\mowli\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\datastructures.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编辑 2 实际上,使用此表单时甚至没有提交表单
message.messages = request.POST.get('message', False)
This submits the form with the value 'False' in the db.这将提交数据库中值为“False”的表单。 Once the form is submitted I should get an alert right?
提交表单后,我应该收到警报吗? So please omit this part.
所以请省略这部分。
Let's address the problem, There're 2 solutions.让我们解决这个问题,有2个解决方案。 The easy one which is just a better solution to remove useless pain.
简单的方法只是消除无用疼痛的更好解决方案。 put the script in your HTML file, And use this line
将脚本放入您的 HTML 文件中,并使用这一行
csrfmiddlewaretoken: '{%csrf_token%}'
instead of代替
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
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. AJAX 按钮不是提交按钮,它们只是按钮,从表单中删除
action
并将按钮类型更改为button
,它应该可以工作。
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.编辑:问题不在
csrf_token
中,但是我想将第一个解决方案展示为一种更简单的方法来实现您所需要的。
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(),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.