Django,在模型中使用当前用户ID

时间:2016-01-11 16:13:24

标签: python django django-models django-admin backend

我对Python或Django并不熟悉,但我开始使用Django作为后端构建Web应用程序。

我有一些带有字段filler的模型。该字段由用户填写,其值为id的{​​{1}}。

现在,我想自动将其值设置为当前登录的用户。

根据我的阅读,可以使用user方法完成,但我无法使其正常工作。 (编辑:我没有尝试通过管理界面设置值,因此可能不是我正在寻找的内容)

这是我得到的:

在models.py中:

save_model

在serializers.py

class Project(models.Model):
    CRITICITIES = (
        ('MAND', 'Mandatory to do the task'),
        ('HCHR', 'Not Mandatory but High Impact / High Risk Impact'),
        ('HCLR', 'Not Mandatory but High Impact / Low Risk Impact'),
        ('LCHR', 'Not Mandatory but Low Impact / High Risk Impact'),
        ('LCLR', 'Not Mandatory but Low Impact / Low Risk Impact'),
    )

    DOWNTIME = (
        ('3+', '> 3 Days'),
        ('1-3', '1 to 3 Days'),
        ('0.5-1', '1/2 to 1 Day'),
        ('0.5-', '<1/2 Day')
    )

    filler = models.ForeignKey(User, related_name='+')
    title = models.CharField(max_length=100, unique=True)
    description = models.TextField()
    user_departments = models.ManyToManyField('Department', related_name='+')
    products = models.ManyToManyField('Product', blank=False)
    processes = models.ManyToManyField('Process')
    functions = models.ManyToManyField('Function')
    frameworks = models.ManyToManyField('Framework')
    valuechains = models.ManyToManyField('ValueChain')
    regions = models.ManyToManyField('Region')
    project_path = models.CharField(max_length=255, blank=False)
    password = models.CharField(max_length=50, blank=True)
    downtime_acceptance = models.CharField(max_length=5, choices=DOWNTIME, blank=True)
    categories = models.ManyToManyField('Category', blank=False)
    criticity_detail = models.CharField(max_length=4, choices=CRITICITIES, blank=True)
    comment = models.TextField(blank=True)  #TODO: remove
    inputs = models.ManyToManyField('InputOutput', related_name='+', blank=True)
    outputs = models.ManyToManyField('InputOutput', related_name='+', blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        permissions = (
            ('can_view_logs', 'Can view project logs'),
        )

    def __unicode__(self):
        return self.title

在urls.py中:

class ProjectSerializer(serializers.ModelSerializer):
    requests = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Project
        fields = ('id', 'filler', 'title', 'description', 'requests', 'products', 'processes', 'functions', 'frameworks',
                  'categories', 'password', 'project_path', 'regions', 'criticity_detail', 'comment', 'inputs',
                  'outputs', 'valuechains', 'user_departments')

在views.py中:

router = DefaultRouter(trailing_slash=False)
router.register(r'users', UserViewSet)
# Other irrelevant routes
# ...
router.register(r'projects', ProjectViewSet)
projects_router = NestedSimpleRouter(router, r'projects', lookup='project', trailing_slash=False)
projects_router.register(r'requests', ProjectRequestViewSet, base_name='project-requests')
router.register(r'requestcomments', RequestCommentViewSet)
router.register(r'requests', RequestViewSet)
requests_router = NestedSimpleRouter(router, r'requests', lookup='request', trailing_slash=False)
requests_router.register(r'statuses', RequestStatusViewSet, base_name='request-statuses')
requests_router.register(r'comments', RequestCommentViewSet, base_name='request-comments')
requests_router.register(r'estimatedcosts', RequestEstimatedCostViewSet, base_name='request-estimatedcosts')


urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^', include(projects_router.urls)),
    url(r'^', include(requests_router.urls)),
    url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^token-auth', views.obtain_auth_token),
]

例如,这里我们有字段class ProjectViewSet(ModelViewSet): """ API endpoint that allows projects to be viewed or edited. """ queryset = Project.objects.all() serializer_class = ProjectSerializer created_at,每次发布项目时都会自动发布适当的值(当前日期)。 我试图实现的是对具有当前用户ID的字段updated_at执行相同的操作。

1 个答案:

答案 0 :(得分:0)

根据文档,您在管理员中做了正确的事情。请参阅here,完全是您的用例。但是,如果要从其他位置保存模型,则可能需要覆盖模型中的save方法。