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

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'



Solution 1:[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)

Solution 2:[2]

If you are using the post method return redirect('formula home') works too.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 solarissmoke
Solution 2 Mebatsion Sahle