Django模型保存由。创建和修改

时间:2016-07-17 04:16:28

标签: django model save

我正在运行djando 1.8,我正在尝试将当前登录的用户保存在我的数据库中的字段创建和修改中。我已经尝试了许多不同的组合来实现这一点,但我没有遇到任何运气。我必须在用户ID中使用硬编码进行编码,如下所示:

@python_2_unicode_compatible  # only if you need to support Python 2
class Project(models.Model):
    name = models.CharField(max_length=50, verbose_name="Name")
    jobNumber = models.CharField(max_length=8)
    shopOut = models.DateTimeField(null=True)
    shopIn = models.DateTimeField(null=True)
    completion = models.DateTimeField(null=True)
    installation_date = models.DateTimeField(null=True)
    contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, default=101)
    created_by = models.ForeignKey(User, related_name='Project_created_by')
    created_date = models.DateTimeField(auto_now_add=True)
    modified_by = models.ForeignKey(User, related_name='Project_modified_by')
    modified_date = models.DateTimeField(auto_now=True)
    assigned_to = models.ForeignKey(User, related_name='Project_assigned_to', default=1)
    status = models.ForeignKey('Status', related_name='Project_status', default=1)
    def __str__(self):
        return self.name
    def save(self, *args, **kwargs):
        if not self.id:
            self.created_by = User.objects.get(id=1)
            #self.created_by = User.objects.get(id=kwargs['request'].user)
            #self.created_by = User.objects.get(id=request.user)
            self.modified_by = User.objects.get(id=1)
            #self.modified_by = User.objects.get(id=kwargs['request'].user)
            #self.modified_by = User.objects.get(id=request.user)
            super(Project, self).save(*args, **kwargs)
            year = datetime.datetime.now().year
            self.jobNumber = '{}{:04d}'.format(year, self.id)
        self.modified_by = User.objects.get(id=1)
        #self.modified_by = User.objects.get(id=kwargs['request'].user)
        #self.modified_by = User.objects.get(id=request.user)
        super(Project, self).save(*args, **kwargs)

如果我尝试任何注释掉的代码:

self.created_by = User.objects.get(id=kwargs['request'].user)

self.created_by = User.objects.get(id=request.user)

我收到以下错误:

  

/ admin / project / project / add /中的KeyError   '请求'

  

/ admin / project / project / add /中的NameError   全局名称“请求”未定义

我的问题再一次是如何将当前登录用户保存在created_by和modified_by字段中?

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

在搜索了一下后,我发现这个post 我跟着大部分代码,但这是我的:

这是我的app文件夹结构:

MyApp的

  • 项目
    • admin.py#已更改此
    • models.py#已更改此
    • ...
  • MyApp的
    • setting.py
    • url.py
    • ...

我的新admin.py

from django.contrib import admin
from . import models

class ProjectAdmin(admin.ModelAdmin):
    fields = ('name', 'jobNumber', 'contractor', 'assigned_to', 'status')
    def save_model(self, request, obj, form, change):
        instance = form.save(commit=False)
        if not hasattr(instance, 'created_by'):
            instance.created_by = request.user
        instance.modified_by = request.user
        instance.save()
        form.save_m2m()
        return instance

admin.site.register(models.Project,ProjectAdmin)

models.py

import datetime
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.auth.models import User
from contractor.models import Contractor

@python_2_unicode_compatible  # only if you need to support Python 2
class Project(models.Model):
    name = models.CharField(max_length=50, verbose_name="Name")
    jobNumber = models.CharField(max_length=8)
    shopOut = models.DateTimeField(null=True)
    shopIn = models.DateTimeField(null=True)
    completion = models.DateTimeField(null=True)
    installation_date = models.DateTimeField(null=True)
    contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, default=101)
    created_by = models.ForeignKey(User, related_name='Project_created_by')
    created_date = models.DateTimeField(auto_now_add=True)
    modified_by = models.ForeignKey(User, related_name='Project_modified_by')
    modified_date = models.DateTimeField(auto_now=True)
    assigned_to = models.ForeignKey(User, related_name='Project_assigned_to', default=1)
    status = models.ForeignKey('Status', related_name='Project_status', default=1)
    def __str__(self):
        return self.name
    def save(self, *args, **kwargs):
        if not self.id:
            super(Project, self).save(*args, **kwargs)
            year = datetime.datetime.now().year
            self.jobNumber = '{}{:04d}'.format(year, self.id)
        super(Project, self).save(*args, **kwargs)

我想诀窍是在admin.py文件中捕获请求。感谢solarissmoke的输入!

答案 1 :(得分:0)

您可以使用django-currentuser软件包。

例如:

from django_currentuser.middleware import get_current_authenticated_user

class Project(models.Model):
    ....

    self.modifier = get_current_authenticated_user()
    if not self.id:
        self.creator = get_current_authenticated_user()
    
    ....