扩展用户模型Django,IntegrityError

时间:2017-08-14 18:00:01

标签: django django-models django-forms

我正在尝试扩展User模型以创建Profile模型。以下代码成功显示了一个表单,其中包含我指定为locationbio的其他字段。但是,当我提交表单时,只有原始的usernamefirst_namelast_nameemailpassword字段存储在{{3}的数据库中},我的自定义字段都没有存储在我添加到管理员的“配置文件”部分中。我也收到以下错误:

IntegrityError at /accounts/register/
NOT NULL constraint failed: accounts_profile.user_id
Request Method: POST
Request URL:    http://127.0.0.1:8000/accounts/register/
Django Version: 1.11.2
Exception Type: IntegrityError
Exception Value:    
NOT NULL constraint failed: accounts_profile.user_id
Exception Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 328
Python Executable:  /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6

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):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

forms.py:

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

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)

    class Meta:
        model = User #model User comes with username, email, first name, last name , pass1 and pass2 fields
        fields = (
            'username',
            'email',
            'first_name',
            'last_name',
            'password1',
            'password2'
        )

    def save(self, commit = True):
        user =  super(RegistrationForm, self).save(commit = False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name =  self.cleaned_data['last_name']
        user.email =  self.cleaned_data['email']


        if commit:
            user.save()

            return user

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('location','bio')

views.py:

from django.shortcuts import render, redirect  
from .forms import RegistrationForm,ProfileForm



def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        profile_form = ProfileForm(request.POST)
        if form.is_valid() and profile_form.is_valid():
            form.save()
            profile_form.save()
            return redirect('login')

    else:
        form = RegistrationForm()
        profile_form = ProfileForm()


    return render(request, 'accounts/register.html', {'form': form, 'profile_form': profile_form})

urls.py:

from django.conf.urls import url
from django.contrib.auth.views import login
from . import views


urlpatterns = [
    # /accounts/
    url(r'^$', views.index, name = 'accounts'),

    # /accounts/register/
    url(r'^register/$',  views.register, name='register'),

    url(r'^login/$', login, {'template_name': 'accounts/login.html'}, name='login'),
]

admin.py:

from django.contrib import admin
from .models import Profile
# Register your models here.

admin.site.register(Profile)
# Register your models here.

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您必须手动设置关系,然后您的视图应如下所示:

    if form.is_valid() and profile_form.is_valid():
        user_object = form.save()
        a = profile_form.save(commit=False)
        a.user = user_object
        a.save()
        return redirect('login')

答案 1 :(得分:0)

您不能一次注册和个人资料POST。因为您的个人资料模型是1to1字段,它属于User,这意味着现有用户可以创建一个用户个人资料。最初用户应该创建他们的注册帐户,而不仅仅是他们可以创建个人资料。