2017-01-14 2 views
0

У меня есть следующий вид, который работает отлично:Джанго -> Исключение Значение: (1048, «Колонка„user_id“не может быть пустым»)

@transaction.atomic 
def register(request): 
    next_url = request.POST.get('next', request.GET.get('next', reverse('profile'))) 
    if request.method == 'POST': 
     form = RegistrationForm(request.POST) 
     profileform = ProfileForm(request.POST) 
     if form.is_valid() and profileform.is_valid(): 
      new_user = form.save() 

      # Login the newly created user. 
      authenticated_user = authenticate(username=new_user.username, 
               password=form.cleaned_data['password1']) 
      login(request, authenticated_user) 
      return redirect(next_url) 
    else: 
     form = RegistrationForm() 
     profileform = ProfileForm() 
    return render(request, 'meta/register.html', {'form': form, 'profileform': profileform, 'next': next_url}) 

Однако, когда я желаю, чтобы сохранить дополнительную информацию о профиле использования следующая строка (помещенных ниже линии new_user = form.save()):

new_user_profile = profileform.save() 

я получаю следующую ошибку:

Exception Type: IntegrityError 
Exception Value: (1048, "Column 'user_id' cannot be null") 

Моя модель для профиля выглядит следующим образом:

class Profile(models.Model): 
    user = models.OneToOneField(User) 
    dob = models.DateField(max_length=8) 

    class Meta: 
     managed = True 
     db_table = 'fbf_profile' 

Любая помощь будет большим, Алан.

ответ

3

При работе с внешними ключами, как это, вы обычно видите сохранение с commit=False, а затем вручную устанавливаете внешние ключи на модели. например,

new_user = form.save() 
profile = profileform.save(commit=False) 
if profile.user_id is None: 
    profile.user_id = new_user.id 
profile.save() 

This save() method accepts an optional commit keyword argument, which accepts either True or False . If you call save() with commit=False , then it will return an object that hasn’t yet been saved to the database. In this case, it’s up to you to call save() on the resulting model instance. This is useful if you want to do custom processing on the object before saving it, or if you want to use one of the specialized model saving options. commit is True by default.

+0

Спасибо за объяснение наряду с ответом. Помогает старому банку знаний. –

0

По-видимому, поле user не установлено в ProfileForm. Модель Profile нуждается в user_id для userOneToOneField.

ProfileForm потребуется user поле, которое вы должны установить, или вам придется вручную установить user поле в save() функции ProfileForm (которые вы затем должны переопределить).