简体   繁体   English

如何使当前用户成为Django模型中的外键

[英]How to make current user the foreign key in Django Model

I am using Django admin as a dashboard for clients (restricted permissions). 我将Django admin用作客户端的仪表板(受限权限)。 I am allowing them to add new products via the admin site, and wish to use the current user as a foreign key in the Products model. 我允许他们通过管理站点添加新产品,并希望将当前用户用作Products模型中的外键。 I am using "exclude" in the ProductAdmin so the client won't have the choice of changing it. 我在ProductAdmin中使用“排除”,因此客户端将无法选择更改它。 When the "exclude" is not used the user is the default selection and it works. 当不使用“排除”时,用户是默认选择,并且可以使用。 When I include "exclude" the form returns an error saying the field is null. 当我包含“ exclude”时,表单返回错误,指出该字段为null。 How can I make the current user the foreign key in the Products model whether they add items via the admin form or upload via csv? 我如何使当前用户成为产品模型中的外键,无论他们是通过管理表单添加项目还是通过csv上传项目?

Here is my Product model: 这是我的产品型号:

#models.py
from django.db import models
from datetime import datetime
from django.contrib.auth.models import User

class Product(models.Model):
    client_id = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    title = models.CharField(max_length=200)
    asin = models.CharField(max_length=200, blank=True)
    sku = models.CharField(max_length=200, blank=True)
    date_added = models.DateTimeField(default=datetime.now, blank=True)
    in_report = models.BooleanField(default=True)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        return qs.filter(client_id=request.user)

    def __str__(self):
        return self.title

#admin.py
from django.contrib import admin
from .models import Product

class ProductAdmin(admin.ModelAdmin):
    list_display = ('title', 'asin', 'sku', 'in_report')
    list_display_links = ('title', 'asin', 'sku')
    list_editable = ('in_report',)
    search_fields = ('title', 'asin', 'sku', 'in_report')
    list_per_page = 50
    exclude = ('client_id',)

admin.site.register(Product, ProductAdmin)

I believe that you want to hide client_id from the users but while saving/changing the object via admin you would like the current user to get saved. 我相信您想向用户隐藏client_id,但是在通过admin保存/更改对象时,您希望当前用户得到保存。

Now when you exclude the client_id from the admin, the field will not be present in the form, which will then throw the error, since the client_id is a required field.Hence you can override the save_model method of the admin as : 现在,当您从admin中exclude client_id时,该字段将不会出现在表单中,这将引发错误,因为client_id是必填字段。因此,您可以使用save_model方法覆盖admin的save_model方法:

def save_model(self, request, obj, form, change):
    # associating the current logged in user to the client_id
    obj.client_id = request.user
    super().save_model(request, obj, form, change)

So whenever an object is changed/added current user will be assigned to client_id.Hope it helps 因此,无论何时更改/添加对象,当前用户都将被分配给client_id。希望它会有所帮助

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

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