简体   繁体   中英

How to request.user.is_authenticated() in views.py? Django

I am trying to check if user is logged in from my views.py file. As depending if user is logged in it should return me different forms. But request.user.is_authenticated() or request.user.is_authenticated is not working, i always get True value.

My view:

def ContactsView(request):
    form_class = ContactForm_logged(request=request)
    form_class_nonlogged = ContactForm_nonlogged(request=request)

    # new logic!
    if request.method == 'POST':
        if request.user.is_authenticated():
            form = ContactForm_logged(data=request.POST, request = request)
        else:
            form = ContactForm_nonlogged(data=request.POST)

        if form.is_valid():
            contact_name = request.POST.get(
                'contact_name'
                , '')
            contact_email = request.POST.get(
                'contact_email'
                , '')
            form_content = request.POST.get('content', '')
            subjects = form.cleaned_data['subjects']
            subjects = dict(form.fields['subjects'].choices)[subjects]
            # Email the profile with the
            # contact information
            template = get_template('threeD/email/contact_template.txt')
            context = Context({
                'contact_name': contact_name,
                'subjects': subjects,
                'contact_email': contact_email,
                'form_content': form_content,
            })
            content = template.render(context)

            email = EmailMessage(
                "New message from " + contact_name,
                content,
                "Message - " + subjects + ' ',
                ['smart.3d.printing.facility@gmail.com'],
                headers={'Reply-To': contact_email}
            )
            email.send()
            messages.success(request, "Thank you for your message.")
            return redirect('/index/contacts/')

    else:
        if request.user.is_authenticated():
            form = ContactForm_logged(request=request)
        else:
            form = ContactForm_nonlogged()

    if request.user.is_authenticated():
        return render(request, 'threeD/contacts.html', {
            'form': form_class,
        })
    else:
        return render(request, 'threeD/contacts.html', {
            'form': form_class_nonlogged,
        })

And two of my forms:

class ContactForm_logged(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    subjects = forms.ChoiceField(choices=emailsubjects)
    content = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(ContactForm_logged, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = "Your name:"

        if (self.request.user.first_name == '' or self.request.user.last_name ==''):
            self.fields['contact_name'].initial = 'Type your name here'
            self.fields['contact_name'].widget.attrs['readonly'] = False
        else:
            self.fields['contact_name'].initial = self.request.user.first_name
            self.fields['contact_name'].widget.attrs['readonly'] = True

        self.fields['contact_email'].label = "Your email:"

        if (self.request.user.profile.sdu_email == ''):
            if (self.request.user.email == ''):
                self.fields['contact_email'].initial = 'Type your email here'
                self.fields['contact_email'].widget.attrs['readonly'] = False
            else:
                self.fields['contact_email'].initial = self.request.user.email
                self.fields['contact_email'].widget.attrs['readonly'] = True
        else:
            self.fields['contact_email'].initial = self.request.user.profile.sdu_email
            self.fields['contact_email'].widget.attrs['readonly'] = True

        self.fields['content'].label = "What do you want to say?"
        self.fields['content'].initial = "Dear, Smart 3D printing facility team, I like this WEB server very much, but ..."

        self.fields['subjects'].label = "Please, select the subject of your message"


class ContactForm_nonlogged(forms.Form):
    contact_name = forms.CharField(required=True)
    contact_email = forms.EmailField(required=True)
    subjects = forms.ChoiceField(choices=emailsubjects)
    content = forms.CharField(
        required=True,
        widget=forms.Textarea
    )

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop("request")
        super(ContactForm_nonlogged, self).__init__(*args, **kwargs)
        self.fields['contact_name'].label = "Your name:"

        self.fields['contact_name'].initial = 'Type your name here'

        self.fields['contact_email'].label = "Your email:"

        self.fields['contact_email'].initial = 'Type your email here'

        self.fields['content'].label = "What do you want to say?"
        self.fields['content'].initial = "Dear, Smart 3D printing facility team, I like this WEB server very much, but ..."

        self.fields['subjects'].label = "Please, select the subject of your message"

The problem is that, whether i am logged in or am not i always get ContactForm_logged form back. And if im not logged in than, getting ContactForm_logged form back i get an error, that "'AnonymousUser' object has no attribute 'first_name'". I read on forums that that could have happened if i call request.user.is_authenticated() wrong, but i have tried both request.user.is_authenticated() and request.user.is_authenticated, both give me the same error :/

Any help would be greatly appreciated!

If you are using Django 1.10+, then you should use the property request.user.is_authenticated .

If you are using Django 1.9 or earlier, then you must use request.user.is_authenticated() . Using request.user.is_authenticated in Django 1.9 or earlier is a mistake which can cause sensitive data to be leaked, because it will always be evaluated as True .

If you are using the correct version and it is returning True , then that suggests you really are logged in.

The problem is in the first line of your view method definition:

def ContactsView(request):
    form_class = ContactForm_logged(request=request)

Here you are creating an instance of ContactForm_logged class. This line will be executed every time the view method is called. So an instance of ContactForm_logged class will be created everytime, whether user is logged-in or not. Further, in the __init__ method of ContactForm_logged class you are accessing self.request.user.first_name . So when the ContactForm_logged instance is being initialized for unauthenticated requests it is raising the error: " 'AnonymousUser' object has no attribute 'first_name' "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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