I'm trying to make editable User profile and found, how to add some fields to it... But also I need to make editable first and last name, email and one field for change user password. Now I got only user and additional fields in my form...
How can I realise that?
My model:
import PIL
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.db import models
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User)
user_phone = models.CharField(max_length=140, blank=True, null=True)
user_picture = models.ImageField(upload_to='users', blank=True, null=True)
user_balance = models.IntegerField(default=0)
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u) [0])
My forms.py :
from django import forms
from userprofile.models import UserProfile
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('user', 'user_phone', 'user_picture', 'user_balance')
My view:
from django.shortcuts import render, render_to_response
from django.shortcuts import HttpResponseRedirect, Http404
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.core.context_processors import csrf
# Create your views here.
from userprofile.forms import UserProfileForm
from userprofile.models import UserProfile
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html', args)
And my template:
{% for field in form %}
{{ field.error }}
{% endfor %}
<form action="/users/profile/" method="POST">{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Update" />
</form>
If you cant call the user fields from the UserProfile then you can create a form for the User model
You need to show both forms in your view also. Check this example ModelForm with OneToOneField in Django For the password field you might need to do something like this, check the examples.
https://docs.djangoproject.com/en/1.5/topics/auth/customizing/#a-full-example