0

I’m trying to create a form to when the current logged in user makes a submission the user column in admin.py gets populated with the logged in user.

My problem: The user column gets populated when a new user gets created using the CustomUserCreationForm however when the newly created user makes a form submission with the form listed below, the user column doesn’t get populated.

The Custom User Model that I'm trying to get the username from is located in from users.models import CustomUser so I’m not sure why this isn’t working.

How do I get the current logged in user to populate in admin.py in the users column with the form listed below?

Any help i gladly appreciated, thanks.

enter image description here

Code Below:

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 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.PROTECT, 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)
    cc_number = models.CharField(max_length=100)
    cc_expiration = models.CharField(max_length=100)
    cc_cvv = 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/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)

user_profile/views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.conf import settings
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


# add to your views

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

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

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

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

user_profile/forms.py

import os

from django import forms
from django.forms import ModelForm

from django.forms import widgets
from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import filesizeformat

from avatar.conf import settings
from avatar.models import Avatar
from .models import Listing


class HomeForm(forms.ModelForm):

    user = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
    username = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))
    created = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))    
    name = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Full Name', 'class': 'form-control'}))
    address = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Address', 'class': 'form-control'}))
    zip_code = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Zipcode', 'class': 'form-control'}))
    mobile_number = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Mobile Number', 'class': 'form-control'}))
    cc_number = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Credit Card', 'class': 'form-control'}))
    cc_expiration = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'Expiration Date', 'class': 'form-control'}))
    cc_cvv = forms.CharField(required=False, label='', max_length=100,  widget=forms.TextInput(attrs={'placeholder': 'CVV', 'class': 'form-control'}))

    class Meta:
        model = Listing
        fields = '__all__'

settings.py

AUTH_USER_MODEL = 'users.CustomUser'
spidey677
  • 317
  • 1
  • 10
  • 27

1 Answers1

0

Try this

forms.py

import os

from django import forms
from django.forms import ModelForm

from django.forms import widgets
from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import filesizeformat

from avatar.conf import settings
from avatar.models import Avatar
from .models import Listing


class HomeForm(forms.ModelForm):

    class Meta:
        model = Listing
        fields = ('name', 'address', 'zip_code', 'mobile_number', 'cc_number', 'cc_number', 'cc_expiration', 'cc_cvv')

Add in models file

class ListingManager(models.Manager):
    def save_from_object(self, request, obj):
        obj.user = request.user
        obj.save()

Add Update your Listing Model with objects as new manager

class Listing (models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, 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)
    cc_number = models.CharField(max_length=100)
    cc_expiration = models.CharField(max_length=100)
    cc_cvv = models.CharField(max_length=100) 

    objects = ListingManager()

This should work, Also I am not sure about your idea of keeping user as OneToOneField (This will not allow having multiple records with same user instance), I think you need to change it to ForeignKey. Refer What's the difference between django OneToOneField and ForeignKey?

Nagesh Dhope
  • 797
  • 5
  • 13
  • I tried what you suggested and no luck. I'll play around with adding a foreign key and see what happens. If you have any other ideas troubleshooting please let me know. Thanks! – spidey677 Jan 03 '19 at 06:52
  • i added `user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)`. then after a user submits i received an error in terminal that says `ValueError: Cannot assign "''": "Listing.user" must be a "CustomUser" instance.` Any ideas? – spidey677 Jan 03 '19 at 07:02
  • Update `user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)`. Also Login before submitting the form – Nagesh Dhope Jan 03 '19 at 07:45
  • `ValueError: Cannot assign "''": "Listing.user" must be a "CustomUser" instance.` I still get that same error my friend. – spidey677 Jan 03 '19 at 17:51