Adding and Modifying New Objects

Using the generic views to add objects is similarly simple. You need to provide basic information to the view and define URL patterns for those actions. The generic views require the following information:

• The Model Class name, so the view knows what sort of objects it's dealing with.

• The Model Form Class, so the form generation framework knows how to generate form representation.

• The post-action redirect URL, which tells the views where to redirect the user after the data has been submitted. This should be a string representing a URL. If it is not specified, Django will attempt to apply get_absolute_url to the object, so make sure the get_absolute_url method of the object is defined. The advantage of using get_absolute_url , however, is that you don't need to change URL in two places if you modify it.

In Listing 4-15 we define two classes; one is the Model class and the other is the ModelForm class. Strictly speaking, the ModelForm class is not required here as we have a really simple model with only two fields, but I prefer to define them explicitly; this makes it easier should I wish to extend and modify the models later. Note that get_absolute_url returns the reverse-resolved URL.

Listing 4-15. The ClassRule model and form classes class ClassRule(models.Model): rule = models.TextField()

description = models.CharField(max_length=400)

return self.description[:20]

@models.permalink def get_absolute_url(self):

return ('classrule-display', (), {'object_id': self.id})

class ClassRuleForm(ModelForm): class Meta:

model = ClassRule

Back in the URLConfig file, we define a configuration dictionary with a model name and a form filename:

s classrule_form = {

'form_class': ClassRuleForm, 'template_name': 'add.html',

We can even reuse the same form we've been using to add or modify other objects. Because we kept the form generic and let the template handler generate all the required fieldsets, it does not require any changes.

Finally, let's add two URL patterns for the Add and Modify functions and make sure the same URL pattern names are used as referenced from the templates:

url(r'Aclassrule/(?P<object_id>\d+)/modify/$', create_update.update_object, classrule_form, name='classrule-modify'), url(r'Aclassrule/add/$', create_update.create_object, classrule_form, name='classrule-add'),

As you can see, the syntax is same as with generic display views—the first argument is a view function and the second argument is the dictionary that contains the view configuration items, such as the form class name and the template file name.

Was this article helpful?

0 0

Post a comment