“ user_id”列中的null值违反了非null约束DETAIL:

时间:2019-03-19 12:59:09

标签: python django

出现错误,但正在保存用户注册表数据,但未保存loyerform数据。

这是我得到的错误:- “ user_id”列中的空值违反了非空约束 详细信息:失败行包含(18,asda,asdasd,建筑,净工资,否,基于年龄,每季度,每半年,每年,空)

Models.py

APP_NAME=Mywebsite
APP_ENV=local
APP_KEY=
APP_DEBUG=false
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testdb
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=mailgun 
MAIL_HOST=smtp.eu.mailgun.org
MAIL_PORT=2525
MAIL_USERNAME=
MAIL_PASSWORD=

MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=

MAILGUN_DOMAIN=
MAILGUN_SECRET=
MAILGUN_ENDPOINT=

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

MAILCHIMP_LIST_ID=
MAILCHIMP_APIKEY=

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

views.py

class EmployerUser(models.Model):
    id                              = models.AutoField(primary_key=True)
    user                            = models.ForeignKey(User,on_delete=models.CASCADE)
    company_name                    = models.CharField(max_length=20,default="")
    address                         = models.TextField(default="")
    industry                        = models.CharField(choices=INDUSTRY,max_length=20,default="")
    isSalarySacrifies               = models.CharField(max_length=20,choices=SALARYSACRIFIES,default=False)
    isNetpayRelief                  = models.CharField(max_length=20,choices=NETPAY,default=False)
    contribution_type               = models.CharField(choices=CONTRI_TYPE,max_length=20,default="")
    contribution_change_type        = models.CharField(choices=CONTRI_CHANGE_TYPE,max_length=20,default="")
    payrise_type                    = models.CharField(choices=PAYRISE,max_length=20,default="")
    bonus_type                      = models.CharField(choices=BONUS,max_length=20,default="")

    def __str__(self):
        return self.company_name

EmployerUserForm

def register_view(request):
next = request.GET.get('next')
form             = UserRegisterForm(request.POST or None)
profileform      = EmployerUserForm(request.POST or None)

if form.is_valid() and profileform.is_valid():
    user = form.save(commit=False)
    profile = profileform.save(commit=False)
    password = form.cleaned_data.get('password')
    user.set_password(password)
    user.save()
    profile.save()
    new_user = authenticate(email=user.email, password=password)

    login(request, new_user)
    if next:
        return redirect(next)
    return redirect('login')

context = {
    'form': form,
    'profileform': profileform,
}
return render(request, "registration/signup.html", context)

1 个答案:

答案 0 :(得分:1)

您似乎需要为员工设置用户:

profile = profileform.save(commit=False)
profile.user = user
profile.save()