Django – Access to the relational database in view

This is my

class RegistrationForm(forms.Form):
    ('none','---'), ('dog', 'Dog'),

    username = forms.CharField()
    email = forms.EmailField()
    password1 = forms.CharField()
    birthdate = forms.DateField(widget=extras.SelectDateWidget)
    pet = forms.ChoiceField(choices=PET_CHOICES)

This is my

from django.db import models
from django.contrib.auth.models import User
# Create your models here.

class UserExtended(models.Model):
    user = models.ForeignKey(User)
    pet = models.CharField(max_length=40)
    age = models.PositiveSmallIntegerField()

As you can see, this model extends the default Django User model. Now, this is my view which registers users:

def registerView(request):
    form = RegistrationForm()
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = User.objects.create_user(


            return HttpResponseRedirect('/')

I’m wondering, is this part of my code correct?['pet']

With the two lines above, I am trying to add to the UserExtended model which has a ForiegnKey with User. I think I am doing something wrong because after the user is created and I authenticate and log the user in using the functions




provided by django, and if I place this in my template which Django redirects to after logging in

your pet is {{ }}

it does not display another for

{{ }}

. It just says:

your pet is

. Any idea why it does not display anything? {{ }}

The problem here is,

returns a RelatedManager
type. So, you cannot do a simple .pet
would not work.

Now, looking at your models, i am assuming
you intend UserExtended
to a OneToOneField
, rather than a ForeignKey
. As long as you can manage the (non) creation of duplicates, you are just fine.

Now, coming back to your issue:

You can do

user_extended = user.userextended_set.all()[0]
#Or if you are sure it is a unique relationship,
#user_extended = user.userextended_set.get()
#Note - this would raise error if MultipleObjectsReturned, or DoesNotExist = form.cleaned_data['pet']
user_extended.age = form.cleaned_data['age']

Also, in the template,

{{ }}

Or even this:

{% for u_e in user.userextended_set.all %}
{% empty %}
    Not found
{% endfor %}
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Django – Access to the relational database in view

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录