1

I’ve created a form to when the current logged in user makes a submission I have everything I want populated in the admin, except the current logged in user’s username.

The Custom User Model I’m using is located in from users.models import CustomUser if that helps.

How do I get the current logged in user’s username to populate in admin.py in the user column?

Any help i gladly appreciated, Cheers

Screenshot of Admin:

enter image description here

user_profile/models

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractUser, UserManager
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from users.models import CustomUser


class Listing (models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True)
    created =  models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    zip_code = models.CharField(max_length=100)
    mobile_number = models.CharField(max_length=100)


def create_profile(sender, **kwargs):
    if kwargs['created']:
        user_profile = Listing.objects.create(user=kwargs['instance'])

post_save.connect(create_profile, sender=CustomUser)

user_profile/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.conf import settings
from django.views.generic.edit import FormView
from django.views.generic.edit import UpdateView
from django.views.generic import TemplateView
from .forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from .models import Listing
from users.models import CustomUser
from django.urls import reverse_lazy
from django.utils import six
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from avatar.forms import PrimaryAvatarForm, DeleteAvatarForm, UploadAvatarForm
from avatar.models import Avatar
from avatar.signals import avatar_updated, avatar_deleted
from avatar.utils import (get_primary_avatar, get_default_avatar_url,
                          invalidate_cache)


def change_view(request):
    form = HomeForm(request.POST or None)
    user_profile = Listing.objects.all
    user = request.user

    if form.is_valid():
        form.save()
        form = HomeForm()

    context = {
        'form': form, 'user_profile': user_profile 
    }

    return render(request, "myaccount.html", context)

user_profile/admin.py

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin


from user_profile.forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm

from user_profile.models import Listing
from users.models import CustomUser


# Register models here.

class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user']
    list_filter = ['name', 'zip_code', 'created', 'updated', 'user']

admin.site.register(Listing, UserProfileAdmin)

HTML

<form role="form" action="" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.errors }}   
{{ form.name }}
{{ form.address }}
{{ form.zip_code }}
{{ form.mobile_number }}
<button class="btn btn-primary btn-success btn-round btn-extend" type="submit" value="Submit"><i class="zmdi zmdi-favorite-outline6"></i>Submit</button>
</form>   

settings

AUTH_USER_MODEL = 'users.CustomUser'
spidey677
  • 317
  • 1
  • 10
  • 27
  • @dfundako I've tried something like that over here and no luck... Any other ideas by any chance? https://stackoverflow.com/questions/54015285/django-logged-in-user-not-populating-in-admin-py/54017428#comment94872610_54017428 – spidey677 Jan 03 '19 at 21:03
  • 1
    So the username you want is held by the `user` attribute on the `Listing` object? – Will Keeling Jan 03 '19 at 21:18
  • @WillKeeling Yes if that's how i get what I need done. I'm new to Django so I'm not too sure. I just added the HTML above. I need the current logged in user's username to populate in` admin.py` when the user makes a form submission. What's the best way to do that? – spidey677 Jan 03 '19 at 21:40

2 Answers2

0

Changed the following code in view.py to resolve the issue:

user_profile/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.conf import settings
from django.views.generic.edit import FormView
from django.views.generic.edit import UpdateView
from django.views.generic import TemplateView
from .forms import HomeForm
from users.forms import CustomUserCreationForm, CustomUserChangeForm
from .models import Listing
from users.models import CustomUser
from django.urls import reverse_lazy
from django.utils import six
from django.utils.translation import ugettext as _
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from avatar.forms import PrimaryAvatarForm, DeleteAvatarForm, UploadAvatarForm
from avatar.models import Avatar
from avatar.signals import avatar_updated, avatar_deleted
from avatar.utils import (get_primary_avatar, get_default_avatar_url,
                          invalidate_cache)


def change_view(request):
    form = HomeForm(request.POST or None)
    user_profile = Listing.objects.all
    user = request.user

    if form.is_valid():
        listing_instance = form.save()  # "this will return the 'Listing' instance"
        listing_instance.user = user
        listing_instance.save()
        form = HomeForm()

    context = {
        'form': form, 'user_profile': user_profile
    }

    return render(request, "myaccount.html", context)
Community
  • 1
  • 1
spidey677
  • 317
  • 1
  • 10
  • 27
-1

In the list_display for the UserProfileAdmin, you can set the name of a method that will retrieve the username from the referenced user object.

For example, using a method called get_username():

class UserProfileAdmin(admin.ModelAdmin):
    list_display = ['name', 'address', 'zip_code', 'mobile_number',
                    'created', 'updated', 'get_username']  # Use the method name
    list_filter = ['name', 'zip_code', 'created', 'updated', 'user']

    def get_username(self, obj):
        if obj.user is not None:
            return obj.user.username
        return '-'
    get_username.short_description = 'User'

The obj argument is the Listing instance representing the current row in the table.

Will Keeling
  • 22,055
  • 4
  • 51
  • 61
  • Thanks for the suggestion! I just tried it but no luck.. I recevied an error saying: AttributeError: 'NoneType' object has no attribute 'username'. Any idea how to solve this? – spidey677 Jan 04 '19 at 01:55
  • @spidey677 - I missed that the user is nullable. I have modified the answer to take that into account. – Will Keeling Jan 04 '19 at 09:04
  • So I added what you suggested and still no luck. The error message went away and I still can't see the logged in user populate in admin. What can this issue be? – spidey677 Jan 04 '19 at 17:33
  • I also want to add that I've noticed that the username field populates in the admin when users create an account but not when they fill out this model form.. which is what I'd like to do as well. – spidey677 Jan 04 '19 at 17:45