Tuesday, August 31, 2010

Re: Django UserProfile's - the hardest part of the whole framework

(snip 'programming by accident' code)

I'm not sure you really understand what you're doing :-/


> > > Here's my problem, I know you don't get direct access to the user
> > > model,
>
> > Yes you do.
>
> > > so making the user email editable is kind of tricky
>
> > Why so ?
>
> you can't query for a user with request.user

Query what ?

> but I can with user_id as
> above.

Where exactly ?

> > I personnaly don't use a ModelForm for user profiles - since you
> > (usually) have to mix&match data from both the user and profile
> > models, I find it simpler to use a plain forms.Form and handle the
> > fields/models mapping, saving etc by myself
>
> Do you have an example, I keep piecing together stuff from the b-list
> etc.

Yeps, that's what your code looks like - copy/paste without true
undrestanding...

Here's a (shortened and simplified) snippet:

class ProfileForm(forms.Form):
# User fields
first_name = forms.CharField(
label=_("First name"),
max_length=30
)

last_name = forms.CharField(
label=_("Last name"),
max_length=30
)

email = forms.EmailField(
label=_("E-mail"),
max_length=128,
help_text=_(u"ex : prenom@exemple.com")
)

_USER_FIELDS = (
'first_name',
'last_name',
'email'
)

# Profile fields
address1 = forms.CharField(
label=_("Address 1"),
max_length=80
)

address2 = forms.CharField(
label=_("Address 2"),
max_length=80,
required=False
)

postcode = forms.CharField(
label=_("Postcode"),
max_length=10, # should be enough for most cases ? NB : max 8
in current dataset
required=False # no postcode for IR ???
)

town = forms.CharField(
label=_("Town"),
max_length=100
)


#
--------------------------------------------------------------------------
def _from_model(self, name):
if name in self._USER_FIELDS:
return getattr(self.user, name)
else:
return getattr(self.profile, name)

#
--------------------------------------------------------------------------
def _to_model(self, name, value):
if name in self._USER_FIELDS:
setattr(self.user, name, value)
else:
setattr(self.profile, name, value)

#
--------------------------------------------------------------------------
def __init__(self, profile, *args, **kw):
self.prefix = kw.get("prefix", None)
data = kw.pop('data', {}).copy()

self.profile = profile
self.user = user = profile.user

for name in self.base_fields:
data.setdefault(self.add_prefix(name),
self._from_model(name))

kw['data'] = data
super(ProfileForm, self).__init__(*args, **kw)


#
--------------------------------------------------------------------------
def save(self):
if not self.is_valid():
raise ValueError("trying to save an invalid form")

# XXX : handle transaction here ?
self.user.save()
self.profile.save()

return self.profile, self.user

#
------------------------------------------------------------------------------
#
------------------------------------------------------------------------------
@login_required
@csrf_protect
def profile_edit(request, *args, **kw):
user = request.user
profile = user.get_profile()

if request.method == "POST":
profile_form = ProfileForm(profile, data=request.POST)
if profile_form.is_valid():
profile_form.save()
user.message_set.create(message=_("Your profile has been
modified successfully"))
return HttpResponseRedirect(reverse("core_profile_edit"))
else:
profile_form = ProfileForm(profile)

context = dict(
profile=profile,
profile_form=profile_form,
)

return render_to_response(
"core/profile_edit.html",
context,
context_instance=RequestContext(request)
)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment