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

10,232

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)
Share:
10,232
ratrace123
Author by

ratrace123

Updated on June 05, 2022

Comments

  • ratrace123
    ratrace123 almost 2 years

    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'