'__proxy__'对象在CreateView中没有属性'get' [英] '__proxy__' object has no attribute 'get' in CreateView
问题描述
所以我认为这不是做事情的正确方法,但是我正在尝试学习django,并且正在尝试一些事情。我试图通过在 maker
实例中进行硬编码来为我的 Formula
模型设置外键。
So I'm thinking that this is not the right way to do things, but I am trying to learn django and I am trying some things out. I am trying to set a foreign key for my Formula
model, by hardcoding in an instance of maker
.
型号:
class Cooker(models.Model):
name = models.CharField(max_length=20, name="name")
background = models.CharField(max_length=500, name="background")
class Formula(models.Model):
food = models.CharField(max_length=200, name="food")
maker = models.ForeignKey(Cooker, related_name="cooker_key")
视图
class CookerCreate(CreateView):
template_name = "cookercreate.html"
model = Cooker
fields = ['name','background']
success_url = reverse_lazy('cooker')
class FormulaCreate(CreateView):
template_name = "formulahome.html"
model = Formula
fields = ['food']
success_url = reverse_lazy('formulahome')
def form_valid(self, form):
self.object = form.save(commit = False)
self.object.maker = Cooker.objects.get(pk=1)
form.save()
return reverse_lazy('formula home')
在 FormulaCreate
类,在其中设置 self.object.maker
,我只想在中进行硬编码我已经创建的Cooker
。谢谢
In the FormulaCreate
class where I am setting self.object.maker
, I just want to hard code in a Cooker
that I already created. Thanks
编辑:当我尝试在 FormulaCreate(CreateView)
中提交表单时,出现错误 Exception值:'__proxy__'对象没有属性'get'
When I try to submit the form in my FormulaCreate(CreateView)
I get the error Exception Value: '__proxy__' object has no attribute 'get'
推荐答案
错误的原因是 form_valid
应该返回 Response
对象,并且您正在返回URL。
The reason for your error is that form_valid
should return a Response
object, and you are returning a URL.
与其手动执行操作,不如直接调用父方法,该方法将重定向到您已经拥有的 success_url
定义:
Rather than do this manually you should just call the parent method which will redirect to the success_url
that you have already defined:
def form_valid(self, form):
self.object = form.save(commit = False)
self.object.maker = Cooker.objects.get(pk=1)
form.save()
return super(FormulaCreate, self).form_valid(form)
这篇关于'__proxy__'对象在CreateView中没有属性'get'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!