【问题标题】:django how to create field dependent fielddjango如何创建字段相关字段
【发布时间】:2017-04-23 08:36:25
【问题描述】:

我有一个帖子模型,其中有帖子类型字段。 我希望当用户选择帖子类型 = 分配时,它会要求提交截止日期,否则它不会询问任何内容。 以及如何在模板中显示它。

models.py

class Post(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True, blank = True)
    content = models.TextField()
    choice = (
        ('post','post'),
        ('anouncement','anouncement'),
        ('question', 'question'),
        ('assignment', 'assignment')
        )
    post_type = models.CharField(choices = choice, default = 'post', max_length = 12)
    classroom = models.ForeignKey(Classroom)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)



    def __unicode__(self):
        return self.title

    def __str__(self):
        return self.title

    @property
    def comments(self):
        instance = self
        qs = Comment.objects.filter_by_instance(instance)
        return qs

    @property
    def get_content_type(self):
        instance = self
        content_type = ContentType.objects.get_for_model(instance.__class__)
        return content_type

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})

【问题讨论】:

    标签: django django-models django-forms django-views


    【解决方案1】:

    在模型中,您需要为相互依赖的字段添加一个干净的方法。 https://docs.djangoproject.com/en/1.11/ref/models/instances/#django.db.models.Model.clean

    在模型 Admin 中,您需要添加一些 JavaScript 来显示和隐藏该字段。 https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#modeladmin-asset-definitions

    【讨论】:

    • 更新的 django 存在安全问题
    猜你喜欢
    • 2021-08-15
    • 2013-05-11
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多