I have a django model called Contexts which is essentially a group that has a list of users.I have another model called UserProperty which has some user information.
class Contexts(models.Model):
context_name = models.CharField(max_length=50)
context_description = models.TextField()
users = models.ManyToManyField(UserProperty , related_name='context_users')
def getUserImagePath(instance,filename):
return "/static/images/%s_%s"% (str(time()).replace('.','_'),filename)
class UserProperty(models.Model):
username = models.CharField(max_length=255, null=False)
pic = models.ImageField(upload_to=getUserImagePath, default="/static/images/user.png" ,null=True, blank=True)
org = models.CharField(max_length=255, null=True)
This works fine in my local system when I run a migration using django manage.py.But in the server for some reason, I cannot run migrations and I have to define the models manually in postgres (the server uses django _ postgres).So this is what I did
CREATE TABLE webhook_contexts(id integer, context_name character varying(100), context_description character varying(100), users text [], FOREIGN KEY (users) REFERENCES webhook_userproperty);
I am not sure exactly how to replicate this in postgres.For users field in Contexts model, I did models.ManyToManyField(UserProperty , related_name='context_users') so I assume the users must be an array in postgres that contains the fields of the referenced table UserProperty namely username, pic, org.So I do
.., users text [], FOREIGN KEY (users) REFERENCES webhook_userproperty)
But I get this error
ERROR: there is no primary key for referenced table "webhook_userproperty"
But I did define an id for the webhook_userproperty which django treats as a primary key.Then why am I getting this error?Is my table definition wrong?
Related
I am getting this error while trying to save a model from the admin section using Django admin, this is the error Field 'object_id' expected a number but got 'id_b2cbfe2b1fd4313c'.. I am using django shortuuid package https://pypi.org/project/shortuuid/ to create id field in django, and i choose to use it because the inbuild UUID field keeps giving this error Django UUIDField shows 'badly formed hexadecimal UUID string' error? and the id looks like this id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True). What would be the problem witht the short uuid field.
Based on this, i quote:
If you filter on the ForeignKey, then Django will filter on the primary key of the target object, and that is normally an AutoField, unless you referred to another (unique) column, or defined another primary key as field.
But i dont know what the issue might be now
Models.py
class Channel(models.Model):
id = ShortUUIDField( length=16, max_length=40, prefix="id_", alphabet="abcdefg1234", primary_key=True,)
full_name = models.CharField(max_length=200)
user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True, related_name="channel")
Views.py
def channel_profile(request, channel_name):
channel = Channel.objects.get(id=channel_name, status="active")
context = {
"channel": channel,
}
return render(request, "channel/channel.html", context)
Your database is not sync with your migrations file, because your problem is easy to solve, Django is expecting an ID (integrer) and you are passing a string.
If you have not push your project into production you can delete the migration folder and migrate again, otherwise you need to update your migrations files to change the type for the UD field
I am changing my register model so that there is a foreign key referencing a location. What I want to achieve, is to have a relationship where the Register model can have 0 to many locations.
Originally I set a manytomany field which I realised was a mistake as it gives each Register all of the locations in existence. I just want a subset for each Register.
My model now looks like:
class Register(AbstractBaseUser, models.Model):
username = models.CharField(max_length=20,default='',blank=True)
password = models.CharField(max_length=80,default='',blank=True)
email = models.CharField(max_length=255,default='',blank=True)
#Added 2nd May
#locations = models.ManyToManyField(Location)
#3rd May change to foreign key
locations = models.ForeignKey(Location,on_delete=models.CASCADE, blank=True, null=True, default='')
USERNAME_FIELD = 'username'
The model referenced is:
class Location(models.Model):
locationname = models.CharField(max_length=80,default='',blank=True)
address = models.ForeignKey(Address, on_delete=models.CASCADE)
geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')
When I try to migrate I get the error below. I have ran makemigrations and if I run it again it states there are no changes.
"NOT NULL constraint failed: register_register.locations_id"
I have been searching other posts and it suggested adding the null=True argument which I have added, but I still get this error. I can't find any posts where this has been done and it still gives this error.
Purging the data from the database using manage.py flush allowed me to re-migrate the projects.
I realised that I had made a mistake with the relationship and had the Foreign key on the wrong table, it needed to be on location so that was fundamentally the issue.
I am currently working on a Django 1.5.2 project within a Docker instance that speaks with a mysql database in a separate Docker instance. I am trying to create a Many to Many relationship between two tables by creating a middle table that contains two foreign keys that point to the two tables that need connecting. The problem arises when I run python manage.py syncdb and it spits out the following error to the terminal: NameError: name 'QueryString' is not defined. QueryString is clearly defined in my models.
Here are my Models...
class Tag(models.Model):
name = models.CharField(max_length=100)
class QueryStringTab(models.Model):
tag = models.ForeignKey(Tag, related_name='querystringtab')
querystring = models.ForeignKey(QueryString, related_name='querystringtab')
class QueryString(BaseObject):
"""
Query string holds an SQL statement and query properties for execution
"""
server_id = models.IntegerField()
schema = models.CharField(max_length=255, blank=True)
query = models.CharField(max_length=60000)
variables = models.TextField(blank=True)
created_by = models.ForeignKey(User, related_name='queries_created')
updated_by = models.ForeignKey(User, related_name='queries_last_edited')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField()
touched_by = models.CharField(max_length=1000)
config = models.TextField(blank=True)
runs_started = models.IntegerField(default=0)
runs_completed = models.IntegerField(default=0)
runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion
formats = "pretty_html html json prettyjson csv excel tableau".split()
Noteworthy points...
1) It is recognizing the Tag model just fine.
2) Could it have something to do with the fact that QueryString is a BaseObject
3) It is successfully creating the Tag table in the mysql database
Can anyone find anything obvious that I am doing wrong?
The declaration of QueryStringTab is before the one for QueryStringTab; so when Python evaluates the first, it has not yet seen any definition for the second and therefore reports a NameError.
Django allows you to use a string target than a class object in cases like this:
querystring = models.ForeignKey('QueryString', related_name='querystringtab')
Or, you could simply move the definition of QueryStringTab to the end.
Im modeling database tables for register/login pages. At the first insert all ends without any errors, but following insert return IntegrityError exception:
duplicate key value violates unique constraint
"mainws_user_role_id_key" DETAIL: Key (role_id)=(1) already exists.
If OneToOneField making rows only as unique, it means, that I cant create many users with one role, right? Then better using ForeignKey(Role) for this situation, or not?
Source code:
class User(models.Model):
login = models.CharField(max_length=50)
password = models.CharField(max_length=50)
address = models.CharField(max_length=255)
phone = models.CharField(max_length=25)
postcode = models.CharField(max_length=25)
email = models.EmailField()
role = models.OneToOneField(Role, primary_key=False)
class Role(models.Model):
role_name = models.CharField(max_length=25, unique=True)
def create_user(user_data):
md5 = hashlib.md5()
md5.update(user_data['password'])
user_role = Role.objects.filter(role_name='user')[0]
password_md5 = md5.hexdigest()
new_user = User(login=user_data['login'],password=password_md5,address=user_data['address'],
phone=user_data['phone'],postcode=user_data['postcode'],
email=user_data['email'],role=user_role)
new_user.save()
I would think your issue is in the OneToOneField. As its name implies, you can only associate one role with one user. A foreign key represents a ManyToOne relationship, that is what you want in this case, many users can have one role.
On the other hand, you are trying to create users on your own when Django already has most of that by default. Frameworks are there to avoid you making sensitive parts of your application manually.
You may want to check documentation if you don't know how to do that.
A duplicate model field is giving me trouble (no such table appname_modelname when I run my webpage). Whenever I do ./manage.py migrate appname, it gives me "duplicate field". I checked my models.py, there is only one of them there. How do I delete that duplicate field? It seems no matter what I do, it stays. I've tried:
Deleting the database
Deleting migrations folder in app folder
Doing ./manage.py sqlclear south and then dropping the south_migrationhistory table in the dbshell
./manage.py schemamigration appname --initial, ./manage.py migrate appname --fake
I've run out of ideas.
class Document(models.Model):
filename = models.CharField(max_length=255, blank=True, null=True, default=None)
identity = models.CharField(max_length=255, default=None, null=True)
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
docfile = models.FileField(upload_to=_upload_path, storage=fs) # upload_to is a path inside the storage path
def get_upload_path(self,filename):
return str(self.user.id) + '/' + str(date.today()) + '/' + filename
You can't do this, for your user foreign key, Django ORM will create a database field named user_id (your foreign key field name plus _id) to use it as a FK in the database.
You don't have to create this field yourself (the ORM will take care), even if you need it, change the name of the attribute user or user_id.
From the documentation:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
Not sure but problem causing here in these two line
user = models.ForeignKey(User, null=False)
user_id = models.IntegerField(User, null=True)
Better to use "related name" attribute to avoid the duplicate error as in database "user" will be added as user_id.
user = models.ForeignKey(User, related_name="id_user") # Change the related field as your convenience
user_id = models.IntegerField(null=True, related_name="user_id")
Check if this resolve your issues