First time here? Check out the FAQ!
1

Write a query using user object to get data from different table

I have created a new table which has auth_user table id as its foreign key. My new table has extra information of the user which I want to populate on the profile page of the user.

Here is the model of the new table:

class ShibUser(models.Model):
    auth_user = models.ForeignKey(User)
    shib_username = models.CharField(max_length = 200)
    shib_user_role = models.CharField(max_length = 200)

    class Meta:
        app_label = 'askbot'

Basically way I understand is that write the query but use objects. So I initially started by adding a field in the edit profile:

in askbot/forms.py

role = forms.CharField(
                    label=_('Role'),
                    required=False,
                    max_length=255,
                    widget=forms.TextInput(attrs={'size': 35})
                )

my next goal was to get the user role which is in the new table that I created based on the id of the auth_user table.

if askbot_settings.EDITABLE_SCREEN_NAME:
    self.fields['role'].initial = "test"

Currently I have put dummy "test", How can I accomplish this?

SocialQA's avatar
265
SocialQA
asked 2013-06-05 12:35:33 -0500
edit flag offensive 0 remove flag close merge delete

Comments

Which form are you modifying?

Evgeny's avatar Evgeny (2013-06-06 06:44:21 -0500) edit
add a comment see more comments

1 Answer

0

It's achieved via "related name". Django adds one automatically for each relational field of the models.

In this case one could do:

u = User.objects.get(id=1)
shib_profile = u.shibuser_set.all()[0]
shib_profile.shib_user_role = 'captain'
shib_profile.save()

or:

u.shibuser_set.all().update(shib_user_role='captain')

If you don't like name shibuser_set, create your own with the related_name parameter in the model field definition (see django docs for that).

Most importantly I would recommend you to define that extra model in a separate app. If it's inside askbot code base, it may be harder down the road to keep the code in sync. It will be also more difficult this way to identify bugs as you will be reporting bugs against your custom code base and we may not be able to verify and help you.

It's not a good idea at all to modify askbot/forms.py, much easier to create an app say askbot_shib and define a separate form there.

Then - if adding that form to askbot is not yet available by configuration, we can build such capability. It's already possible to define custom "ask" and "answer" forms and we can have more.

Evgeny's avatar
13.2k
Evgeny
answered 2013-06-06 06:42:34 -0500, updated 2013-06-06 06:53:30 -0500
edit flag offensive 0 remove flag delete link

Comments

add a comment see more comments