Subhayan Bhattacharya
Subhayan Bhattacharya

Reputation: 5723

How to access the user details when i use the original user model as a foreign key in Django

I have a book model as below :

from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify
from django.conf import settings


class Book(models.Model):
    added_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_add', on_delete=models.CASCADE),
    last_edited_by = models.ForeignKey(
        settings.AUTH_USER_MODEL, null=True, blank=True, related_name='book_edit', on_delete=models.CASCADE)
    title = models.CharField(max_length=120)
    description = models.TextField(null=True, blank=True)
    slug = models.SlugField()
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    @property
    def user_id(self):
        return self.added_by.id

    def __str__(self):
        return self.title


def pre_save_book(sender, instance, *args, **kwargs):
    slug = slugify(instance.title)
    instance.slug = slug


pre_save.connect(pre_save_book, sender=Book)

Now in my admin.py file i am trying to do this :

from django.contrib import admin
from .models import Book
from .forms import BookForm


class BookAdmin(admin.ModelAdmin):
    fields = [
        'title',
        'slug',
        'added_by'
    ]

    read_only_fields = [
        'updated'
        'timestamp',
        'added_by',
        'last_edited_by'
    ]


admin.site.register(Book, BookAdmin)

I am getting an error which says the added_by field is not recognized , but it should be right, since i have defined it as a foreign key on the original user model.

So i tried to go to the console and try it out :

(Django-concepts) ~/Desktop/Studies/Codes/Django-concepts/django_cls_views:$ python manage.py shell
Python 3.7.3 (default, Mar 27 2019, 09:23:15) 
[Clang 10.0.1 (clang-1001.0.46.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from demo.models import Book
>>> for obj in Book.objects.all():
...     print(obj.added_by[0].username)
... 
Traceback (most recent call last):
  File "<console>", line 2, in <module>
AttributeError: 'ForeignKey' object has no attribute 'username'
>>> 

I have absolutely no clue what am i doing wrong. Can someone please advise on this .How do i access the user details so that i can print them in the view.

Upvotes: 0

Views: 213

Answers (2)

Daniel Roseman
Daniel Roseman

Reputation: 600059

You have a typo in your model definition; an extra , after the added_by field. That has turned the definition into a tuple; your migrations will not have actually added a column there. Remove the comma and run makemigrations and migrate again.

Upvotes: 6

phang
phang

Reputation: 536

print(obj.added_by.username)

This should work.

Upvotes: 1

Related Questions