Question

I am developing a simple LMS system where I have 3 stakeholders Administrator, Faculty Members and Students. Administrator can create, edit, delete, block and list user accounts, with my developement so far I am able to create and list all users.

Now I am stuck at editing user profile, my requirement is when I click on any listed users it should open my extended/customized user profile in a form and I should have the ability to edit any opened user profile.

Below are my code snippets:

MODELS.PY:

from django.contrib.auth.models import User
class UserInformation(models.Model):
    user = models.ForeignKey(User, unique=True)
    degree = models.ForeignKey(Degree, null=True, blank=True)
    stakeholder = models.ForeignKey(Stakeholder)
    cell_number = models.CharField(max_length=32, null=True, blank=True)

    def __str__(self):
        return self.user.username

VIEWS.PY (to create user):

def ad_create_user(request):
    if request.method == 'POST':
        firstname = request.POST['firstname']
        lastname = request.POST['lastname']
        username = request.POST['username']
        password = request.POST['password']
        email = request.POST['email']
        group = request.POST['group']
        degree = request.POST['degree']
        cell_no = request.POST['cell_no']
        new_user = User.objects.create_user(username, email, password)
        new_user.first_name = firstname
        new_user.last_name = lastname
        new_user.save()

        if group == 'option_one':
            set_group = 3
            new_user.groups.add(3)
            userinfo = UserInformation(user=User.objects.get(username=username), degree=Degree.objects.get(pk=degree),
                                       stakeholder=Stakeholder.objects.get(pk=set_group), cell_number=cell_no)
            userinfo.save()
        if group == 'option_two':
            set_group = 2
            new_user.groups.add(2)
            userinfo = UserInformation(user=User.objects.get(username=username),
                                       stakeholder=Stakeholder.objects.get(pk=set_group), cell_number=cell_no)
            userinfo.save()
        if group == 'option_three':
            set_group = 1
            new_user.groups.add(1)
            userinfo = UserInformation(user=User.objects.get(username=username),
                                       stakeholder=Stakeholder.objects.get(pk=set_group), cell_number=cell_no)
            userinfo.save()
        return HttpResponseRedirect('/administrator/user_management/')
    return render(request, 'MobiApp/create_user.html', {'form': CreateUserForm()})

FORMS.PY (to create user):

class CreateUserForm(forms.Form):
    firstname = forms.CharField(max_length=64)
    lastname = forms.CharField(max_length=64)
    username = forms.CharField(max_length=16)
    password = forms.CharField(
        widget=forms.PasswordInput(),
    )
    email = forms.EmailField()
    group = forms.ChoiceField(
        choices=(
            ('option_one', "Student"),
            ('option_two', "Faculty Member"),
            ('option_three', "Administrator"),
        ),
        widget = forms.RadioSelect,
        initial = 'option_one',
    )
    degree = forms.ModelChoiceField(queryset=Degree.objects.all())
    cell_no = forms.CharField()

    helper = FormHelper()
    helper.form_class = 'form-horizontal'
    helper.layout = Layout(
        Field('firstname', css_class='input-xlarge'),
        Field('lastname', css_class='input-xlarge'),
        Field('username', css_class='input-xlarge'),
        Field('password', css_class='input-xlarge'),
        Field('email', css_class='input-xlarge'),
        'group',
        'degree',
        Field('cell_no', css_class='input-xlarge'),
        FormActions(
            Submit('create', 'Create!', css_class="btn-primary"),
        )
    )

I found many questions similar to this but none of them helped me and my requirement is also little different as user is not editing his/her profile but administrator is editing profile of any user.

Just for your information:

where 11 is the user id

Thanks in advance, let me know if you need any further information.

Was it helpful?

Solution

EDIT:

Here's my final proposed solution (charlesliam also made a reference to this in his comment)

We will subclass AbstractUser to add extra fields to the user. Obviously, there's other ways of doing this, but using AbstractUser should suffice your requirements. You'd have to syncdb for model changes to propagate.

SETTINGS.PY

AUTH_USER_MODEL  = 'app.UserInformation' # Points to our custom User model which we will define in models.py

MODELS.PY

from django.contrib.auth.models import AbstractUser

class UserInformation(AbstractUser):
    # user = models.ForeignKey(User, unique=True) <---- Remove this field
    degree = models.ForeignKey(Degree, null=True, blank=True)
    stakeholder = models.ForeignKey(Stakeholder)
    cell_number = models.CharField(max_length=32, null=True, blank=True)

FORMS.PY

class EditUserForm(forms.ModelForm): #fixed typo. It's forms.ModelForm, not models.ModelForm
    class Meta:
        model = UserInformation

VIEWS.PY

from forms.py import EditUserForm

def edit_user (request, id):
    user = User.objects.get(id=11)
    if request.method == 'POST': #If form has been submitted
        form = EditUserForm(request.POST, instance=user)
        if form.is_valid(): #All good. Validation passed
            form.save()
            return HttpResponseRedirect('/your-view/') # Redirect after POST
    else:
            form = EditUserForm(instance=user) # Unbound form

    return render(request, 'MobiApp/edit_user.html', {'form': form})

edit_user.html

{% load crispy_forms_tags %} 

{% crispy form %}

will give you a pre-populated form with the user instance, which you can edit and POST back.

Now with regards to user authentication, you can check if the currently logged in user is superuser (administrator), and proceed with the form editing logic.

So in your VIEWS.PY:

def edit_user (request, id):
    current_user = request.user
    if current_user.is_superuser:
        ...

Alternatively, you can assign the currently logged-in user to any group and then check if the user is member of that group, then proceed with form editing.

I hope that helps.

REFERENCES:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top