1

I am learning the basics of Django web but and I'm stuck in a problem

I have the following models(simplified) at models.py :

class CustomUser(AbstractUser): # Custom Admin Model
        def __str__(self):
            return self.username

        def __len__(self):
            return 1

class Task(models.Model):
            title = models.CharField(max_length=250, blank=False)
            author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default=None)

and also this at admin.py :

class TaskInline(admin.TabularInline):
    model = Task

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username']
    inlines = [TaskInline]

    fieldsets = (
        (('User'), {'fields': ('username', 'email')}),
    )

I am currently working on a TODO web app and what I would like to do is to show the Title of Task model in an HTML.

Looking for something like this:

{{ user.inlines[0].title }} # This does not work 

Is it even possible? May I have to create a function for CustomModel that returns his inline models (ex: get_inline_models(self))? Other solutions?

Thanks in advance :)

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60

1 Answers1

0

If what you want is to have access to task's titles through a user instance according to the models you can:

{{ user.task_set }}

in order to get all task related to some user. You can also define a related_name option for your author field:

class Task(models.Model):
   title = models.CharField(max_length=250, blank=False)
   author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, default=None, related_name='tasks')

That way you could:

{{ user.tasks }}

read about this here.

Example

{% for task in user.tasks %}
    {{ task.title }}
{% endfor %}
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60