Heyraoul
Heyraoul

Reputation: 3

Display user data in template

I'm new in Django. I want to display in templates user's information where he connect, but when I change page, data disappears!

views.py:

def login(request):
    if request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        user = authenticate(username=username, password=password)

        data = {}
        data['user'] = user

        if user is not None:
            if user.is_authenticated:
                return redirect(accueil)

            else:
                messages.error(request, 'Compte inactif.')

        else:
            messages.error(request, 'Identifiant et/ou mot de passe invalide.')

     return render(request, 'login.html')

Models.py:

class AbstractCustomerUser(AbstractBaseUser):
        """
        An abstract base class implementing a fully featured User model with
        admin-compliant permissions.

        Username, password and email are required. Other fields are optional.
        """
    username = models.CharField(_('username'), max_length=30, unique=True,
        help_text=_('Required. 30 characters or fewer. Letters, digits and '
                    '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$', _('Enter a valid username.'), 'invalid')
        ])


    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('email address'), blank=True, unique=True)
    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
    company = models.ForeignKey(Customer)
    referent_for_customers = models.ManyToManyField('Customer',
                                                    related_name='referents',
    verbose_name="est référent pour")

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['id', 'company']

    class Meta:
        # For an unknown reason, fails to save a modified object with this
        # constaint. Comment it for now:
        #unique_together = ('username', 'company')
        verbose_name = _('utilisateur')
        abstract = True

    class CustomerUser(AbstractCustomerUser):
        class Meta(AbstractCustomerUser.Meta):
            db_table = 'customers_customeruser'
            swappable = 'AUTH_USER_MODEL'
            verbose_name = 'utilisateur portail'

templates:

<div id="header">
   <h2>Portail Client</h2>
   Bienvenue {{ user.username }}

   CustomerUser table info: {{ user.company_id }}, {{ user.last_login }} 
   Customer table info:  {{ user.company.name }}

   <a href="/referents/password_change/">Modifier mot de passe</a>
   <a href="/referents/logout/">Déconnexion</a>
</div>

Upvotes: 0

Views: 244

Answers (3)

dannymilsom
dannymilsom

Reputation: 2406

Looks like the user object is not available inside your template. If the user object is not available in the template, nothing will be displayed when the template evaluates {{ user.username }}

From the docs -

If you use a variable that doesn’t exist, the template system will insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is set to '' (the empty string) by default.

You can pass the user object to the template by modifying the appropriate view which returns the welcome template, using either render() which forces the use of a RequestContext implicitly or render_to_response() where you have to explicitly pass a RequestContext instance

Upvotes: 0

Marius Darila
Marius Darila

Reputation: 873

in your views.py you should use RequestContext

from django.template import RequestContext
from django.shortcuts import render_to_response

def login(request):
args={}
...
return render_to_response('login.html', args, context_instance=RequestContext(request))

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

user is automatically provided to the template via the context processor. But these only run if you are using a RequestContext when rendering your template: either by specifically passing it in (eg with the context_instance parameter to render_to_response), or by using the newer render shortcut.

So in all your other views, you need to be sure you are doing:

return render(request, 'your_template.html', params)

Upvotes: 1

Related Questions