On Fri, Nov 5, 2010 at 10:29 PM, Valentin Golev <[email protected]> wrote:
> Hello,
>
> I'm still playing with brand new class-based views. I think I'm not
> wrong about writing my experiences, questions and ideas so you
> developers could polish the API more (if I'm being useless here,
> sorry).
>
> My first question is, that is "the right way" to handle creation of
> objects with parameters which can't be set in the creation form?
>
> Let's say we have a model:
>
> class Item(models.Model):
> owner = models.ForeignKey(User)
> title = models.CharField(max_length=120)
>
> and we have a form
>
> class ItemForm(forms.ModelForm):
> class Meta:
> exclude = ('owner',) # because one can only add items which
> belongs to him
>
> so if we just write
>
> class ItemCreateView(CreateView):
> model = Item
>
> the form won't be saved! And I have to do something like this:
>
> class ItemCreateView(CreateView):
> model = Item
> def form_valid(self, form):
> obj = form.save(commit=False)
> obj.owner = self.request.user
> obj.save()
> self.object = obj
> return HttpResponseRedirect(self.get_success_url())
There's a much easier way to do this, and no extra features are required:
class ItemCreateView(CreateView):
form_class = ItemForm
def form_valid(self, form):
form.instance.owner = self.request.user
return super(MyView, self).form_valid(form)
> Another question, or I'd rather say remark, is what Mixins are awesome
> and seem better than decorators. My views.py file looks like this now:
...
> and I like this "style" more than dancing with old-school decorators
> in one way or another. We've already had this conversation, but I
> can't still can't see neither why this style is bad nor how should I
> write it instead? (By "bad" and "should write" I mean "not supported
> and not encouraged by Django" and "supported and encouraged by
> Django").
Well, Mixins predate decorators by some time; Mixins are really just a
pattern of multiple inheritance.
It's not a matter of one being better than the other, either. They are
for solving different problems. Decorators allow you to wrap an
existing block of logic with entry and exit conditions. Mixins allow
you to compose complex behaviors out of smaller primitives, and
enhance internal behaviors by replacing key components.
In some cases, you will be able to get the same outcome using either
approach; it's really up to you as to which one you want to use.
Yours
Russ Magee %-)
--
You received this message because you are subscribed to the Google Groups
"Django developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/django-developers?hl=en.