Friday, February 24, 2012

Re: help needed with multiple profile images with UserProfile

On Fri, Feb 24, 2012 at 2:55 PM, richard <pullenjenna10@gmail.com> wrote:
> Hi Tom,
>
> Thanks for your reply. So for clarity i thought i was getting the
> userprofile to pass into the bound form so that the userprofile_id in
> the UserProfilePic would get populated/saved. as if i leave the
> instance as None
> then i get an error saying that userprofile_id cannot be empty?

Correct. So when you are creating a new UserProfilePic object, you
will need to populate those fields manually. I know of a couple of
techniques:

1) Do it manually:

frm = UserProfilePicForm(request.POST, instance=None)
if frm.is_valid():
instance = frm.save(commit=False)
instance.userprofile = user.get_profile()
instance.save()

2) Pass the profile to the form's constructor, override the save
method and implement the same logic there:
class UserProfilePicForm(ModelForm):
def __init__(self, *args, **kwargs):
self.profile = kwargs.pop('profile')
def save(self, commit=True, *args, **kwargs):
instance = super(UserProfilePicForm, self).save(commit=False,
*args, **kwargs)
instance.userprofile = self.profile
if commit:
instance.save()
return instance
class Meta:
model = UserProfilePic
fields = ('profilepic',)


>also,
> is a 1 to may relationship here correct for what i want to achieve?
>

Probably. You don't want multiple profiles linking to the same picture
do you? IE each picture has exactly one owner.

Cheers

Tom

--
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