I'm stuck for 2 days on this error,I'm new to Django and I am trying to write reviews for books.When I open the review form and type some text and after that submit it, I get this error -
OperationalError at /books/add_review_to_book/8
table books_review has no column named book_id.
Everything looks okay for me heres the code:
My models.py
class Book(models.Model):
user = models.ForeignKey(User, default=1)
title = models.CharField(max_length=100, null=True)
author = models.ForeignKey('Author', on_delete=models.CASCADE, null=True)
def __str__(self):
return self.title + ' - ' + self.author
class Author(models.Model):
first_name = models.CharField(max_length=50, null=True)
last_name = models.CharField(max_length=50, null=True)
class Review(models.Model):
book = models.ForeignKey('Book', related_name='reviews')
author = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.text
My views.py:
def add_review_to_book(request, id):
book = get_object_or_404(Book, id=id)
if request.method == "POST":
form = ReviewsForm(request.POST)
if form.is_valid():
review = form.save(commit=False)
review.book = book
review.save()
return redirect('book_detail.html', id=book.id)
else:
form = ReviewsForm()
return render(request, 'books/add_review_to_book.html', {'form': form})
My forms.py:
class ReviewsForm(forms.ModelForm):
class Meta:
model = Review
fields = ('author', 'text')
My html that takes the form add_review_to_book:
{% block content %}
<hr>
<a class="btn btn-default" href="{% url 'add_review_to_book' id=book.id %}">Add review</a>
{% for review in book.reviews.all %}
{% if user.is_authenticated %}
<div class="review">
<div class="date">
{{ review.created_date }}
</div>
<strong>{{ review.author }}</strong>
<p>{{ review.text|linebreaks }}</p>
</div>
{% endif %}
{% empty %}
<p>No comments</p>
{% endfor %}
{% endblock content %}
I deleted migrations and made them again, I still get the same error when I try to write a review. Thanks in advance.
Edit: Result after running .schema books_review in dbshell -
CREATE TABLE IF NOT EXISTS "books_review" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "text" text NOT NULL);
Still table books_review has no column named book_id
:(
as i can see, you have no two fields
book
andauthor
, possible you broke migrations, try to do next steps:./manage.py dumpdata auth.user > users.json
./manage.py dumpdata books.book > book.json
rm db.sqlite3
rm -rf books/migrations
mkdir books/migrations
touch books\migrations\__init__.py
./manage.py makemigrations
./manage.py migrate
./manage.py loaddata *.json
hope it help you