-1

I am using Django-userena to extend user profile behavior.

What I am trying to do is either override the edit_profile function in userena/forms.py or handle this from my myapp/forms.py.

In myapp/models.py I have added the new fields that I would like to include in the form.

models.py

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,verbose_name=_('user'),related_name='my_profile')
    storename=models.CharField(null=True, blank=True, max_length=20)
    streetaddress=models.CharField(null=True, blank=True, max_length=30)
    city = models.CharField(null=True, blank=True, max_length=20)
    state = models.CharField(null=True, blank=True, max_length=20)
    zipcode = models.IntegerField(_('zipcode'),null=True, blank=True)
    nearbyzips1=models.IntegerField(null=True, blank=True)
    nearbyzips2=models.IntegerField(null=True, blank=True)

my question is what do I add to either forms or views.py in userena to save these attributes?

userena/forms.py

class EditProfileForm(forms.ModelForm):
    """ Base form used for fields that are always required """
    first_name = forms.CharField(label=_('First name'),max_length=30,required=False)
    last_name = forms.CharField(label=_('Last name'),max_length=30,required=False)

    def __init__(self, *args, **kw):
        super(EditProfileForm, self).__init__(*args, **kw)
        # Put the first and last name at the top
        try:  # in Django < 1.7
            new_order = self.fields.keyOrder[:-2]
            new_order.insert(0, 'first_name')
            new_order.insert(1, 'last_name')
            self.fields.keyOrder = new_order
        except AttributeError:  # in Django > 1.7
            new_order = [('first_name', self.fields['first_name']), ('last_name', self.fields['last_name'])]
            new_order.extend(list(self.fields.items())[:-2])
            self.fields = OrderedDict(new_order)

    class Meta:
        model = get_profile_model()
        exclude = ['user']

    def save(self, force_insert=False, force_update=False, commit=True):
        profile = super(EditProfileForm, self).save(commit=commit)
        # Save first and last name
        user = profile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        return profile

Can I simply just add

user.storename = self.cleaned_data['storename']
user.streetaddress = self.cleaned_data['streetaddress']

ect.. Or is there more to it?

userena/views.py

@permission_required_or_403('change_profile', (get_profile_model(), 'user__username', 'username'))    
def profile_edit(request, username, edit_profile_form=EditProfileForm,template_name='userena/profile_form.html', success_url=None,extra_context=None, **kwargs):

    user = get_object_or_404(get_user_model(), username__iexact=username)        
    profile = get_user_profile(user=user)  
    user_initial = {'first_name': user.first_name,'last_name': user.last_name}   
    form = edit_profile_form(instance=profile, initial=user_initial)

    if request.method == 'POST':    
        form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial)

        if form.is_valid():    
            profile = form.save()

            if userena_settings.USERENA_USE_MESSAGES:    
                messages.success(request, _('Your profile has been updated.'), fail_silently=True)

            if success_url:    
                # Send a signal that the profile has changed    
                userena_signals.profile_change.send(sender=None, user=user)
                redirect_to = success_url
            else:
                redirect_to = reverse('userena_profile_detail', kwargs={'username': username})

            return redirect(redirect_to)

    if not extra_context: 
        extra_context = dict()

    extra_context['form'] = form
    extra_context['profile'] = profile

    return ExtraContextTemplateView.as_view(template_name=template_name,extra_context=extra_context)(request)
Prakhar Trivedi
  • 8,218
  • 3
  • 28
  • 35
david
  • 6,303
  • 16
  • 54
  • 91

1 Answers1

0

If your MyProfile class is the model being returned by get_profile_model() (this isn't clear from your code) then that will be the model the form is built from. You should then be able to see your extra fields in the form, and when you save the form, it will save the model.

You should not need to anything like:

user.storename = self.cleaned_data['storename']
user.streetaddress = self.cleaned_data['streetaddress']

In fact, that would be incorrect anyway, since that's saving those attributes to the user, not the profile. It looks like you've built that form from an example, so unless you really want to keep that first name and last name stuff, I would suggest rewriting it to make it much simpler:

class MyProfileForm(forms.ModelForm):
    class Meta: 
        model = MyProfile
        exclude = ['user']

And that's all.

ChidG
  • 3,053
  • 1
  • 21
  • 26