gpt4 book ai didi

javascript - 使用 Django、Ajax、jQuery 提交表单而不刷新页面?

转载 作者:行者123 更新时间:2023-11-28 03:07:17 24 4
gpt4 key购买 nike

我是 Django 的新手。我需要一个简单的例子。如何使用 Django、Ajax、jQuery 提交表单(帖子)而不刷新页面?

这是我的表单、 View 和模板:

View .py

import json
from django.shortcuts import *
from django.template import RequestContext
from linnea.web_interface import run_linnea
from linnea_demo_app.forms import *

def linnea_demo(request):
if request.method == "POST":
form = AdvertForm(request.POST)

message = 'something wrong!'
if(form.is_valid()):
print(request.POST['title'])
message = request.POST['title']

return HttpResponse(json.dumps({'message': message}))

return render_to_response('linnea_demo.html',
{'form':AdvertForm()}, RequestContext(request))

表单.py

from django import forms
from django.forms import ModelForm
from linnea_demo_app.models import Advert

class AdvertForm(ModelForm):
class Meta:
model = Advert

模型.py

from django.db import models


class Advert(models.Model):
text = models.TextField()

index.html

<form action="" method="POST" id="post-form">
{% csrf_token %}
{{form.as_p}}
<input type="submit" id="btnGetKernel" class="" value="Generate Kernel"/>
</form>

.js

$('#form').submit(function(e){
$.post('/url/', $(this).serialize(), function(data){
$('.message').html(data.message);
});
e.preventDefault();
});

但是,我收到了这个错误:

django.core.exceptions.ImproperlyConfigured: Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form AdvertForm needs updating.

我做得对吗?

最佳答案

错误信息非常清楚。

Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form AdvertForm needs updating.

您需要更新 AdvertForm 以包含 fieldsexclude 属性。

from django import forms
from django.forms import ModelForm
from linnea_demo_app.models import Advert

class AdvertForm(ModelForm):
class Meta:
model = Advert
fields = ['text']

关于javascript - 使用 Django、Ajax、jQuery 提交表单而不刷新页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60492771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com