简体   繁体   English

Django-登录的用户未填充在admin.py中

[英]Django - Logged in User Not Populating in admin.py

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. 我正在尝试创建一个表单,以供当前登录的用户进行提交时, admin.pyuser列填充有已登录的用户。

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. 我的问题:使用CustomUserCreationForm创建新用户时,将填充user列,但是当新创建的用户使用下面列出的表单提交表单时,不会填充user列。

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. 我试图从中获取用户名的自定义用户模型位于from users.models import CustomUser所以我不确定为什么这不起作用。

How do I get the current logged in user to populate in admin.py in the users column with the form listed below? 如何使用下面列出的形式获取当前登录用户以在“ users列中的admin.py中进行填充?

Any help i gladly appreciated, thanks. 我很感激任何帮助,谢谢。

在此处输入图片说明

Code Below: 下面的代码:

user_profile/models user_profile /模型

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 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 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 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 settings.py

AUTH_USER_MODEL = 'users.CustomUser'

Try this 尝试这个

forms.py 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 添加使用objects作为新管理员更新您的清单模型

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. 这应该可以工作,而且我不确定您将用户保留为OneToOneField的想法(这将不允许具有相同用户实例的多个记录),我认为您需要将其更改为ForeignKey。 Refer What's the difference between django OneToOneField and ForeignKey? 请参阅django OneToOneField和ForeignKey有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM