Alex Rivera | Logout

How do I create a custom UserChangeForm that does not allow certain fields to be edited?

Asked 2011-04-02T04:59:26.900
10

This is my second post on SO, as well as my second post on Django--please be gentle.

I am working on a simple User model. Users should be able to sign up for the site, and after signing up they should be able to change their account settings upon login. However, if I do the following, Users see a huge form with all kinds of info I don't want them to edit:

views.py

from django.shortcuts import render_to_response, get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import UserChangeForm

@login_required 
def settings( request, template_name = 'accounts/settings.html' ):
    """
    Processes requests for the settings page, where users
    can edit their profiles.
    """
    page_title = 'Account Settings'
    if request.method == 'POST':
        postdata = request.POST.copy()
        form = UserChangeForm( postdata )
        if form.is_valid():
            form.save()
    else:
        form = UserChangeForm()
    title = 'Settings'
    return render_to_response( template_name, locals(), context_instance = RequestContext( request) )

As if that wasn't bad enough, this form doesn't allow any changes to be made, citing "User with this Username already exists" as an error. This confuses me--I am attempting to save a UserChangeForm, so wouldn't it already existing be a given?

I've been looking online for a while now, attempting making my own custom forms, based on other questions I've seen on SO, like so:

forms.py

class CustomUserChangeForm( UserChangeForm ):
    def __init__( self, *args, **kwargs ):
        super( CustomUserChangeForm, self ).__init__( *args, **kwargs )
        if self.instance and self.
Edit
Report

1 Answer

1

It looks like you have not read the documentation carefully.

Let me help you with that, check out using-a-subset-of-fields-on-the-form.

Basically you just need to add exclude = ('fieldname',) to your modelforms meta.

answered 2011-04-02T06:22:26.427

Your Answer