JHall651
JHall651

Reputation: 437

How to make current user the foreign key in Django Model

I am using Django admin as a dashboard for clients (restricted permissions). 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. I am using "exclude" in the ProductAdmin so the client won't have the choice of changing it. 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. 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?

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)

Upvotes: 0

Views: 2570

Answers (1)

not2acoder
not2acoder

Reputation: 1152

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.

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 :

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

Upvotes: 1

Related Questions