Django在提交注册时创建用户个人资料

时间:2017-04-22 10:09:54

标签: python django django-models django-forms django-views

我正在django上工作基于角色的访问控制系统。在注册/注册时,人们将被指定为“部门”,并将被分配一个“角色”因此我创建了一个自定义用户模型

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


 class Profile(models.Model):

 DEPARTMENT_CHOICES = (
    ('Production', 'Production'),
    ('Marketing', 'Marketing'),
    ('IT', 'IT'),
    ('HR', 'HR'),
    ('Accounts', 'Accounts'),
)
ROLE_CHOICES = (
    ('Manager', 'Manager'),
    ('Team Lead', 'Team Lead'),
    ('Member', 'Member'),
)

user = models.OneToOneField(
    User,)
department = models.CharField(
    max_length=50, choices=DEPARTMENT_CHOICES, null=True)
role = models.CharField(max_length=50, choices=ROLE_CHOICES, null=True)

def __unicode__(self):
    return unicode(self.user.first_name + ' ' + self.user.last_name)

def __str__(self):
    return self.user.first_name + ' ' + self.user.last_name


def create_profile(sender, **kwargs):
    if kwargs['created']:
    user_profile = Profile.objects.create(user=kwargs['instance'])
    pass

post_save.connect(create_profile, sender=User)

然后我创建了一个像

这样的表单

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Profile


class SignUpForm(UserCreationForm):
DEPARTMENT_CHOICES = (
    ('Production', 'Production'),
    ('Marketing', 'Marketing'),
    ('IT', 'IT'),
    ('HR', 'HR'),
    ('Accounts', 'Accounts'),
)
ROLE_CHOICES = (
    ('Manager', 'Manager'),
    ('Team Lead', 'Team Lead'),
    ('Member', 'Member'),
)
first_name = forms.CharField(
    max_length=30, required=True, help_text='Optional.')
last_name = forms.CharField(
    max_length=30, required=True, help_text='Optional.')
email = forms.EmailField(
    max_length=254, required=False)
department = forms.ChoiceField(choices=DEPARTMENT_CHOICES, )
role = forms.ChoiceField(choices=ROLE_CHOICES, )

class Meta:
    model = User
    fields = ('first_name', 'last_name', 'username',
              'email', 'password1', 'password2', 'department', 'role')

我的观点

from django.shortcuts import render, redirect, render_to_response
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login, authenticate
from .forms import SignUpForm
from .models import Profile
from django.shortcuts import get_object_or_404
from django.http import Http404
from django.contrib.auth.models import User
from django.template import RequestContext

def register(request):
if request.user.is_authenticated:
    if request.user.is_superuser or request.user.role == 'Manager':
        if request.method == 'POST':
            form = SignUpForm(request.POST)
            if form.is_valid():
                user = form.save()
                userprofile = Profile.objects.update(
                    user=user, department=form.cleaned_data['department'])
                userprofile = Profile.objects.update(
                    user=user, role=form.cleaned_data['role'])
        else:
            form = SignUpForm()

        c = {
            'form': form,
        }

        return render(request, 'registration/register.html', c)
    else:
        raise Http404
else:
    raise Http404

我的register.html

{% extends 'layouts/base.html' %} {% load widget_tweaks %}{% block additionalbottom %}
<script>
var allParas = document.getElementsByTagName('div');
//filter by class name if desired...
for (var i = 0; i < allParas.length; i++) {
    if (allParas[i].getElementsByTagName('*').length == 0) {
        allParas[i].style.display = 'none';
    }
}
</script>
{% endblock %} {% block content %}
<div class="login-page">
    <div class="form">
        <h2>User Registration</h2>
        <form class="login-form" method="post">
            {% csrf_token %}
            <div class="row">
                {% endblock %} {% for field in form %}
                <div class="col-md-6">
                    {% if field.name == "first_name" or field.name == "last_name" %} {% render_field field class="form-control" placeholder=field.label.capitalize %} {% endif %}
                </div>
                <div class="col-md-6">
                    {% if field.name == "username" or field.name == "email" %} {% render_field field class="form-control" placeholder=field.label.capitalize %} {% endif %}
                </div>
                <div class="col-md-6 form-group">
                    {% if field.name == "department" or field.name == "role" %} {% render_field field class="form-control" placeholder=field.label.capitalize %} {% endif %}
            </div>
            <div class="col-md-12">
                {% if field.name == "password1" %} {% render_field field class="form-control" placeholder=field.label.capitalize %} {% endif %}
            </div>
            <div class="col-md-12">
                {% if field.name == "password2" %} {% render_field field class="form-control" placeholder=field.label.capitalize %} {% endif %}
            </div>
            {% endfor %}
        </div>
        <div class="form-group">
            <button type="submit">Register</button>
        </div>
    </form>
    {% if form.errors %} {% for field in form %} {% for error in field.errors %}
    <div class="alert alert-danger">
        <strong>{{ error|escape }}</strong>
    </div>
    {% endfor %} {% endfor %} {% for error in form.non_field_errors %}
    <div class="alert alert-danger">
        <strong>{{ error|escape }}</strong>
    </div>
    {% endfor %} {% endif %}
</div>

现在,当我尝试提交表单时,它说

  

/ register /中的IntegrityError   列user_id不是唯一的

我尝试了谷歌的这么多解决方案似乎无法解决问题任何人都可以告诉我如何解决它或者为什么不能做到如果它无法完成什么是解决方法

2 个答案:

答案 0 :(得分:0)

这是你的问题。

Profile.objects.update(user=user, department=form.cleaned_data['department'])

这将尝试使用相同的数据更新所有配置文件。如果您有多个配置文件,那是不允许的,因为用户是一对一的关系。

我想你想要做的是创建一个新的配置文件对象。尝试这样的事情:

Profile.objects.create(
    user=user,
    department=form.cleaned_data['department'], 
    role=form.cleaned_data['role'],
)

如果您在保存新用户时使用信号创建个人资料,则可以改为使用update_or_create

Profile.objects.update_or_create(
    user=user,
    defaults={
        "department": form.cleaned_data['department'], 
        "role": form.cleaned_data['role'],
    }
)

答案 1 :(得分:0)

这篇文章对我有很大帮助。对我来说,我的问题是我曾经使用过:

current_user = request.user 应该是什么时候: current_user = form.save()