在fixing one error中,我又开发了另一个。我甚至不确定从哪里开始,我很沮丧。
我的应用程序显示在Django管理部分,当我点击“添加”时,它会显示表单。当我填写它&提交它会导致此错误:
异常值:(1048,“列'user_id'不能为空”)
似乎简单&清除,但如果我将user_id添加到我的admin.py,那么它会导致我刚修复的错误。如果我将其遗漏并使用修复旧错误的代码,那么我会收到此错误。这是相关的代码:
admin.py (我注释掉了我正在使用的代码,因为这导致了之前的错误)
from timeslip.models import Timeslip
from django.contrib import admin
class TimeslipAdmin(admin.ModelAdmin):
pass
#fields = ['user_id','day','hours_as_sec','part_of_day','drove','gas_money','notes']
admin.site.register(Timeslip, TimeslipAdmin)
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Timeslip(models.Model):
user=models.ManyToManyField(User)
day = models.DateField()
hours_as_sec = models.PositiveIntegerField()
part_of_day = models.CharField(max_length=16,choices=PART_O_DAY)
drove = models.BooleanField(default=False)
gas_money = models.DecimalField(max_digits=5,decimal_places=2)
notes = models.TextField()
class UserProfile(models.Model):
user = models.ForeignKey(User)
url = models.URLField("Website", blank=True)
position = models.CharField(max_length=50, blank=True)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
如果我将Timeslip的用户=设置为ForeignKey(User)
而不是ManyToManyField(User)
,则错误变为:
Exception Value: (1062, "Duplicate entry '2' for key 'user_id'")
...我明白了,但这正是我现在要做的 - 为每个用户制作多个时间片。
我该怎么做?无论我尝试什么,我都会继续犯下荒谬的错误,即使它看起来像是一个普通的&基本的事情。
更新:
新问题。 Django缓存了吗?我从模型中删除了一些东西并重置了所有东西,但它仍然显示旧的形式。如果它显示了我缓存的内容 - 如何刷新缓存?
无论如何,这是我运行manage.py sqlall timeslip
BEGIN;
CREATE TABLE `timeslip_timeslip` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`user_id` integer NOT NULL,
`day` date NOT NULL,
`hours_as_sec` integer UNSIGNED NOT NULL,
`part_of_day` varchar(16) NOT NULL,
`drove` bool NOT NULL,
`gas_money` numeric(5, 2) NOT NULL,
`notes` longtext NOT NULL
)
;
ALTER TABLE `timeslip_timeslip` ADD CONSTRAINT `user_id_refs_id_bb29929c` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
CREATE TABLE `timeslip_userprofile_user` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`userprofile_id` integer NOT NULL,
`user_id` integer NOT NULL,
UNIQUE (`userprofile_id`, `user_id`)
)
;
ALTER TABLE `timeslip_userprofile_user` ADD CONSTRAINT `user_id_refs_id_c73880a3` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);
CREATE TABLE `timeslip_userprofile` (
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
`url` varchar(200) NOT NULL,
`company` varchar(50) NOT NULL
)
;
ALTER TABLE `timeslip_userprofile_user` ADD CONSTRAINT `userprofile_id_refs_id_d05b8c80` FOREIGN KEY (`userprofile_id`) REFERENCES `timeslip_userprofile` (`id`);
CREATE INDEX `timeslip_timeslip_fbfc09f1` ON `timeslip_timeslip` (`user_id`);
COMMIT;