Django FileNotFoundError when trying to add an item to a model - python

I am trying to create some models using Django and python. All my models are working and I can add items to the models, except for my User model. Can anyone suggest what could be wrong about it?
models.py
from django.db import models
# Create your models here.
class Item(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Name = models.CharField(max_length=30)
Price = models.IntegerField()
class User(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True)
Nickname = models.CharField(max_length=50)
Password = models.CharField(max_length=200)
Mail = models.EmailField()
Points = models.IntegerField()
SaleItem = models.ForeignKey(Item, on_delete=models.CASCADE)
ProfilePic = models.FilePathField()
BannerPic = models.FilePathField()
ZodiacSign = models.CharField(max_length=50)
class Friendship(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
UserID = models.ManyToManyField(User, related_name="user")
FriendID = models.ManyToManyField(User, related_name="befriended_user")
class ThreadPrivate(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Text = models.TextField()
Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Sender")
Receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Receiver")
Time = models.DateTimeField(auto_now_add=True)
class Side(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator_of_page")
Time = models.DateTimeField(auto_now_add=True)
class ThreadPublic(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Text = models.TextField()
Time = models.DateTimeField(auto_now_add=True)
Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="thread_sender")
SideID = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="side_for_thread")
and admin.py
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Item)
admin.site.register(User)
admin.site.register(Friendship)
admin.site.register(ThreadPrivate)
admin.site.register(Side)
admin.site.register(ThreadPublic)
I have remembered to add to APPS in settings.py and such. All models work,
except for the User model. Any ideas?
picture of the error:

You have to provide a path to the FilePathField of the user model. According to this answer you could create the variable FILE_PATH_FIELD_DIRECTORY in your settings and then use it like:
from django.conf import settings
class User(models.Model):
ProfilePic = models.FilePathField(path=settings.FILE_PATH_FIELD_DIRECTORY)
It would be helpful to change the name of your class to CustomUser, so you don't confuse it with the User class from django.

Related

I have extended the default User table named UserProfile and want to access info from Product model but shown integrity error

UserProfile table: (Extended table of default User)
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE`enter code here`
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
k_name = models.CharField(max_length=100, default="krishok Name", null=True)
k_address = models.CharField(max_length=300, default="Goes Krishok Address Here", null=True, blank=True)
k_national_id_no = models.CharField(default="1", max_length=50)
k_phone = models.CharField(default="01778956098", max_length=20)
k_email = models.EmailField(default="xxx#gmail.com", max_length=254)
k_image = models.ImageField(default = '', upload_to = 'upload/pkrishokImage/')
national_id = models.ImageField(default= '',upload_to = 'upload/IDImage/')
Product model code:
from Store.models.userprofile import UserProfile
from django.db import models
from .categories import Category
from .unit_type import Unit_Type
class Product(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
unit= models.ForeignKey(Unit_Type, on_delete=models.CASCADE, default=1)
Unit_price = models.IntegerField(default=0)
#k_name = models.ForeignKey(UserProfile, on_delete=models.CASCADE)#this is the problem
quantity = models.IntegerField(default=0)
description = models.CharField(max_length=200, default='', null=True, blank=True)
image = models.ImageField(upload_to = 'upload/productsImg/')
#staticmethod
def get_all_products():
return Product.objects.all()
#Filtering by Category Id:
# this method will bring all products by its categoryID
#staticmethod
def get_all_products_by_id(category_id):
if category_id:
return Product.objects.filter(category = category_id)
else:
return Product.get_all_products()
#i am trying to get id from extended user table called UserProfile model and want to get access of #all data from Product model, so that i am trying to written my foreignKey at product table from UserProfile table but it's give me integrity error.

'Users' object has no attribute 'values' django rest framework

I'm having a problem with serializing the data with joined tables. Am i doing this right? i'm just a newbie in django.
here's my models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
class Agency(models.Model):
agency_id = models.CharField(primary_key=True, max_length=50)
agency_shortname = models.CharField(max_length=20, blank=True, null=True)
agency_longname = models.CharField(max_length=255, blank=True, null=True)
date_created = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'agency'
class Users(AbstractBaseUser):
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = []
user_id = models.CharField(primary_key=True, max_length=50)
first_name = models.CharField(max_length=50, blank=True, null=True)
middle_name = models.CharField(max_length=50, blank=True, null=True)
last_name = models.CharField(max_length=50, blank=True, null=True)
username = models.CharField(unique=True, max_length=50, blank=True, null=True)
password = models.CharField(max_length=100, blank=True, null=True)
agency = models.OneToOneField(Agency, models.DO_NOTHING)
date_created = models.DateTimeField(blank=True, null=True)
active = models.CharField(max_length=8)
login_status = models.CharField(max_length=6)
last_login = models.DateTimeField(blank=True, null=True)
class Meta:
managed = False
db_table = 'users'
Then in my serializers.py
from rest_framework import serializers
from .models import Users, Agency
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
class AgencyDetailSerializer(serializers.ModelSerializer):
agency_id = UserDetailSerializer()
class Meta:
model = Agency
fields = ['agency_id','agency_shortname','agency_longname']
and my views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from .serializers import UserDetailSerializer
from .models import Users, Agency
from rest_framework.permissions import IsAuthenticated
#api_view(['GET'])
#permission_classes([IsAuthenticated])
def userData(request):
username = request.GET.get('username')
r_type = request.GET.get('type')
user = Users.objects.get(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
user_serializer = UserDetailSerializer(user, many=False)
return Response(user_serializer.data)
I'm getting an error of 'Users' object has no attribute 'values', what seems be the problem? i'm building api based application with vue.js and django rest framework. Thanks a lot
get queryset does not have values attribute, using filter instead.
user = Users.objects.filter(username=username).values(...)
Regarding your case, using get is enough and custom your Serializer like this:
class UserDetailSerializer(serializers.ModelSerializer):
class Meta:
model = Users
fields = '__all__'
agency = AgencyDetailSerializer(many=False, read_only=True)
Because values is not an attribute of model object. You can call values on queryset object. something like:
user = Users.objects.filter(username=username).values('user_id','first_name','middle_name','last_name','username','email','agency__agency_id','agency__agency_shortname','agency__agency_longname')
Note: You don't need to call values, just change this line to:
from rest_framework.generics import get_object_or_404
...
user = get_object_or_404(Users, **dict(username=username))
user_serializer = UserDetailSerializer(user)
...
Because serializer itself will handle it for you.

NameError: name 'Profile' is not defined

here is my models.py code. im trying to run the python3.8 manage.py migrate command to create the tables for the database but i keep getting this error, what could be the issue here. Profile is a class in the models.py code. if you need another part of my code please ask
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Image(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null='True', blank=True)
image = models.ImageField(upload_to = 'pics/')
name = models.CharField(max_length=50,blank=True)
caption = models.CharField(max_length=250, blank=True)
likes = models.ManyToManyField(User, related_name='likes', blank=True, )
date_posted = models.DateTimeField(default=timezone.now)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
You are using the Profile class before defining it. Switch the order of the Comment class and Profile class. Like so:
class Profile(models.Model):
name = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='images/', default='default.png')
bio = models.TextField(max_length=500, default="My Bio", blank=True)
followers = models.ManyToManyField(User, related_name="followers", blank=True)
following = models.ManyToManyField(User, related_name="following", blank=True)
class Comment(models.Model):
comment = models.TextField()
image = models.ForeignKey('Image', on_delete=models.CASCADE,related_name='comments',null='True', blank=True )
name = models.CharField(max_length=100, blank=True)
user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='comments',null='True', blank=True )
created = models.DateTimeField(auto_now_add=True, null=True)
You are referencing the Profile class before this is constructed. You can make use of a string literal instead:
class Comment(models.Model):
# …
user = models.ForeignKey(
'Profile', # ← a string literal
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
It might also be better to rename the field to profile, to make it clear the ForeignKey is referencing a Profile object, not a User object:
class Comment(models.Model):
# …
profile = models.ForeignKey( # ← rename to profile
'Profile',
on_delete=models.CASCADE,
related_name='comments',
null='True',
blank=True
)
# …
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

How to have a Django relational database with four tables?

I am creating a website using Django and have a problem with the database!
I have four tables (topics, questions, answers, and images). Each one of these tables has an id column and I would like to connect these four tables together.
I have tried to use a ForeignKey() but that didn't work out. I am receiving an error message. I don't know if I can use ManyToManyField() in this case, because it is only one column that I am trying to connect.
This is the code:
from django.db import models
# Create your models here.
class topics(models.Model):
topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()
class questions(models.Model):
question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()
class answers(models.Model):
answer_id = models.AutoField(primary_key=True)
description = models.TextField()
class images (models.Model):
image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()
This is the code with the ForeignKey():
from django.db import models
# Create your models here.
class topics(models.Model):
topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()
topic_question = models.ForeignKey(questions, on_delete=CASCADE)
topic_answer = models.ForeignKey(answers, on_delete=CASCADE)
topic_image = models.ForeignKey(images, on_delete=CASCADE)
class questions(models.Model):
question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()
question_topic = models.ForeignKey(topics, on_delete=CASCADE)
question_answer = models.ForeignKey(answers, on_delete=CASCADE)
question_image = models.ForeignKey(images, on_delete=CASCADE)
class answers(models.Model):
answer_id = models.AutoField(primary_key=True)
description = models.TextField()
answer_topic = models.ForeignKey(topics, on_delete=CASCADE)
answer_question = models.ForeignKey(questions, on_delete=CASCADE)
answer_image = models.ForeignKey(images, on_delete=CASCADE)
class images (models.Model):
image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()
image_topic = models.ForeignKey(topics, on_delete=CASCADE)
image_question = models.ForeignKey(questions, on_delete=CASCADE)
image_answer= models.ForeignKey(answers, on_delete=CASCADE)
And this is the error message that I am receiving:
topic_question = models.ForeignKey(questions, on_delete=CASCADE)
NameError: name 'questions' is not defined
At the point you're trying to use the question class name for indicating the related model, such class is not defined, as the error states. When you're referencing a model that is defined later in the code you must enclose the name in "":
topic_question = models.ForeignKey("questions", on_delete=CASCADE)
Here is the related docs: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey

In Django restframework, foreign key value is not getting in HyperlinkedModelserializer

Models.py
from django.db import models
class BusinessType(models.Model):
method = models.CharField(max_length=25)
class Vendor(models.Model):
first_name = models.CharField(max_length=25)
middle_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
nick_name = models.CharField(max_length=10)
email = models.CharField(max_length=30)
company = models.CharField(max_length=25)
phone = models.CharField(max_length=15)
mobile = models.CharField(max_length=10)
fax = models.CharField(max_length=10)
billing_address_street = models.CharField(max_length=120)
billing_address_city = models.CharField(max_length=20)
billing_address_state = models.CharField(max_length=20)
billing_address_zip = models.CharField(max_length=6)
billing_address_country = models.CharField(max_length=20)
shipping_address_street = models.CharField(max_length=120)
shipping_address_city = models.CharField(max_length=20)
shipping_address_state = models.CharField(max_length=20)
shipping_address_zip = models.CharField(max_length=6)
shipping_address_country = models.CharField(max_length=20)
notes = models.CharField(max_length=120)
gstin = models.CharField(max_length=25, null=True)
tin = models.CharField(max_length=25, null=True)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
Serializers.py
from rest_framework import serializers
from .models import Vendor,BusinessType
class BusinessTypeSerializer(serializers.HyperlinkedModelSerializer):
[enter image description here][1]
class Meta:
model = BusinessType
fields = ('id','method')
class VendorSerializer(serializers.HyperlinkedModelSerializer):
business_type = serializers.CharField(source='business_type.method')
class Meta:
model = Vendor
fields = ('id','first_name','middle_name','last_name','nick_name','email','company','phone','mobile','fax','billing_address_street','billing_address_city','billing_address_state','billing_address_zip','billing_address_country','shipping_address_street','shipping_address_city','shipping_address_state','shipping_address_zip','shipping_address_country','notes','gstin','tin','business_type')
In Django restframework, foreign key value is not getting in HyperlinkedModelserializer in 'business_type' field. When I tried to post method after declaring foreign key field, it says:
"AssertionError: The .create() method does not support nested
writable fields by default. Write an explicit .create() method for
serializer UserSerializer, or set read_only=True"

Categories

Resources