How to efficiently initial data in Django forms.Form? -


For example, I have a paragraph model for blog articles, so it's easy to add articles to the database.

But when I make them a form class by form.ModelForm , then I need to edit them in the form, I type instace = artcile < / Code> and I can pass it / P>

But if I create a form class by form.Forms , then I have to declare a form form and pass the field one by one.

Something like this

  form = ArticleForm ({'title': article.title, 'body': article.body, 'pub_date': article.pub_date 'status ': Article.status,' writer ': article: author,' comments': article.comments.count (), 'blah': article: blahblahah, 'again blah': article song, ..... })   

It's ugly, is not it? form.ModelForm ?

model_to_dict And you can use django.forms.models from fields_for_model utils:
  # Contemplating the article is an example of your paragraph model : Django.forms import form django.forms.models from fields_for_model, model_to_dict form = form (model_to_dict (article)) form.fields.update (fields_for_model (article))   

If you have M2M is a relation, so you can create a format for it:

  django.fo Import from rms.models as django import Model_to_ dict, fields_for_model to django.forms.formsets Import formset_factory # To handle your respective model, 'tag' is called form.Form: def __init __ (auto, * Args, ** kwargs): super (TagForm, self) .__ init __ (* args, ** kwargs) self .field. Feature (fields_for_model (tag)) tagFormSet = formset_factory (TagForm) formset = TagFormSet (Initial = [article] [Tags] for tags in .tags.all ()] [model_to_dict (tag)]   

Then you can use the form of the form to access the form created for related models Can repeat: > to form Formset.forms

 : print form    

Comments