I am using an extended user model from all-auth. I am able to pull both extended model fields (like organization), as well as the standard user fields (like user.email) easily on all templates except one.
Because I struggled to build an update form (as I'm still new to Django), I ended up using properties/instances. This worked. I can edit orgnization. But for some reason on this template I cannot call user.email. I've tried all variations of it, from RequestContext to failed attempts at passing it in other ways.
Model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE)
organization = models.CharField(max_length=100)
def __str__(self):
return self.user.organization
# I got this from an old tutorial:
User.profile_p = property(lambda u: Profile.objects.get_or_create(user=u)[0])
View:
from django.shortcuts import render, render_to_response
from django.http import HttpResponseRedirect
from django.template.context_processors import csrf
from .forms import UserProfileForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import Profile
@login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile_p)
if form.is_valid():
form.save()
return HttpResponseRedirect('/base_home.html')
else:
logged_user = request.user
profile = logged_user.profile_p
form = UserProfileForm(instance=logged_user.profile_p)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html', args)
Template:
{% extends 'base.html' %}
<title>{% block title %}Admul:{% endblock %}</title>
{% block content %}
<div id="cd_content">
<div class="container-fluid">
<div class="row-fluid">
<h3>Account Details for: {{ user.email }}</h3>
<div class="widget-box">
<div class="widget-content nopadding">
{% for field in form %}
{{field.error}}
{% endfor %}
<form method="post" action="/cust_profile/profile/">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Edit »</button>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
For some reason, user.email or many variations thereof (like {{request.user.email}} ) does not work in this template. It, however, works perfectly fine in all other templates. Is it something to do with my view cancelling the RequestContext info from being passed?
Also, thanks in advance if you see me making any other silly errors that can be fixed.
You should not be using render_to_response
in your view. That does not run context processors, and so does not add the request or user variables. Use render
instead:
return render(request, 'profile.html', args)
Also note that CSRF will be added by a context processor, so there is no need to add it manually as you are doing.