Django, при регистрации пользователя: AttributeError: объект AnonymousUser не имеет атрибута _meta - PullRequest
0 голосов
/ 26 июня 2019

При попытке зарегистрировать нового пользователя с помощью wp_register (это другой тип пользователя), я получаю следующую ошибку:

AttributeError: 'AnonymousUser' object has no attribute '_meta'

Есть разные ответы на этот вопрос, но ни один из них не решил мою проблему,

Система работала нормально, пока я не попытался добавить разные представления для разных пользователей (W и WP). Я также добавил поле «описание» (в качестве теста) в форму регистрации и также пытаюсьсоздать два разных профиля для двух разных пользователей (WP и W).Я создал, как вы увидите ниже, отдельную страницу регистрации для wps (user type2), на которую ссылаются также profile_wp, register_WP и т. Д., И при попытке зарегистрировать пользователя с помощью этой формы я получаю сообщение об ошибке, указанное выше.

Ниже приведены различные соответствующие биты моего кода

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile


class UserRegisterForm(UserCreationForm): #form that inherits from the usercreationform
    email = forms.EmailField()


    class Meta: 
        model = User 




class Register_WP_Form(UserCreationForm): #form that inherits from the usercreationform
    email = forms.EmailField()
    description=forms.EmailField()
    #choice = forms.ChoiceField(required=True, widget=forms.RadioSelect(
    #attrs={'class': 'Radio'}), choices=(('option1','I am a W'),('option2','I am a WP'),))

    class Meta: 
        model = User 

        #when this form validates it creates a new user
        #type the fields to be shown on your form, in that order.
        fields = ['username','email','password1','password2','description'] 





class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta: 
        model = User 
        fields = ['username','email']

class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model= Profile
        fields=['image']

views.py

#USERS (register) view.py
from django.shortcuts import render,redirect
from django.contrib.auth.forms import UserCreationForm
from django.contrib import messages #this allows us flash messages for testing
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm
from .forms import UserUpdateForm
from .forms import Register_WP_Form
from .forms import ProfileUpdateForm

from django.contrib.auth.decorators import login_required

# Create your views here.



def register(request):
    if request.method =='POST':
        #this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
        form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST
        if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
            form.save()#this just saves the account, hashes the password and it's all done for you!
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}, you can now login.')
            return redirect('socialmedia-moreinfo')

    else:
        form =UserRegisterForm() #if the form input is invalid, render the empty form again

    #above we are creating a blank form and rendering it to the template
    return render(request, 'users/register.html',{'form':form})
#different types of messages message . debug, inf success warning and error


def register_wp(request):
    if request.method =='POST':
        #this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
        form = Register_WP_Form(request.POST) #create a form that has the data that was in request.POST
        if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
            form.save()#this just saves the account, hashes the password and it's all done for you!
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}, you can now login.')
            print("SUCCESS")
            return redirect('profile-wp')

    else:
        form =Register_WP_Form() #if the form input is invalid, render the empty form again

    #above we are creating a blank form and rendering it to the template
    return render(request, 'users/register-wp.html',{'form':form})
#different types of messages message . debug, inf success warning and error


def register_w(request):
    if request.method =='POST':
        #this UserRegisterForm is created in forms.py and inherits from UserCreationForm (the ready made form)
        form = UserRegisterForm(request.POST) #create a form that has the data that was in request.POST
        if form.is_valid(): #is the form valid (do you have a username like this already, passwords match?
            form.save()#this just saves the account, hashes the password and it's all done for you!
            username = form.cleaned_data.get('username')
            messages.success(request,f'Account created for {username}, you can now login.')
            return redirect('profile')

    else:
        form =UserRegisterForm() #if the form input is invalid, render the empty form again

    #above we are creating a blank form and rendering it to the template
    return render(request, 'users/register-w.html',{'form':form})
#different types of messages message . debug, inf success warning and error





@login_required #this is a decorator (adds functionality to an existing function)
def profile(request):
    if request.method =='POST':
        u_form =UserUpdateForm(request.POST,instance=request.user)
        p_form =ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request,f'Your account has been updated')
            return redirect('profile')

    else:   
        u_form =UserUpdateForm(instance=request.user)
        p_form =ProfileUpdateForm(instance=request.user.profile)


    context={
            'u_form': u_form,
            'p_form': p_form
        }

    return render(request,'users/profile.html',context)
        #add a login required dectorator that django provides
        #we want a user to be logged in to view this profile view
        #see the very top to import decorators






def profile_wp(request):
    if request.method =='POST':
        u_form =UserUpdateForm(request.POST,instance=request.user)
        p_form =ProfileUpdateForm(request.POST, request.FILES,instance=request.user.profile)

        if u_form.is_valid() and p_form.is_valid():
            u_form.save()
            p_form.save()
            messages.success(request,f'Your account has been updated')
            return redirect('profile-wp')

    else:   
        u_form =UserUpdateForm(instance=request.user)
        p_form =ProfileUpdateForm(instance=request.user.profile)


    context={
            'u_form': u_form,
            'p_form': p_form
        }

    return render(request,'users/profile-wp.html',context)
        #add a login required dectorator that django provides
        #we want a user to be logged in to view this profile view
        #see the very top to import decorators

urls.py

#URLS in main project directory

from django.contrib import admin
from django.contrib.auth import views as auth_views #add this for user views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_views


#now create paths for the user views (default django user views) below
urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/',user_views.register, name='register'),
    path('register_wp/',user_views.register_wp, name='register_wp'),
    path('register_w/',user_views.register_w, name='register_w'),
    #path('socialmedia/',include('socialmedia.urls')),
    path('login/',auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('profile/',user_views.profile, name='profile'),
    path('profile-wp/',user_views.profile_wp, name='profile-wp'),
    path('',include('socialmedia.urls')),
]

if settings.DEBUG:#if we currently in DEBUG mode, then add the below to URL patterns
    urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
...