我从头开始重启项目后遇到了一个问题,我可以手动添加一个值到我的django模型中,但当它来自用户输入的变量时,它只传递一个空白字符串。
进程所以,我有一个简单的模型Tech和我有一个页面,你可以添加一个新的名称到Tech模型.我输入的名称(在这里,我输入的名称ede dede),点击添加,然后我把它发送到后台使用AJAX。
在VSCODE的shell中,我看到我收到了元素,但是当我把它添加到我的django模型Tech中,然后在Tech中打印新的对象时,它有一个ID,一切都有,但是名字是一个空白字符串""
此外,当我把它打印在我的python代码中时,它甚至没有给我queryset,我什么都没有。
怎么会这样?
下面是我的一段代码
VIEWS.PY:
@ajax_required
@require_http_methods(["POST"])
def AddNewEmployee(request):
newtechname = request.POST.get('new_employee').title()
response_data = {}
print('new employee: '+newtechname)
print(type(newtechname))
if Tech.objects.filter(name=newtechname).exists():
response_data['success'] = False
response_data['result'] = 'This name already exists'
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
else:
techname = Tech(name=newtechname)
techname = Tech(selected=True) #add new tech to model
techname.save() #save new name to model
response_data['success'] = True
response_data['result'] = 'Added a new teammate successfully!'
response_data['tech_id'] = techname.id #get new name id from model
response_data['tech_name'] = techname.name
response_data['tech_selected'] = techname.selected
print(techname)
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
MODELS.PY
class Tech(models.Model):
name = models.CharField(max_length=200)
selected = models.BooleanField(default=False)
def __str__(self):
return self.name
JS.PY: MODELS.PY
$('#add-employee').on('submit',function(e){
e.preventDefault();
if(e.target.getAttribute('id')==('add-employee')){
console.log('form submitted!'); //sanity check
AddNewEmployee();
}
});
function AddNewEmployee(){
console.log('AddNewEmployee is working!');
console.log($('#addtech_id').val()); //get the input value from input id
const addemployee_form_url = $('#add-employee').attr('action'); //get the form url
new_employee = $('#addtech_id').val(); // data sent with the post request
console.log(typeof new_employee);
let request_data = {
'new_employee': new_employee,
'csrf_token':csrftoken
}
$self = $(this)
$.ajax({
url : addemployee_form_url, //endpoint
type : "POST", //httpmethod
data : request_data,
//handle a successful response
success : function(response){
$('#addtech_id').val(''); //remove the value from the input
console.log(response); // log the returned json to the console
console.log("A connexion to the backend has been established with success!"); // sanity check
//Add to selected list
if (response['success']){
AddToSelectedList(response['tech_id'], response['tech_name']);
$('#results').html("<h5><div class='alert-box alert radius' data-alert style='color:green;'>"+response['result']+"</div><h5>");
}
else{
$('#results').html("<h5><div class='alert-box alert radius' data-alert style='color:red;'>This name is already in the list!</div><h5>");
}
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
}
我不明白的是,为什么它正确地打印(views.py中的)newtechname,我甚至可以看到它的类型是一个字符串,所以没有问题,然后,当techname = Tech(name=newtechname)时,它将一个空字符串传给Tech模型。
谢谢你的帮助!我有一个问题。
问题出在这里
else:
techname = Tech(name=newtechname)
techname = Tech(selected=True) #add new tech to model
techname.save() #save new name to model
你试图创建一个不存在的对象,因为Tech(name=newtechname)并没有创建对象,你可以在使用Tech.objects.create()之后再使用。
所以在你的情况下,用传统的objects.create()来改变,就解决了这个问题。