Form to create several objects with one-to-one relation

70 views
Skip to first unread message

Ilya Kazakevich

unread,
Apr 21, 2015, 6:41:48 PM4/21/15
to django...@googlegroups.com
Hello,

I have several models with one-to-one relation. For example

class Task(models.Model):
    initial_comment = models.OneToOneField('Comment')
   # A pack of other fields

class Comment(models.Model)
    body = RichTextField()
   # A pack of other fields


I want to create "create view" based on form, that gives user ability to create task and initial comment there.

1) I can't use CreateView because it is based on only one model
2) I can't use ModelForm because it is based on only one model
3) I can create several forms, but I can't join them into one formset (forms are different)
4) I feel "inlineformset_factory" (InlineFormSet) should be used here, but I am not sure it suits best. Is there any 3rd party Django app to do that?

Sure I can create form myself, but I do not want to copy/paste all fields, their types, localized labels, validations and so on. I just want to list their names (like "fields" attibute).
If you wonder why do I need one-to-one: Comments are used heavily in other places and have different relations with different models.

Thank you.

Ilya.

Vijay Khemlani

unread,
Apr 21, 2015, 7:40:56 PM4/21/15
to django...@googlegroups.com
What about and old-school DetailView?

def get_context_data -> Creates the two forms and puts them in the context

def post -> Validates and process the forms



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e5254d86-c237-4192-bf1e-4e2d96722a9f%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ilya Kazakevich

unread,
Apr 22, 2015, 8:38:30 AM4/22/15
to django...@googlegroups.com
Thank you, that may work, but I feel that I reinventing wheel here.

Actually, there are inline_formset  and CreateWithInlinesView  (from django extras) and they do exactly what I want, but they only support ForeignKey, not OneToOne. Looks like I need to extend them to support OneToOne.

Ilya Kazakevich

unread,
Apr 23, 2015, 9:12:19 AM4/23/15
to django...@googlegroups.com
Well, I found solution.

``CreateWithInlinesView `` works perfectly with ``OneToOneField`` (after all, 1-to-1 is just a foreign key with constraint), but my main model here is ``Comment``, not ``Task``. So I should set ``Comment`` as ``model`` field in this view and ``Task`` as ``inline``. It looks silly. I will create custom form or review my model structure.
Reply all
Reply to author
Forward
0 new messages