python - 验证后更改 django 中的表单排除值

标签 python django

我有以下基于模型的表格。

class Article(models.Model):
    title = models.CharField(max_length=100, db_column='title')
    url = models.CharField(max_length=100, db_column='url')
    category = models.ForeignKey(Category, db_column='category')
    description = models.TextField(db_column='description')
    createDate = models.DateTimeField(db_column='createDate')

    def __unicode__(self):
        return self.title

    class Meta:
        db_table = 'articles'
        ordering = ['createDate']

表格

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('title', 'description', 'category')

我想要的是通过小写干净的标题来验证表单并更改 url 的值。 我怎样才能做到这一点? 我发现 url 是排除值,那么验证后如何在表单中更改它?

谢谢。

最佳答案

您可以在保存文章时提供自定义 URL,如下所示:

class Article(models.Model):
    ...

    def save(self, *args, **kwargs):
        if not self.url:
            self.url = self.title.lower()

        super(Article, self).save(*args, **kwargs)

关于python - 验证后更改 django 中的表单排除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424019/

相关文章:

python - pygame 如何从屏幕的每一侧生成敌人?

python - 您可以通过传入自己的函数来更改/重定向 django 表单的函数吗?

python - 在 Django 应用程序中,每个用户只允许一个事件 session

python - Django 模板表达式中的 "bar"是文字吗?

python - 使用pywin32获取过去3个月事件日志中所有错误条目的来源,日期/时间和消息的列表

python - 从 3D 数组的 2D 切片创建网格网格

python - Python 中除空格外的正则表达式匹配

python - lxml etree.iterparse 错误 "TypeError: reading file objects must return plain strings"

javascript - 数据表不显示 Django

python - 有什么方法可以重命名 django.auth 表吗?