TypeError at /register/ 'AnonymousUser' 对象不可迭代

我目前正在开发一个博客Web应用程序,我试图用一对一字段扩展我的Django用户框架,一切都很好,但是当我尝试注册新用户时,它会抛出TypeError。还值得注意的是,正在创建和存储用户(我从管理页面进行了检查)。


它是说,我 views.py 的这一发言正在制造问题。profile.user = Profile.objects.get(user=request.user)


我的 models.py:


from django.db import models

from django.contrib.auth.models import User



class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)

    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    CHOICES = (

        ('AB+', 'AB+'),

        ('AB-', 'AB-'),

        ('A+', 'A+'),

        ('A-', 'A-'),

        ('B+', 'B+'),

        ('B-', 'B-'),

        ('O+', 'O+'),

        ('O-', 'O-'),

        )

    bloodgroup = models.CharField(max_length=100, choices= CHOICES)

    bio = models.TextField(max_length=300)


    def __str__(self):

        return f'{self.user.username} Profile'

我的 views.py


from django.shortcuts import render, redirect

from .models import Profile

from django.contrib import messages

from django.contrib.auth.decorators import login_required

from .forms import UserRegisterForm, ProfileForm



def register(request):

    if request.method == 'POST':

        form = UserRegisterForm(request.POST)

        profile_form = ProfileForm(request.POST)

        if form.is_valid() and profile_form.is_valid():

            form.save()

            profile = profile_form.save(commit=False)

            profile.user = Profile.objects.get(user=request.user)  

            profile.save()


            username = form.cleaned_data.get('username')

            messages.success(request, f'Your account has been created! You are now able to log in')

            return redirect('login')

    else:

        form = UserRegisterForm()

        profile_form = ProfileForm

    return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form})


@login_required

def profile(request):

    return render(request, 'users/profile.html')



波斯汪
浏览 243回答 1
1回答

翻过高山走不出你

我认为你写的两个信号是不必要的。此外,此行也不起作用:profile.user = Profile.objects.get(user=request.user)  因为您尚未登录。未登录,您将无法在此处获取用户实例。但没有必要。因为,您可以从另一个窗体获取用户实例。喜欢这个:def register(request):    if request.method == 'POST':        form = UserRegisterForm(request.POST)        profile_form = ProfileForm(request.POST, request.FILES)        if form.is_valid() and profile_form.is_valid():            user = form.save()            profile = profile_form.save(commit=False)            profile.user = user              profile.save()            username = form.cleaned_data.get('username')            messages.success(request, f'Your account has been created! You are now able to log in')            return redirect('login')    else:        form = UserRegisterForm()        profile_form = ProfileForm()    return render(request, 'users/register.html', {'form': form, 'profile_form': profile_form})另外,请务必删除这两个信号。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python