Вопрос

I am fairly new to CBV and I have the following question: I see that there is CreateView that would show you the "empty" form to create a new database entry and there is UpdateView that would show you the form for the existing entry for update.

What I need is some kind of mix of it: present the user with the form for the lastly viewes/updated entry, but if the database has no entries yet (e.g. new user), present the user with a default ("empty") form.

So, there are 2 points here:

  1. Have a model that contains lastly viewed/updated entry per user: what should this model be?

  2. Have a view that allows to present forms as specified above. Is there a generic or semi-generic way to do that in Django? What kind of CBV should I be using?

Thanks.

Это было полезно?

Решение

I haven't tested this so I'm not sure if this will work.

from django.views.generic.edit import ModelFormMixin, ProcessFormMixin

class MyView(ModelFormMixin, ProcessFormMixin):
    def get(self, request, *args, **kwargs):
        try:
            self.object = MyModel.objects.latest("id")
        except MyModel.DoesNotExist:
            self.object = None
        return super(MyView, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        try:
            self.object = MyModel.objects.latest("id")
        except MyModel.DoesNotExist:
            self.object = None
        return super(MyView, self).post(request, *args, **kwargs)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top