Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should default model fields be set by the Form or the Model?

Which option is best, 1 or 2?

1.

class TopicForm(forms.Form):

    name = forms.CharField(required=True)
    body = RichTextFormField(required=True)

    def save(self, request):
        t = models.Topic(user=request.user,
                         site=get_current_site(request),
                         name=self.cleaned_data['name'],
                         body=self.cleaned_data['body'])
        t.slug = slugify(self.name)
        t.body_html = seo.nofollow(seo.noindex(self.body))
        t.ip = utils.get_client_ip(request)
        t.save()

or 2.

class Topic(models.Model):
    ...   

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        self.body_html = seo.nofollow(seo.noindex(self.body))
        self.ip = utils.get_client_ip(request)
        super(Topic, self).save(*args, **kwargs)
like image 597
Evg Avatar asked Oct 01 '22 18:10

Evg


1 Answers

The difference is that the first version is only applied when modifying objects through the form, while the second is applied whenever the model is saved (though that is still a subset of all the ways in which database rows can be modified in Django). Even if you currently only create objects through forms, I think it's still a useful distinction to keep in mind.

It looks to me like a mixture of the two makes sense in your case. A slug is something that you will always want to set based on name - that is, it's inherent to the model itself. On the other hand, the idea of a client_ip seems inexorably tied to the notion of creating an object with a form via a web request.

Of course, you are in a better position to know about the specifics of this model, but that is the general way I would approach the question.

like image 102
Kevin Christopher Henry Avatar answered Oct 03 '22 08:10

Kevin Christopher Henry