Django – Access to the relational database in view

This is my forms.py:

class RegistrationForm(forms.Form):
    PET_CHOICES = (
    ('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 models.py:

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(
                username=form.cleaned_data['username'],
                password=form.cleaned_data['password1'],
                email=form.cleaned_data['email']
            )

            user.userextended_set.pet=form.cleaned_data['pet']
            user.userextended_set.age=form.cleaned_data['birthdate']

            return HttpResponseRedirect('/')

I’m wondering, is this part of my code correct?

user.userextended_set.pet=form.cleaned_data['pet']
user.userextended_set.age=form.cleaned_data['birthdate']

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

authenticate()

and

login()

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

your pet is {{ user.userextended_set.pet }}

it does not display another for

{{ user.userextended_set.pet }}

. It just says:

your pet is

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

The problem here is,

user.userextended_set
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

user_extended.pet = form.cleaned_data['pet']
user_extended.age = form.cleaned_data['age']

Also, in the template,

{{ user.userextended_set.0.pet }}

Or even this:

{% for u_e in user.userextended_set.all %}
    {{u_e.pet}}
{% 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

使用声明 | 英豪名录