On 11/9/07, Marty Alchin <[EMAIL PROTECTED]> wrote: > > On Nov 9, 2007 9:57 AM, Marty Alchin <[EMAIL PROTECTED]> wrote: > > The only thing it doesn't handle yet is how to remove > > fields from the customized form, but this might be as simple as > > assigning the field to None or some new ExcludedField class or > > something. > > I actually like the idea of an ExcludedField. ExcludedFields wouldn't > be output in HTML, and wouldn't be expected in the incoming data, but > would be set in the constructor instead, using keyword arguments. Take > the following example. > > class Article(models.Model): > author = models.ForeignKey(User) > title = models.CharField(max_length=255) > body = models.TextField() > > class ArticleForm(forms.ModelForm(Article)): > author = forms.ExcludedField() > body = myapp.ReStructuredTextField() > > def new_article(request): > if request.method == 'POST': > form = ArticleForm(request.POST, author=request.user) > if form.is_valid(): > obj = form.save() > ... > else: > form = ArticleForm(author=request.user) > > Using this, is_valid would return False if author wasn't set in the > constructor, unless ExcludedField was declared using required=False. I > don't think it'd be necessary to deal with validating the data on an > ExcludedField though, since it would only get set in Python code. > Setting it to the wrong type would be a code error, not an input > error.
Why not just do this? No need for any special new fields at all. class Article(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=255) body = models.TextField() class ArticleForm(ModelForm): model = Article exclude = ['author'] def new_article(request): article = Article(author=request.user) if request.method == 'POST': form = ArticleForm(request.POST, obj=article) if form.is_valid(): obj = form.save() ... else: form = ArticleForm(obj=article) It's the business of the form to know what the user is supposed to provide. In this case, author needs to be provided by the programmer, and if the programmer screwed up and saving the Article raises an error due to a missing author field, there's nothing the user can do. Adding extra machinery to handle stuff like that in the form seems overly complicated to me. Joseph --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to django-developers@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/django-developers?hl=en -~----------~----~----~----~------~----~------~--~---