Django auth.models用户一对多(1048,“列'user_id'不能为空”)

时间:2017-06-28 18:30:29

标签: python mysql django

我是django的新手,我的任务是让用户在注册后能够在注册后创建很多个人资料。

这是我的models.py:

class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(blank=False, max_length=100)
    lastname = models.CharField( blank=False, max_length=100)
    city = models.CharField( blank=True, max_length=100)
    country = models.CharField( blank=True, max_length=100)
    phonenumber = models.CharField(blank=False, null=True, max_length=20)
    email = models.EmailField(blank=False, max_length=100)
    date_of_birth = models.DateField( blank=True, null=True)
    date_of_addition = models.DateField(auto_now=True, editable=False, null=True)

当我创建用户时,请登录并按下创建个人资料按钮我得到: django.db.utils.IntegrityError:(1048,“列'user_id'不能为空”)

这是我的views.py:

    @login_required
def profile_create(request):
    data = dict()
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            form.save()
            data['form_is_valid'] = True
            profiles = Profile.objects.all()
            data['html_profile_list'] = render_to_string('basic_app/users_list_1_10.html', {'profiles': profiles})
        else:
            data['form_is_valid'] = False
    else:
        form = ProfileForm()
    context = {'form': form}
    data['html_form'] = render_to_string('basic_app/partial_profile_create.html', context, request=request)
    return JsonResponse(data)


def register(request):
    registered = False
    if request.method == "POST":
        user_form = UserForm(data=request.POST)
        if user_form.is_valid():
            user = user_form.save()
            user.set_password(user.password)
            user.save()
            registered = True
        else:
            print(user_form.errors)
    else:
        user_form = UserForm()
    return render(request,'basic_app/registration.html',{'user_form':user_form,'registered':registered})

这是我的forms.py:

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

class ProfileForm(ModelForm):
    class Meta:
        model = Profile
        fields = ('name', 'lastname', 'city', 'country', 'phonenumber', 'email', 'date_of_birth')


class UserForm(ModelForm):
    password = forms.CharField(widget=forms.PasswordInput())
    username = forms.CharField(help_text=False)

    class Meta():
        model = User
        fields = ('username','password')

由于

2 个答案:

答案 0 :(得分:0)

这是因为在您的Profile模型中,您有user字段ForeignKey。在Django中,默认情况下需要ForeignKey,这意味着如果不指定Profile字段,则无法创建新的user。但是您没有在ProfileForm中提供用户。

您可以在ProfileForm中提供用户,也可以通过添加以下内容将user字段设置为不需要:

user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)

答案 1 :(得分:0)

我应该在保存ProfileForm之前请求用户:

@login_required
def profile_create(request):
    data = dict()

    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            add = form.save(commit=False)
            add.user = request.user
            add.save()
            data['form_is_valid'] = True
            profiles = Profile.objects.all()
            data['html_profile_list'] = render_to_string('basic_app/users_list_1_10.html', {'profiles': profiles})
        else:
            data['form_is_valid'] = False
    else:
        form = ProfileForm()

    context = {'form': form}
    data['html_form'] = render_to_string('basic_app/partial_profile_create.html', context, request=request)
    return JsonResponse(data)