不推荐使用forms_for_model()和forms_for_instance(),如何使用ModelForm子类呢?

时间:2011-09-07 06:51:56

标签: python django django-forms

models.py

class Person(models.Model):

    userID = models.ForeignKey(User, unique=True)
    name = models.CharField('name', max_length=200)
    birthday = models.DateField('Birthday',blank=True,null=True)
    gender = models.CharField(max_length=1, choices=gender_list)
    email = models.EmailField('Email', max_length=100,unique=True)
    favoriteURL = models.URLField('myURL')  
    desc = models.TextField('Desc', max_length=500,null=True)
    friends = models.ManyToManyField('self', blank=True)
    blogs = models.ManyToManyField(Blog, blank=True)
    def __str__(self):
        return '%s' % (self.name)

views.py

def person_form(request, pID='0'):

    #default
    **PersonForm = forms.form_for_model(Person)** my query
    f = PersonForm()
    message = 'Unknown Request'
    p = get_object_or_404(Person, pk=pID)
    if request.method == 'GET':
        **PersonForm = forms.form_for_instance(p)** my query
        message = 'Editing person %s ' % p.name
    if request.method == 'POST':
        if request.POST['submit'] == 'update':
            message = 'Update Request for %s. ' % p.name
            **PersonForm = forms.form_for_instance(p)** my query
            if f.is_valid():
                message += 'Valid.'
            else:
                message += 'Invalid.'
    return render_to_response('People/person_form.html', locals())

我尝试过:PersonForm = ModelForm(model=Person)但它会抛出__init__() got unexpected kewyword argument 'model'。我是Python的新手,我在24小时的教科书中使用Django,似乎大多数方法都被弃用了。任何想法我怎么能用ModelForm()替换forms_for_model()?

2 个答案:

答案 0 :(得分:0)

Django在24小时内现在已经过时了。

考虑切换到djangobook v2.0 - 它是最新的,真的很棒。以及modelforms

上的官方文档

Here是旧格式和新格式的小比较。

答案 1 :(得分:0)

The docs完全解释了这一点。