5

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'

solarissmoke
  • 30,039
  • 14
  • 71
  • 73
ratrace123
  • 976
  • 4
  • 12
  • 24

2 Answers2

17

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)
solarissmoke
  • 30,039
  • 14
  • 71
  • 73
  • This definitely worked thanks so much. So we are making the `Response` object the `FormulaCreate` instance `self`? And then telling it the form for this instance is valid and Django automatically will go straight to the `success url` right? – ratrace123 Jun 04 '16 at 06:29
  • I don't understand your question. The `Response` object is generated by the parent [`form_valid` method](https://docs.djangoproject.com/en/1.9/ref/class-based-views/mixins-editing/#django.views.generic.edit.FormMixin.form_valid), so we don't have to. – solarissmoke Jun 04 '16 at 06:33
  • I misread the first time, I understand now. This is the same that is in the [Form Handling with Class Based Views Django Docs](https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-editing/) – ratrace123 Jun 04 '16 at 13:45
2

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

Mebatsion Sahle
  • 409
  • 2
  • 9