【问题标题】:How can I use the current Site as the default in a Django form using the Sites Framework?如何使用站点框架在 Django 表单中使用当前站点作为默认站点?
【发布时间】:2017-09-19 20:12:44
【问题描述】:

我正在使用站点框架并希望将当前站点保存为我的一个模型的默认 site 值。

型号:

class MyModel(models.Model):
    site = models.ForeignKey(
        Site, 
        on_delete=models.CASCADE, 
        default=Site.objects.get_current())  # THIS IS WHAT I WANT TO DO (DOESN'T WORK)
    ...other fields...

有没有办法在我保存MyModel 实例时自动将当前Site 对象保存为MyModel 的site 属性?或者我是否需要通过覆盖表单或模型的 save 方法(或类似的覆盖)手动执行此操作?

【问题讨论】:

  • 你的意思是行不通?

标签: django django-sites


【解决方案1】:

您可以设置默认站点。

models.py

def get_current_site():
    return Site.objects.get_current().id


class MyModel(models.Model):
    site = models.ForeignKey(
        Site,
        on_delete=models.CASCADE,
        default=get_current_site)

仅当您在数据库中创建了站点并在 settings.py 中设置了 SITE_ID 时,这才有效

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 2011-04-14
    • 2012-09-15
    • 1970-01-01
    • 2012-05-06
    相关资源
    最近更新 更多