I was trying to show the list of the User's to-do lists using view.html. The error says:
no such column:testapp_todolist.user_id".
But I don't understand where this column is and how it is related to the red line in my view.html:
{% for td in user.todolist.all %}
Can you please explain in details how do I add this column?
Here's my models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ToDoList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="todolist", default=0)
name = models.CharField(max_length=200)
def __str__(self):
return self.name
class Item(models.Model):
todolist = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
complete = models.BooleanField()
def __str__(self):
return self.text
Try solving this by writing this on your console:
python manage.py makemigrations
python manage.py migrate
Those commands are going to create tables for the TodoList model in the database.
user does not have the object todolist, todolist is a foreign key in Item. You should do:
list = ToDoList.objects.filter(user=YOUR_USER_HERE)
or
# if you want to get the todolist of the currently logged in user
list = ToDoList.objects.filter(user=request.user)
Related
I have created two classes in models.py in my application.
models.py
from django.db import models
# Create your models here.
class User(models.Model):
first_name = models.CharField(max_length=264, unique=True)
last_name = models.CharField(max_length=264, unique=True)
email = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.first_name
class NewUser(models.Model):
categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
area = models.CharField(max_length=264)
def __str__(self):
return self.name
as shown in my image my (User and New users)tables are created.
data is getting added to my (User) table.
But when I try to add data to my (New users) table
I get this error
Since you don't have any custom fields in your User model, you dont need to create a seperate User class, only you have to import the built in User class.
from django.contrib.auth.models import User
class NewUser(models.Model):
categorie = models.ForeignKey('User',on_delete=models.DO_NOTHING)
area = models.CharField(max_length=264)
def __str__(self):
return self.categorie.user.username
You can still get username, first_name, last_name, email etc from the default user class. Refer: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.models.User
Most likely you haven't migrated properly. Try:
python manage.py makemigrations
python manage.py migrate
The models show up in the admin because they are present in the apps models.py. This is not related to the database!
I have made changes to one of my models in my project and migrate, makemigrations does not work as expected. Rebuilding the database creates only 2 out of 3 tables from my models.py and i cannot figure out the problem.
There are two different apps; "blog" and "users". both are registered in the setting.py.
I completely removed the database and deleted the migrations folders.
then i tried the following stuff:
django makemigrations blog
django migrate blog
doing a global django makemigrations does not have any effect, no changes are detected.
here is the relevant models.py of "blog":
class Room(models.Model):
roomname = models.CharField(max_length=6, unique=True)
roomeditors=models.ManyToManyField(User,related_name='rooms_user_can_edit', blank=True)
displayadmin=models.ForeignKey(User,
related_name='room_user_is_displayadmin',null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.roomname
class Post(models.Model):
title = models.CharField(max_length=40)
content = models.TextField(max_length=300)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
rooms = models.ManyToManyField(Room, related_name='roomposts', through='Display')
def __str__(self):
return self.title
def get_absolute_url(self):
return "/post/{}/".format(self.pk)
class Display(models.Model):
class Meta:
auto_created = True
post = models.ForeignKey(Post, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
isdisplayed = models.BooleanField(default=0)
def __str__(self):
return str(self.isdisplayed)
every table gets created except from display. the output is:
Migrations for 'blog':
blog\migrations\0001_initial.py
- Create model Room
- Create model Post
You are giving auto_created = True in your model's Meta class, which is not recommended neither its documented. Here is the list of all possible meta options you can give inside your model.
Official documentation says:
auto_created: Boolean flag that indicates if the field was automatically created, such as the OneToOneField used by model inheritance.
Giving this in Meta refrains Django to create this model itself.
This is the model I am working with:
from django.db import models
from django.conf import settings
from products.models import Variation
class CartItem(models.Model):
cart = models.ForeignKey('Cart')
items = models.ForeignKey(Variation)
quantity = models.PositiveIntegerField(default=1)
def __unicode__(self):
return self.items.title
class Cart(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
items = models.ManyToManyField(Variation, through='CartItem')
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
def __unicode__(self):
return (str(self.id))
I had run makemigrations and migrate once before, with the items field in the model Cart being items = models.ManyToManyField(CartItem)
Now after making this change, I get the following error:
ValueError: Cannot alter field carts.Cart.items into carts.Cart.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
How do I fix this ? Please help.
Like the error says, you can't convert a many-to-many into a foreign key. You'll have to split this into two migrations: first, remove the original field completely and run makemigrations to create the DROP COLUMN call; then, add the foreign key and run makemigrations again to create the ADD COLUMN.
I am working on a django admin based project now i am stuck with a big thing.i want to add a field named "item_issued" in the user_profile model.
in the "item issued" field there is a table which consist of 3 column "item_name","quantity" and "price".I am unable to apply this.Can u guys please help me in this?
Thanks in advance
If I understand you correctly you want to add a ForeignKey to your user_profile pointing to item_issued. You can accomplish that by creating a new model ItemIssued with the fields you mentioned:
class ItemIssued(models.Model):
item_name = models.CharField(max_length=100)
quantity = models.IntegerField()
price = models.FloatField()
Now, when you're having ItemIssued model you can add a ForeignKey to user_profile (I assume the model is called UserProfile):
class UserProfile(models.Model):
... # your existing fields
item_issued = models.ForeignKey(ItemIssued)
After that, don't forget to run
python manage.py makemigrations app
python manage.py migrate
Here is a starting point:
models.py:
class ItemIssued(models.Model):
item_name = models.CharField(max_length=50)
quantity = models.IntegerField()
models.DecimalField(max_digits=6, decimal_places=2) #use decimal field for price values.
class UserProfile(models.Model):
# some other fields..
issued_items = models.ManyToManyField("ItemIssued", related_name="+issued_items", null=True, blank=True)
And if you need to use this field outside of Django Admin, views.py:
user = UserProfile.objects.get(username="ali")
new_issued_item = ItemIssued.objects.get(item_name="test_item")
user.issued_items.add(new_issued_item) #add
user.issued_items.delete(new_issued_item) #delete
items = user.issued_items.all() # get all issued items of user
i didn't test the code. But they should work.
I've added a ManyToManyField to my app. Every restaurant can fall under many categories, and each category can be applied to many restaurants. The app has been working and running, and my models look like this:
class Category(models.Model):
class Meta:
verbose_name_plural = "categories"
title = models.CharField(max_length=100)
def __unicode__(self):
return self.title
class RestaurantInfo(models.Model):
name = models.CharField(max_length=100)
aboutUs = models.TextField(max_length=10000)
founded = models.DateField()
categories = models.ManyToManyField(Category)
def __unicode__(self):
return self.name
The ManyToManyFied is what is new. However, make migrations finds no changes to make.
Looks like you are not supplying app_name to makemigrations command.
python manage.py makemigrations app_name
If you won't supply app_name, Django won't detect changes made to your models.