在不使用django admin的情况下编辑用户配置文件表单

时间:2014-03-23 19:49:56

标签: python-3.x django-1.6

我正在开发一个简单的LMS系统,我有3个利益相关者管理员,教师和学生。管理员可以创建,编辑,删除,阻止和列出用户帐户,到目前为止,我可以创建并列出所有用户。

现在我被困在编辑用户个人资料,我的要求是,当我点击任何列出的用户时,它应该在表单中打开我的扩展/自定义用户配置文件,我应该能够编辑任何打开的用户配置文件。

以下是我的代码段:

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(创建用户):

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(创建用户):

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"),
        )
    )

我发现了许多与此相似的问题,但没有一个问题对我有帮助,因为用户没有编辑他/她的个人资料但管理员正在编辑任何用户的个人资料,我的要求也没什么不同。

仅供参考:

其中11是用户ID

在此先感谢您,如果您需要任何进一步的信息,请与我们联系。

1 个答案:

答案 0 :(得分:0)

编辑:

这是我最后提出的解决方案(charlesliam也在他的评论中提到了这一点)

我们将子类AbstractUser添加到用户的额外字段。显然,还有其他方法可以做到这一点,但使用AbstractUser应该满足您的要求。您必须syncdb才能传播模型更改。

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 %}

将为您提供一个预先填充的表单,其中包含用户实例,您可以对其进行编辑和POST。

现在关于用户身份验证,您可以检查当前登录的用户是否是超级用户(管理员),然后继续使用表单编辑逻辑。

所以在你的 VIEWS.PY

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

或者,您可以将当前登录的用户分配给任何组,然后检查该用户是否是该组的成员,然后继续进行表单编辑。

我希望有所帮助。

参考文献: