1

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 + ' ',
                ['[email protected]'],
                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 i m 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!

1
  • Note you should use return render(request, 'threeD/contacts.html', {'form': form}) in your view. If you use the form class, then you will get a blank form in the template, so errors will not be displayed. Commented Apr 12, 2017 at 10:56

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, Alasdair, for your answer. I am using Django 1.9 version and in my views code i have request.user.is_authenticated(), but it still doesn't work. It returns me True all the time. And i am sure i am not logged in, since in my base template i am changing navigation bar using {% if user.is_authenticated %} ... {% endif %} and it is not getting changed (so i am sure i am not logged in), then i am accessing ContactsView and getting always True from my request.user.is_authenticated(), which leads to error :/
If request.user.is_authenticated() is True then I really think you are logged in. If the navigation bar says that you are not logged in, then that could be a bug in the navigation bar code.
If request.user.is_authenticated() is True you really are logged in. As Ishan says in his answer, the error is probably coming from the form_class_nonlogged = ContactForm_nonlogged(request=request), not from inside the if request.user.is_authenticated(): if statement. You can debug this yourself, by adding print statements or looking at the traceback.
Alasdair, how would you print to debug? Sorry, i m quite new in the topic, that's why i am asking silly Q :D
If you are using the Django development server and you add print(request.user.is_authenticated()) to the top of your view, then you'll see the result in the window where python manage.py runserver is running.
1

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'"

4 Comments

Good spot! The first two lines should be removed entirely. They are only used in the return render() line, and as I said in the comment above, you should be using form there, not the class. It would only make sense to use form_class if you then use form = form_class(...) later in your code instead of the if/else with ContactForm_logged(...) and ContactForm_nonlogged(...). You can only do this if you change the nonlogged form to accept the request as well, or if you set the form kwargs as a separate step.
Awesome, thank you Ishan! I have added an extra if statement at the beginning of my view, like: if request.user.is_authenticated(): form_class = ContactForm_logged(request=request) else: form_class = ContactForm_nonlogged(request=request) and am returning form_class. And it works now. Thank you, guys, for help!!!
Ou, now I see my problem... Thank you, @Alasdair. I have removed first two lines completely and changed my return to 'form': form, as u suggested above and it still works perfectly
Yes @Alasdair. form should be used in place of form_class and form_class_nonlogged in render method calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.