gpt4 book ai didi

javascript - 使用 setattr() 更新对象实例

转载 作者:行者123 更新时间:2023-11-28 05:17:26 25 4
gpt4 key购买 nike

我有一个模型类,它有一个引用 django DB 对象的属性。我想使用带有 setattr() 的单个 View 来更改此属性,我用它来更改此对象的任何属性。

问题是,我似乎无法通过堆栈传递对象实例。我不确定是否可以使用 setattr() 来实现此目的。实际上,我什至不确定问题是否出在我尝试使用 setattr() 或其他方面 - 请让我知道!

POST 尝试时出错:

ValueError at /dollhouseupdate/1
Cannot assign "u'Citadel'": "Dollhouse.dh_background" must be a "Background" instance.

型号:

class Dollhouse(models.Model):
dollhouse_name = models.CharField(max_length=100)
user = models.ForeignKey(User)
dh_background = models.ForeignKey(Background)
def __str__(self):
return self.dollhouse_name

模板:

    <select id="background-select">
<option value="null">Change Background</option>
{% for background in background_objects %}
<option value="{{ background }}">{{ background.bg_name }} </option>
{% endfor %}
</select>

查看:

def dollhouseupdate(request, dollhouseid):
if request.method == 'POST':
workingdollhouse = Dollhouse.objects.get(id=dollhouseid)
if request.POST.get('erase') == "true":
workingdollhouse.delete()
return HttpResponse("Dollhouse deleted!")
else:
data = (request.POST).dict()
for key, value in data.items():
setattr(workingdollhouse, key, value)
workingdollhouse.save()
return HttpResponse("Dollhouse {} saved!".format(workingdollhouse.dollhouse_name))

Javascript:

//change dollhouse background
$("#background-select").change(function() {
if($("#background-select").val() != null) {
var dollhouseid = workingDollhouse;
var dh_background = $("#background-select").val()
console.log("changing background to " + dh_background);
$.ajax("http://127.0.0.1:8000/dollhouseupdate/"+dollhouseid, {
type: 'POST',
data: {
dh_background: dh_background,
}
})
.done(function(response){
console.log("The request is complete!");
console.log(response);
window.location = "http://127.0.0.1:8000/";
})
.fail(function() {
console.log("Sorry, there was a problem!");
})
};
});

最佳答案

您正在 POST 变量中传递对象 ID,而不是实际对象本身(无论如何您都不能这样做)。要么更改以下部分

data: {
dh_background: dh_background,
}

data: {
dh_background_id: dh_background,
}

或者使用 View 代码中的 id 获取对象实例。

关于javascript - 使用 setattr() 更新对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856697/

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