Not null constraint failed ошибка

I keep getting this error: «NOT NULL constraint failed: users_userprofile.user_id» when I try to submit a form

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    #Esta linea es requerira. Linkea UserProfile a un User model
    user = models.OneToOneField(User)

    #atributos adicionales
    about_me = models.TextField(max_length=100,default='',blank=True)
    experience = models.TextField(max_length=250,default='',blank=True)
    offers = models.TextField(max_length=110,default='',blank=True)

This is the forms.py:
from django import forms
from users.models import UserProfile
from django.contrib.auth.models import User

class UserForm(forms.ModelForm):
    password = forms.CharField(min_length=6,label='', widget=forms.PasswordInput(attrs={'placeholder': 'Password','required':'true','class':"form-control"}))
    username = forms.CharField(label='', min_length=6,
                    widget=forms.TextInput(attrs={'placeholder': 'Username','required':'true','class':"form-control",'autofocus':'true'}))
    email = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Email','required':'true','class':"form-control"}))

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

class UserProfileForm(forms.ModelForm):
    about_me = forms.CharField(label='', 
                    widget=forms.Textarea(attrs={'placeholder': 'Sobre mi','required':'true','class':"form-control"}))
    first_name = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Nombre','required':'true','class':"form-control"}))
    last_name = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Apellidos','required':'true','class':"form-control"}))
    experience = forms.CharField(label='', 
                    widget=forms.TextInput(attrs={'placeholder': 'Experiencia','required':'true','class':"form-control"}))
    offers = forms.CharField(label='', 
                    widget=forms.Textarea(attrs={'placeholder': 'Mensaje','required':'true','class':"form-control"}))

    class Meta:
        model = UserProfile
        fields =('first_name','last_name','about_me','experience','offers')

This is the template:

{%extends 'base.html'%}

{%block content%}
{% if user.is_authenticated %}
<h1>Edita tu perfil</h1>
<form id='profile' method='post' action='/edit_profile/'>
{% csrf_token %}

{{profile.as_p}}

<button type='submit'>Editar</button>
</form>
{%endif%}

{%endblock%}

Thanks before hand

EDIT:

The error was in the views.py I needed to add an instance to the form, like this:

form = UserProfileForm(data=request.POST, instance=profile)

This is my complete views.py:

def edit_profile(request):
    try:
        profile = request.user.userprofile

    except UserProfile.DoesNotExist:

        profile = UserProfile(user=request.user)

    if request.method == 'POST':
        form = UserProfileForm(data=request.POST, instance=profile)

        if form.is_valid():

            form.save()

            return HttpResponse("Exito!")
        else:
            form = UserProfileForm(instance=profile)

    else:
        form = UserProfileForm()

    return render(request,
            'editprof.html',
            { 'form': form})

from RXConfigBase import bot, logger
from RXSQLConfig import sqlite3, user_id, name, surname, patronymic


#Начало, логиниться и регистрация
@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.from_user.id,  'Добро пожаловать!n' f'‍♂️>> {message.chat.first_name}|{message.chat.last_name} <<‍♀️nn' 'Входа в систему /logn' 'Регистрация /reg')

#Регистрация
@bot.message_handler(commands=['reg'])
def start_message(message):
    bot.send_message(message.from_user.id, 'Регистрацию аккаунта.nНачнём?(Напиши "next")')
    bot.register_next_step_handler(message, name)

#Собираем данные для регистрации и БД
def name(message): #получаем имя
    bot.send_message(message.from_user.id, 'Укажите имя')
    global name
    global user_id
    user_id = message.from_user.id
    name = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (user_id, name) VALUES (?, ?)", (user_id, name, ))
    #cursor.execute(f"SELECT get_user_id FROM Profile WHERE id = {message.from_user.id}")
    #cursor.execute(f"SELECT get_name FROM Profile WHERE id = {message.text}")
    bot.register_next_step_handler(message, surname)

def surname(message): #получаем фамилии
    bot.send_message(message.from_user.id, 'Укажите фамилию')
    global surname
    surname = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (surname) VALUES (?)", (surname, ))
    bot.register_next_step_handler(message, patronymic)

def patronymic(message): #получаем отчества
    bot.send_message(message.from_user.id, 'Укажите отчество')
    global patronymic
    patronymic = message.text
    conn = sqlite3.connect("DataBase/RXDataBase.db")
    cursor = conn.cursor()
    cursor.execute("INSERT INTO Profile (patronymic) VALUES (?)", (patronymic, ))
    return




if __name__ == '__main__':
    bot.polling(none_stop=True, interval=0)

Ошибка:
cursor.execute(«INSERT INTO Profile (user_id, name) VALUES (?, ?)», (user_id, name))
sqlite3.IntegrityError: NOT NULL constraint failed: Profile.surname

Django Forum

Loading

Hello,

We are struggling for this almost whole day and we don’t see where is the problem. Everything seems good but we realized that somehow after second connection to database and calling different queries we loose PRIMARY KEY at files table.

Here is what we have and what we call to get error Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

user.entity.ts

import { Entity } from 'typeorm/decorator/entity/Entity';
import {Column, OneToMany, PrimaryGeneratedColumn} from 'typeorm';
import {Sources} from './sources.entity';

@Entity()
export class Users {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column("varchar", { nullable: true})
  email: string;

  @OneToMany(type => Sources, source => source.user, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources[];
}

source_type.entity.ts


import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { Sources } from './sources.entity';

@Entity()
export class SourceType {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => Sources, sourcesType => sourcesType.sourceType, {
    cascadeInsert: true,
    cascadeUpdate: true,
    cascadeRemove: true
  })
  source: Sources;
}

sources.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import {Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn} from 'typeorm';
import { SourceType } from './source_type.entity';
import { Users } from './user.entity';
import {SourcesPaths} from "./sources_paths.entity";
import {Files} from "./files.entity";

@Entity()
export class Sources {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @OneToOne(type => SourceType)
  @JoinColumn()
  sourceType: SourceType;

  @ManyToOne(type => Users, users => users.source)
  @JoinColumn()
  user: Users;

  @OneToMany(type => SourcesPaths, sourcesPaths => sourcesPaths.source)
  sourcePath: SourcesPaths[];

  @OneToMany(type => Files, file => file.source)
  file: Files[];

}

files.entity.ts

import {Entity} from 'typeorm/decorator/entity/Entity';
import { Column, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn } from 'typeorm';
import {Sources} from './sources.entity';
import {FilesTags} from './files_tags.entity';

@Entity()
export class Files {

  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar', {length: 45})
  name: string;

  @Column('varchar', {length: 45, nullable: true})
  family_name: string;

  @Column('varchar', {length: 45, nullable: true})
  created_at: string;

  @ManyToOne(type => Sources, source => source.file)
  @JoinColumn()
  source: Sources;

  @OneToMany(type => FilesTags, fileTag => fileTag.file)
  fileTag: FilesTags[];
}

insertUser function
When we call insert function for the first time everything goes well. Data is inserted including data into files entity also. But on second call to insertUser() we are getting error
Error: SQLITE_CONSTRAINT: NOT NULL constraint failed: files.id

In SQLite studio we saw that after first insert of files we loose primary key on files.id.
Are we doing something wrong or there is an issue in typeorm?

insertUser(): void {

    createConnection({

      type: 'sqlite',
      database: '../user.sqlite',
      entities: [
        Users,
        Sources,
        SourceType,
        Files
      ],
      autoSchemaSync: true,
    }).then( async connection => {

      // Here you can start to work with your entities
      const user = new Users();
      user.name = 'Mezenga1234';

     await connection.manager.save(user);

      const sourcetype = new SourceType();
      sourcetype.name = 'my_library';
     await connection.manager.save(sourcetype);

      const source = new Sources();
      source.name = 'my_source';
      source.sourceType = sourcetype;
      source.user = user;

     await connection.manager.save(source);

      const files = new Files();
      files.name = 'Haris.rvt';
      files.source = source;

      await connection.manager.save(files);

      console.log('Inserted');
      connection.close();

    }).catch(error => console.log(error));

  }

При загрузке получаю ошибку

Я так понимаю модели не хватает id пользователя, но где его не хватает, не могу понять. Django вроде делает всю работу за меня))

IntegrityError at /upload/
NOT NULL constraint failed: blog_post.author_id

Обработчик загрузки (views.py)

def model_form_upload(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            # file is saved
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = PostForm()
    return render(request, 'upload.html', {'form': form})

Модель (models.py)

SCRIPT_TYPE = (
    ('SINGLE', 'SINGLE'),
    ('MULTI', 'MULTI'),
)


class Post(models.Model):
    author = models.ForeignKey('auth.User', null=False, verbose_name="Автор", )
    title = models.CharField(max_length=200, null=False, verbose_name="Заголовок", )
    type = models.CharField(max_length=10, choices=SCRIPT_TYPE, default='MULTI', null=False, verbose_name="Тип", )
    text = models.TextField(null=True, verbose_name="Описание", )
    published_date = models.DateTimeField(blank=True, null=True, verbose_name="Дата создания", )
    script = models.FileField(null=False, blank=True, upload_to="scripts/", verbose_name="Скрипт", )

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

HTML файл

{% load staticfiles %}
<html>
<head>
    <title>Django blog</title>
    <link href="https://fonts.googleapis.com/css?family=Lobster&subset=latin,cyrillic" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="{% static 'css/main_window.css' %}">

</head>
<body>
<h1>New post</h1>

<form method="post" class="post-form" enctype="multipart/form-data" action="/upload/">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="save btn btn-default">Save</button>
</form>

</body>
</html>

Понравилась статья? Поделить с друзьями:
  • Not mpisp mode 1b ssd ошибка
  • Not isp mode 7b ошибка
  • Not in index python ошибка
  • Not in gzip format ошибка linux
  • Not in a hypervisor partition virtualbox ошибка