Django - Error saving to Database

Asked

Viewed 1,489 times

2

The data is not being saved in the database and Django is not generating Error, but when I create an object of Livro and try to save by shell it returns me the following error:

Valueerror: invalid literal for int() with base 10:

I tried to look for solutions but without success! I am using sqlite3! Django 1.6.2 and python 2.7! The project is available on github.

Models py.:

class Biblioteca(models.Model):

    endereco = models.CharField(max_length = 80)
    nome = models.CharField(max_length = 60)
    telefone = models.IntegerField(max_length = 11)

    def __unicode__(self):
        return self.nome

class Livro(models.Model):
    codigo = models.CharField(max_length = 10)
    publicacao = models.IntegerField()
    autor = models.CharField(max_length = 80)
    editora = models.CharField(max_length = 45)
    genero = models.CharField(max_length = 45)
    sinopse = models.CharField(max_length=150)
    titulo = models.CharField(max_length = 150)
    biblioteca = models.ForeignKey(Biblioteca)

    def __unicode__(self):
        return (self.titulo, self.autor)

Forms py.:

class FormLivro(forms.Form):

    codigo = forms.CharField(max_length=10)
    publicacao = forms.IntegerField()
    autor = forms.CharField(max_length=80)
    editora = forms.CharField(max_length=45)
    genero = forms.CharField(max_length=45)
    sinopse = forms.CharField(max_length=150)
    titulo = forms.CharField(max_length=150)

def save(self):

    codigo = self.cleaned_data.get('codigo')# Acessando os Fields
    publicacao = self.cleaned_data.get('publicacao')         
    autor = self.cleaned_data.get('autor')
    editora = self.cleaned_data.get('editora')
    genero = self.cleaned_data.get('genero')
    sinopse = self.cleaned_data.get('sinopse')
    titulo = self.cleaned_data.get('titulo')

    novo_livro = Livro(
        codigo = codigo,
        publicacao = publicacao,
        autor = autor,
        editora = editora,
        genero = genero,
        sinopse = sinopse,
        titulo = titulo
    )
    novo_livro.save()
    return novo_livro 

def clean_codigo(self):
    codigo = self.cleaned_data.get('codigo')
    if Livro.object.filter(email = email):
        raise forms.ValidationError('Codigo já cadastrado!')
    return codigo

Views.py:

def cadLivro(request):

    livros = Livro.objects.all() # Lista de livros
    if request.method == "POST":
        form = FormLivro(request.POST)
        if form.is_valid(): # Processando o Formulario
            novo_livro = form.save()
            HttpResponseRedirect(reverse('nCadLivro'))
    else:
        form = FormLivro()

    return render(request, 'cadastro_livro.html')

1 answer

1


Your code on Github is different from the question code. On the template Livro, the field codigo is as IntegerField instead of CharField. For this reason, the error mentioned when trying to save the Livro shell. But using a numeric value in this field, it saves normally (either using an integer, or a string representing an integer in base 10).

I also tried testing from the view, but it doesn’t even compile, so I suggest solving this (and others) problem if you need help with that as well. And always remember to check that the database is consistent with the models - because if you modify some field in the model, run syncdb again will not do anything, it is necessary to destroy your table and create it again (for example using reset; caring for: this erases all data from the table). Soon, Django will support schema migration, but at the moment this is not done natively (only by external libraries such as South).

P.S. Your Method __unicode__ does not work as it returns a tuple instead of a string. I suggest changing it to (for example):

def __unicode__(self):
    return unicode((self.titulo, self.autor))
  • I made the corrections and updated in Github, now it is returning: Integrityerror at /cadLivro/ library_livro.biblioteca_id may not be NULL Note: I already have a Library table created in the Database

  • 1

    @Snickers As for this, the problem is that when you create a new Livro in the forms.py you do not assign the reference to a Biblioteca, or a library ID (after all, a Livro belongs to a Biblioteca). If you want books to exist without a library, put the foreign key as nullable (biblioteca = models.ForeignKey(Biblioteca, null=True, blank=True, default=None)). Otherwise, include an option in your form for the user to choose a library. P.S. Just warning, your views.py says he’s in utf-8 in the header, but it’s actually in Windows-1252 / Cp1252.

  • 1

    I understand, as for the relationship Library -> Book. I really was in doubt when creating models because I can say that a Book belongs to a Library (Onetoone), but tbm can also say that a Library has several Books (Manytoone / Foreingkey)

  • 1

    "one to one" would mean that the library only has a single book... : P I believe that - depending on the application - it may be "Many to one" (the book is a physical thing, which can only belong to a single library) or "Many to Many" (book X has N copies, each in a different library - perhaps more than one in the same). The way you implemented it is correct pro "Many to one", only remains to decide whether there are "independent" books (i.e. that are not in any library) or not.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.