'__proxy__' object has no attribute 'get' in CreateView

流过昼夜 提交于 2019-12-25 07:14:05

问题


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.

Models:

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")

Views

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')

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

EDIT: When I try to submit the form in my FormulaCreate(CreateView) I get the error Exception Value: '__proxy__' object has no attribute 'get'


回答1:


The reason for your error is that form_valid should return a Response object, and you are returning a 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)


来源:https://stackoverflow.com/questions/37626931/proxy-object-has-no-attribute-get-in-createview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!