简体   繁体   English

Django Admin - 无法更改外键字段

[英]Django Admin - Unable to change Foreign Key field

I have Django version 1.4.5 我有Django版本1.4.5

Here are the relevant parts of my model 以下是我模型的相关部分

class Product (models.Model):
    name=models.CharField(max_length=200)
    description=models.TextField()
    label=models.ForeignKey('Label')
    pub_date = models.DateTimeField(editable=False)

    def save(self):
        #item will not have id if this is the first save
        if not self.id:
            self.pub_date = datetime.date.today()
            super(Product, self).save()

    def __unicode__(self):
    return self.name

class Label(models.Model):
    """
    A clothing label, e.g. Kate Spade
    """
    name=models.CharField(max_length=100)

    def __unicode__(self):
        return self.name

When I attempt to publish a Product, selecting a Label works fine. 当我尝试发布产品时,选择标签可以正常工作。 Publishing the item works as expected, and the label field remains populated upon returning to the Product in the admin console. 发布项目按预期工作,并且在管理控制台中返回到产品后,标签字段仍会填充。 However, if I attempt to change the value of the label field, I am taken to the default list of Products page, with the message "he product "Prod 1" was changed successfully" but returning to the Prod 1 page reveals that the field wasn't actually saved properly. 但是,如果我尝试更改标签字段的值,我将进入产品页面的默认列表,消息“他的产品”Prod 1“已成功更改”但返回到Prod 1页面显示该字段实际上没有正确保存。

Any ideas here? 这里有什么想法?

super(Product, self).save() is within the if block, so it isn't being called on edits. super(Product, self).save()if块中,因此在编辑时不会调用它。 Also, why not just use auto_now_add on the pub_date field? 另外,为什么不在pub_date字段上使用auto_now_add呢?

In your case, no need to set the date & time explicitly. 在您的情况下,无需明确设置日期和时间。 You can use ' auto_now_add ' Please fer this link for more details. 您可以使用' auto_now_add '来获取此链接以获取更多详细信息。

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now_add https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.DateField.auto_now_add

class Product (models.Model):
    name=models.CharField(max_length=200)
    description=models.TextField()
    label=models.ForeignKey('Label')
    pub_date = models.DateTimeField(editable=False, auto_now_add = True)

    def __unicode__(self):
    return self.name

If you need to set it manually, Use the following snippet. 如果需要手动设置,请使用以下代码段。 It calls super class for change also. 它也称超级变革。

def save(self):
    #item will not have id if this is the first save
    if not self.id:
        self.pub_date = datetime.date.today()
    super(Product, self).save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM