热门标签:
Q:

Allauth get_user_model()CustomUser问题

我目前正在尝试在基于函数的视图中获取用户模型,但不断收到以下错误。 我已经安装了allauth并使用allauth创建了一个客户用户。帐户模型。 我附上了我的模型和迁移。 我已经查看了我的数据库,并有用户,但是每次我在视图中调用用户时,它都会给我一个客户用户错误。 我已经尝试了在函数视图中注释掉的其他2种方法。

错误

{

Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/store/add_listing/

Django Version: 3.1.14
Python Version: 3.9.10
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.sites',
 'crispy_forms',
 'allauth',
 'allauth.account',
 'accounts',
 'web_pages',
 'store']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/get_printed/store/views.py", line 93, in AddListing
    current_user =  request.CustomUser #.objects.filter(current_user) #get_user_model()

Exception Type: AttributeError at /store/add_listing/
Exception Value: 'WSGIRequest' object has no attribute 'CustomUser'

Views.py

    def AddListing(request):
        if request.method == 'POST':
            form = List_Item_Form(request.POST)
            if form.is_valid():
                itemName = form.cleaned_data['item_name']
                price = form.cleaned_data['price']
                desc = form.cleaned_data['description']
                quan = form.cleaned_data['quantity']
                main_img = form.cleaned_data['main_image']
                current_user =  request.CustomUser #.objects.filter(current_user) #get_user_model()
    
                model_instance = Item(creator=current_user, item_name=itemName, price=price,description=desc, quantity=quan, main_image=main_img)
                model_instance.save()
                return HttpResponseRedirect('user_profile/items/')
        else:
            form = List_Item_Form()
        return render(request, 'store/add_listing.html', {'form': form})
    
    
    def success(request):
        return render(request, 'profile/item_profile.html')

models.py

class CustomUser(AbstractUser): 
pass

迁移

class Migration(migrations.Migration):

initial = True

dependencies = [
    ('auth', '0012_alter_user_first_name_max_length'),
]

operations = [
    migrations.CreateModel(
        name='CustomUser',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('password', models.CharField(max_length=128, verbose_name='password')),
            ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
            ('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
            ('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
            ('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
            ('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
            ('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
            ('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
            ('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
            ('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
            ('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
            ('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
        ],
        options={
            'verbose_name': 'user',
            'verbose_name_plural': 'users',
            'abstract': False,
        },
        managers=[
            ('objects', django.contrib.auth.models.UserManager()),
        ],
    ),
]

Forms.py

class List_Item_Form(ModelForm):
class Meta:
    model = Item
    exclude = ('creator','image_3','image_4','image_5','created_on','updated_on')

store/models.py

class Item(models.Model):
id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False )
creator = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item_name = models.CharField(max_length=40)
price = models.DecimalField(max_digits = 6, decimal_places=2)
description = models.CharField(max_length= 500)
main_image = models.ImageField(upload_to=path_and_rename , max_length=255, null=True, blank=True)
image_2 = models.ImageField(upload_to='items/', blank=True)
image_3= models.ImageField(upload_to='items/', blank=True)
image_4= models.ImageField(upload_to='items/', blank=True)
image_5= models.ImageField(upload_to='items/', blank=True)
quantity = models.IntegerField(default=1, validators=[ MaxValueValidator(100),MinValueValidator(1)])
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.item_name

def get_absolute_url(self):
    return reverse("item_detail_view", args=[str(self.id)])
原网址

相似问题