title: Editing a userprofile on django
body: <p>How to create a userprofile editable page and upon clicking submission it updates the details provided during registration(the details stored in the database) using DJANGO?.</p>
  
  <p>Creation of registration form for a user, and like i have said in my opening post, i want the user after he must have logged in to able to edit what he provided during registration and it will update the previous details stored in the database.</p>
  
  <p>I know i need to create a view for it, but have not arrived at how to call on the details provided during registration. Well maybe using user.get_profile()</p>
  
  <h1>forms.py</h1>
  
  <pre><code>from django import forms
  from django.contrib.auth.models import User
  from django.forms import ModelForm
  from registeredmember.models import Registeredmember
  
  
  class RegistrationForm(ModelForm):
      first_name      = forms.CharField(label=(u'First Name'))
      middle_name     = forms.CharField(label=(u'Middle Name'))
      last_name       = forms.CharField(label=(u'Last Name'))
      occupation      = forms.CharField(label=(u'Occupation'))
      income          = forms.IntegerField(label=(u'Income Amount'))
      age             = forms.IntegerField(label=(u'Age'))
      address_line1   = forms.CharField(label=(u'Address line 1'))
      address_line2   = forms.CharField(label=(u'Address line 2'))
      city            = forms.CharField(label=(u'City'))
      state           = forms.CharField(label=(u'State'))
      phone_no_Mobile = forms.IntegerField(label=(u'Phone Number (Home)'))
      phone_no_Work   = forms.IntegerField(label=(u'Phone Number (Work)'))
      purpose         = forms.CharField(label=(u'Purpose'))
      username        = forms.CharField(label=(u'Username'))
      email           = forms.EmailField(label=(u'Email Address'))
      password        = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
      password1       = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput)
  
  
      class Meta:
          model = Registeredmember
          exclude = ('user','reference_number',)
      def clean_username(self):
          username = self.cleaned_data['username']
          try:
              User.objects.get(username=username)
          except User.DoesNotExist:
              return username
          raise forms.ValidationError('That username is already taken, please select another.')
  
  
      def clean_email(self):
          email = self.cleaned_data['email']
          try:
              User.objects.get(email=email)
          except User.DoesNotExist:
              return email
          raise forms.ValidationError('That email address is already in the database, please provide another.')
  
  class LoginForm(forms.Form):
      username    = forms.CharField(label=(u'Username'),widget=forms.TextInput(attrs={'size': '30'}))
      password    = forms.CharField(label=(u'Password'), widget=forms.PasswordInput)
  </code></pre>
  
  <h1>views.py</h1>
  
  <pre><code>from django.http import HttpResponseRedirect
  from django.contrib.auth.models import User
  from django.contrib.auth.decorators import login_required
  from django.shortcuts import render_to_response
  from django.template import RequestContext
  from registeredmember.forms import RegistrationForm, LoginForm
  from registeredmember.models import Registeredmember 
  from django.contrib.auth import authenticate, login, logout
  import random, time
  from random import randint
  
  
  
  
  
  
  
  
  def userregistration(request):
      if request.user.is_authenticated():
              return HttpResponseRedirect('/profile/')
      if request.method == 'POST':
          form = RegistrationForm
          form = RegistrationForm(request.POST)
          if form.is_valid():
              user = User.objects.create_user(username=form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
              user.first_name = form.cleaned_data['first_name']
              user.last_name = form.cleaned_data['last_name']
              user.save()
              registeredmember = Registeredmember(user=user, prefix = form.cleaned_data['prefix'],first_name=form.cleaned_data['first_name'],\
                                                  middle_name=form.cleaned_data['middle_name'],last_name=form.cleaned_data['last_name'],gender=form.cleaned_data['gender'],\
                                                  occupation=form.cleaned_data['occupation'],income=form.cleaned_data['income'],age=form.cleaned_data['age'],\
                                                  address_line1=form.cleaned_data['address_line1'],address_line2=form.cleaned_data['address_line2'],city=form.cleaned_data['city'],\
                                                  state=form.cleaned_data['state'],phone_no_Mobile=form.cleaned_data['phone_no_Mobile'],phone_no_Work=form.cleaned_data['phone_no_Work'],\
                                                  purpose=form.cleaned_data['purpose'])
  
  
              registeredmember.save()
  
  
  
              return render_to_response('carloan/regsuccessful.html',{'ref_no': ref_no}, context_instance=RequestContext(request))
          else:
              return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
      else:
          '''user is not submitting the form, show them a blank registration form'''
          form = RegistrationForm()
          return render_to_response('carloan/register.html', {'form': form}, context_instance=RequestContext(request))
  
  
  @login_required
  def Profile(request):
      if not request.user.is_authenticated():
          return HttpResponseRedirect('/login/')
      registeredmember = request.user.get_profile
      return render_to_response('carloan/profile.html', {'registeredmember': registeredmember}, context_instance=RequestContext(request))
  
  
  
  def LoginRequest(request):
      if request.user.is_authenticated():
          return HttpResponseRedirect('/profile/')
      if request.method =='POST':
          form = LoginForm(request.POST)
          if form.is_valid():
              username = form.cleaned_data['username']
              password = form.cleaned_data['password']
              registeredmember = authenticate(username=username, password=password)
              if registeredmember is not None:
                  login(request, registeredmember)
                  return HttpResponseRedirect('/profile/')
              else:
                  return render_to_response('carloan/loginerror.html', context_instance=RequestContext(request))
          else:
              '''user is submitting a blank login form, notify him that he submitted a blank form''' 
              return render_to_response('carloan/loginblank.html', context_instance=RequestContext(request))
  
      else:
          '''user is not submitting the form, show the login form'''
          form = LoginForm()
          return render_to_response('carloan/login.html',{'form': form}, context_instance=RequestContext(request))
  
  
  def LogoutRequest(request):
      logout(request)
      return render_to_response('carloan/logout.html', context_instance=RequestContext(request))
  </code></pre>
  
  <h1>The code below gives the error username already exists, but when i specify a new username it updates although it doesn't update the username but the other fields</h1>
  
  <h1>views.py for the editprofile</h1>
  
  <pre><code>@login_required
  def editprofile(request):
      registeredmember = request.user.get_profile()
      if request.method == 'POST':
          userprofile_edit = RegistrationForm(request.POST, instance = registeredmember)
          if userprofile_edit.is_valid():
              userprofile_edit.save()
              return HttpResponseRedirect('/profile/')
      else:
          userprofile_edit = RegistrationForm(instance = registeredmember)
      return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
  </code></pre>
  
  <h1>Got it sorted out with codes below:</h1>
  
  <h1>forms.py</h1>
  
  <pre><code>class EditForm(forms.ModelForm):
      class Meta:
          model = Registeredmember
          exclude = ('user','username','email','password','password1',)
  </code></pre>
  
  <h1>views.py</h1>
  
  <pre><code>@login_required
  def editprofile(request):
      if request.method == 'POST':
          userprofile_edit = EditForm(request.POST, instance = request.user.get_profile())
          if userprofile_edit.is_valid():
              userprofile_edit.save()
              return HttpResponseRedirect('/profile/')
      else:
          userprofile_edit = EditForm(instance = request.user.get_profile())
      return render_to_response('carloan/editprofile.html', {'userprofile_edit': userprofile_edit}, context_instance=RequestContext(request))
  </code></pre>
  
  <p>Thank you all...</p>