我想添加'created_by'和'modified_by'字段到我的Django模型中,我该怎么做?

dldeef67  于 2022-12-14  发布在  Go
关注(0)|答案(1)|浏览(88)

我在account.models.py中的自定义用户模型:

class MyRegistration(AbstractBaseUser, PermissionsMixin):
    location_list=[
        ('abc', 'abc'),
        ('def', 'def'),
        ]
    username=models.CharField(max_length=10, unique=True)
    email=models.EmailField(unique=True)
    first_name=models.CharField(max_length=150)
    last_name=models.CharField(max_length=150)
    location=models.CharField(max_length=10, choices=location_list, default=None)
    designation=models.CharField(max_length=70)
    is_active=models.BooleanField()
    is_staff=models.BooleanField(default=False)
    start_date=models.DateTimeField(default=timezone.now)
    last_login=models.DateTimeField(null=True)

    USERNAME_FIELD='username'
    REQUIRED_FIELDS=['email', 'first_name', 'last_name', 'location', 'designation']
    objects=FirstManager()
    def __str__(self):
        return self.username

sample.models.py中的模型:

class LockData(models.Model):
    patient=models.ForeignKey(Patient, on_delete=CASCADE, default=None)
    patient_type=models.ForeignKey(PatientType, on_delete=CASCADE, default=None, blank=True, null=True)
    lock=models.BooleanField(default=False)
    date=models.DateField(default=datetime.date.today)
    created_on=models.DateTimeField(auto_now_add=True)
    modified_on=models.DateTimeField(auto_now=True)

因此,除了created_onmodified_on字段外,我还需要'created_by'和'modified_by'字段。

zi8p0yeb

zi8p0yeb1#

我们将从功能视图开始,假设您有一个表单,该表单已经提交到视图以创建一个新模型:

def create_lock_data(request):
    if request.method == "POST":
        form = lock_data_create_form(request.POST)
        if form.is_valid():
            form.instance.created_by = request.user
            form.instance.modified_by = request.user
            form.save()
    else:
        form=lock_data_create_form()
     #...render template etc

同样,在编辑视图中

def edit_lock_data(request, lock_id):
    lock = get_object_or_404(LockData, pk = lock_id)
    if request.method == "POST":
        form = data_lock_edit_form(request.POST, instance=lock)
        if form.is_valid():
            form.instance.modified_by = request.user
            form.save()
    else:
        form=lock_data_edit_form()
    #...render template etc

如果您使用的是基于类的视图,则只需将form.is_valid()条件的内容放入form_valid()函数中,同时记住在引用请求时使用self,例如

def form_valid(self, form):
    form.instance.created_by = self.request.user #only use for create
    form.instance.modified_by = self.request.user
    return super().form_valid(form)

相关问题