[英]django use Modelform to save data
I use AJAX to save data into a database and I have a question. 我使用AJAX将数据保存到数据库中,但我有一个问题。 The message board will send 3 variables, which are inputted by the user: name, email, and message.
留言板将发送3个变量,这些变量由用户输入:名称,电子邮件和消息。 It didn't send the IP, but I have to save it into the database.
它没有发送IP,但是我必须将其保存到数据库中。 How can I edit the
views.py
to get the IP? 如何编辑
views.py
以获取IP? Please guide me. 请指导我。
Thank you very much 非常感谢你
forms.py 表格
class MessageForm(ModelForm):
class Meta:
model = Message
fields = ['name', 'email', 'message','ip']
views.py views.py
def create_post(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
# ip = request.META['REMOTE_ADDR'] #not work
m = form.save()
return HttpResponse(2)
else:
form = MessageForm()
this my ajax part: I didn't sent ip in here, 这是我的ajax部分:我没有在这里发送ip,
$.ajax({
url: '{% url 'core:create_post' %}',
data: {
"name":name,
"email":email,
"message":message,
},
type: 'POST',
async: false,
dataType: 'json',
error: function(ts){
alert('操作失敗');
window.location.reload();
},
success: function(dataArr){
if(dataArr == 2){
alert('Sudccess!');
window.location.reload();
}else{
alert('something wrong!');
window.location.reload();
}
}
});
def create_post(request):
if request.method == 'POST':
form = MessageForm(request.POST)
form.ip = request.META['REMOTE_ADDR'] # added 'ip' to the form object here
if form.is_valid():
m = form.save()
return HttpResponse(2)
else:
form = MessageForm()
You need to remove the ip
field from ModelForm
. 您需要从
ModelForm
删除ip
字段。 Otherwise form.is_valid()
will return False
because the ip
field is not from user input. 否则
form.is_valid()
将返回False
因为ip
字段不是来自用户输入的。
Next you have to save the ModelForm
with commit=False
. 接下来,您必须使用
commit=False
保存ModelForm
。 This will not store the data in database but return a Model
object. 这不会将数据存储在数据库中,而是返回一个
Model
对象。 Then you can set the ip
property of that model object and save that model object. 然后,您可以设置该模型对象的
ip
属性并保存该模型对象。 Your code will be something like this: 您的代码将如下所示:
if form.is_valid():
ip = request.META['REMOTE_ADDR'] #get the ip address
m = form.save(false)
m.ip = ip #set the ip address here
m.save() # now saved to database
The good part of a model form is that is always has an instance
attribute that holds the actual model instance, even if it doesn't exist yet in the database. 模型表单的优点在于,它始终具有一个
instance
属性,可以保存实际的模型实例,即使该实例在数据库中尚不存在。 Rafiqunnabi's code can be shortened to this: Rafiqunnabi的代码可以简化为:
if form.is_valid():
form.instance.ip = request.META['REMOTE_ADDR']
m = form.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.