开发者

How to efficiently initial data in Django forms.Form?

开发者 https://www.devze.com 2023-02-19 23:08 出处:网络
For example I have a Article model for blog articles so it\'s easy to add articles to the database. But when I need to edit them, in form if I create a form class by form.ModelForm, I can pass instac

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

But when I need to edit them, in form if I create a form class by form.ModelForm, I can pass instace=artcile to the form and that开发者_高级运维's it.

But if I create a form class by form.Forms I have to declare a form instance and pass fields to the form one by one.

Something like this

form = ArticleForm({
    'title': article.title,
    'body': article.body,
    'pub_date': article.pub_date
    'status': article.status,
    'author': article.author,
    'comments': article.comments.count(),
    'blah': article.blahblah,
    'againBlah': article.againBlah,
    .....
})

It's ugly, isn't? Is there any way to do this shorter, without using form.ModelForm?


You can use the model_to_dict and fields_for_model utils from django.forms.models:

# assuming article is an instance of your Article model:
from django.forms import Form
from django.forms.models import fields_for_model, model_to_dict

form = Form(model_to_dict(article))
form.fields.update(fields_for_model(article))

If you have an m2m relation, you can create a formset for it:

from django import forms
from django.forms.models import model_to_dict, fields_for_model
from django.forms.formsets import formset_factory

# assuming your related model is called 'Tag'
class TagForm(forms.Form):

    def __init__(self, *args, **kwargs):
        super(TagForm, self).__init__(*args, **kwargs)
        self.fields.update(fields_for_model(Tag))


TagFormSet = formset_factory(TagForm)
formset = TagFormSet(initial=[model_to_dict(tag) for tag in article.tags.all()])

Then you can iterate through the formset to access the forms created for the related models:

for form in formset.forms:
    print form
0

精彩评论

暂无评论...
验证码 换一张
取 消