Suppose I have two models:
class Topic(models.Model):
title = models.CharField()
# other stuff
class Post(models.Model):
topic = models.ForeignKey(Topic)
body = models.TextField()
# other stuff
And I want to create a form contains two fields: Topic.title
and Post.body
. Of course, I can create the following form:
class TopicForm(Form):
title = forms.CharField()
body = forms.TextField()
# and so on
But I don't want to duplicate code, since I already have title
and body
in models. I'm looking for something like this:
class TopicForm(MagicForm):
class Meta:
models = (Topic, Post)
fields = {
Topic: ('title', ),
Post: ('body', )
}
# and so on
Also, I want to use it in class based views. I mean, I would like to write view as:
class TopicCreate(CreateView):
form_class = TopicForm
# ...
def form_valid(self, form):
# some things before creating objects
As suggested in comments, I could use two forms. But I don't see any simple way to use two forms in my TopicCreate
view - I should reimplement all methods belongs to getting form(at least).
So, my question is:
Is there something already implemented in Django for my requirements? Or is there a better(simpler) way?
or
Do you know a simple way with using two forms in class based view? If so, tell me, it could solve my issue too.