Reputation: 2884
I have the following models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
url = models.URLField(blank=True)
address=models.CharField(max_length=60)
location = models.CharField(max_length=30)
join_date = models.DateField(auto_now_add=True)
I have the following forms.py
class UserForm(ModelForm):
class Meta:
model = UserProfile
I have the following views.py
def login_temp(request):
form = UserForm()
c = RequestContext(request, {
'form': form,
})
return render_to_response('registration/login.html', c)
In my template (login.html), how do I access fields of the django-defined User class. I'm currently using the syntax below. With this syntax, the "address" input field appears in my template, but the "username" input field does not
<form action="/accounts/register/" method="POST">
<label class="control-label" for="id_address">Address</label>
{{ form.address }}
<label class="control-label" for="id_username">Username</label>
{{ form.username }}
</form>
I tried doing {{ form.user.username }}
, but that didn't work either. What am I doing wrong? How do I get get the username field to appear in my template? FYI, the variable username is defined in the User Model. The User model is a "library" that is pre-defined with Django.
Upvotes: 0
Views: 296
Reputation: 10477
If you want to load the form with date from an existing model instance, you need to change this line
form = UserForm()
to something like
form = UserForm(instance=existing_user_profile)
where existing_user_profile
is the existing instance of UserProfile.
Upvotes: 1
Reputation: 599630
You're confusing a few things here. An instance of your UserProfile model has access to the related User instance via the user
attribute, so you would do my_profile.user.username
.
But here you are not talking about instances, you are talking about forms. It doesn't make sense to ask how you would access the fields of the related model. Forms only have the fields that are actually defined by that form, and in your case you have a form that contains just the fields for the UserProfile model.
If you want fields for the user model, you'll need to add them to the form definition yourself. But you'll need to save them manually - they won't be included in the automatic form.save()
. Alternatively, use two separate modelforms, included within a single HTML form element.
Upvotes: 0
Reputation: 2569
You can access the user object through the reverse relation. Try this:
{{ form.user.username }}
Upvotes: 0