Hello I had to rewrite my user model for add some filed, I used AbstractUser
My models:
It's on blog app:
class Article(models.Model):
author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')...
it's on account app:
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی")
special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا")
def is_special_user(self):
if self.special_user > timezone.now():
return True
else:
return False
is_special_user.boolean = True
is_special_user.short_description = "وضغیت کاربر ویژه"
I imported my User view in this way:
from account.models import User
And I added this to my setting:
AUTH_USER_MODEL = 'account.User'
when I migrate I get this error:
blog.Article.author: (fields.E301) Field defines a relation with the
model 'auth.User', which has been swapped out.
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'.
I searched my error but I can't find my solution
The current User passed to the ForeignKey points to the auth.User right now, not your custom User.
As the HINT itself suggests, use settings.AUTH_USER_MODEL instead of User in your author field in Article model.
class Article(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')...
Link to django docs: Using a custom user model
Did you register the model in the app's admin.py?
Furthermore, changing the user model mid-project...this can be a hassle, look here: Changing to a custom user model mid-project
I think you are importing User model from django auth app.
Change the author field in the Article model as follows:
class Article(models.Model):
author = models.ForeignKey('account.User', null=True, on_delete=models.SET_NULL, related_name='articles', verbose_name='نویسنده')
...
Related
Here is my code
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
So I'm kinda confused with what models.DateTimeField(default=timezone.now) do, what does "default" mean here?
And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is "on_delete=models.CASCADE" do and mean?
And is this code ( from django.contrib.auth.models ) a database for users?
models.DateTimeField(default=timezone.now) do, what does "default" mean here?
You can pass a callable to the default=… parameter. When the model object is the created, and there is no value for date_posted, it will call the timezone.now function and use the result as value for the date_posted.
And I'm also confused what models.ForeignKey(User, on_delete=models.CASCADE) do, what is on_delete=models.CASCADE do and mean?
A ForeignKey refers to an object. The question is what to do if the object it is referring to is removed. With on_delete=… [Django-doc] you can specify a strategy. CASCADE means that it will remove the Post(s) from a User, if that User is removed itself.
And is this code ( from django.contrib.auth.models ) a database for users?
These are models defined in the auth app. Django has such app to make it easy to start with a simple user model, but you can decide to impelement your own. 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.
when i am migrating the code below i get the following error ----ERRORS:
users.UserStripe.user: (fields.E300) Field defines a relation with model 'settings.AUTH_USER_MODEL', which is either not installed, or is abstract.
users.UserStripe.user: (fields.E307) The field users.UserStripe.user was declared with a lazy reference to 'settings.auth_user_model', but app 'settings' isn't installed.---
I understand that it relates to the fact i have 'user' in the stripe and profile class but I'm not sure how to stop the error. any guidance would be appreciated!
models.py - users
import stripe
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
stripe.api_key = '****************'
class UserStripe(models.Model):
**user = models.OneToOneField('settings.AUTH_USER_MODEL', on_delete=models.CASCADE)**
stripe_id = models.CharField(max_length=120)
def __str__(self):
return str(self.stripe_id)
class Profile(models.Model):
**user = models.OneToOneField(User, on_delete=models.CASCADE)**
image = models.ImageField(default='', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
You should not use 'settings.AUTH_USER_MODEL' as a string literal, since then Django will look for a model named AUTH_USER_MODEL in the settings app. But there is no settings app, and nor is there a model with that name.
You should pass the value of settings.AUTH_USER_MODEL:
from django.db import models
from django.conf import settings
class UserStripe(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
stripe_id = models.CharField(max_length=120)
def __str__(self):
return str(self.stripe_id)
class Profile(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
image = models.ImageField(default='', upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
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.
I'm using the django admin and want to sort (by last_name) the dropdown list of users in a related field (ForeignKey).
I'm am using the standard User model in django. I tried the following in the model.py which is not working:
...
from django.contrib.auth.models import User
class Meta:
ordering = ['last_name']
User.add_to_class("Meta", Meta)
...
class Application(models.Model):
...
user = models.ForeignKey(User,
verbose_name="xyz",
null=True, blank=True,
limit_choices_to={'is_active': True},
on_delete=models.PROTECT)
...
Why is this not working? Is there another (easy) way to do it? I probably should have gone for a custom user model. But I didn't do that and changing it now is seams a lot of work.
I am using django 2.0.5 with python 3.6.5
Any help is appreciated.
Why not do it in your model class
class MyModel (models.Model):
user = models.ForeginKey(User)
...
class Meta:
ordering ['user__last_name']
It seams that the ordering in the User model is overwritten by the ordering specified in UserAdmin. Specifying my own UserAdmin solved the problem.
class MyUserAdmin(UserAdmin):
...
ordering = ["last_name", "first_name"]
...
admin.site.register(User, MyUserAdmin)
I read the docs and this post... Django - Foreign Key to User model
I followed what it said and I still cannot get it to work. When I try to run the migrations I get this error in the traceback...
django.db.utils.ProgrammingError: column "author_id" cannot be cast automatically to type integer
HINT: You might need to specify "USING author_id::integer".
I just don't know how to go about fixing that error.
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class BlogCategory(models.Model):
'''model for categories'''
title = models.CharField(max_length=30)
description = models.CharField(max_length=100)
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
Don't use the User model directly.
From the documentation
Instead of referring to User directly, you should reference the user
model using django.contrib.auth.get_user_model()
When you define a foreign key or many-to-many relations to the user model, you should specify the custom model using the AUTH_USER_MODEL setting.
Example:
from django.conf import settings
from django.db import models
class Article(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
If you created a custom User model, you would use setting.AUTH_USER_MODEL, if not you can go ahead an use User model
Referencing Django User model
the column "author_id" doesn't exist, looks like is the same problem from here : Django suffix ForeignKey field with _id , so to avoid this traceback you may use :
author = models.ForeignKey(User, db_column="user")
I do not know the "settings.AUTH_USER_MODEL" approach but a well-known approach and commonly used is the "Auth.User" model. Something like this on your end.
from django.contrib.auth.models import User
class BlogPost(models.Model):
'''a model for a blog post'''
author = models.ForeignKey(User)
date = models.DateField()
title = models.CharField(max_length=100)
post = models.TextField()
I built a simple django application and now have a really confusing error message. I think it's because of Tabularinline, but I use it properly according to this documentation.
models.py
from django.db import models
class Person(models.Model):
company = models.CharField(max_length=120)
name = models.CharField(max_length=120)
birthday = models.DateField(null=True, blank=True)
def __unicode__(self):
return self.name
class Note(models.Model):
person = models.ForeignKey(Person)
datetime = models.DateTimeField()
text = models.TextField()
admin.py
from addressbook.models import Person, Note
from django.contrib import admin
class NoteInline(admin.TabularInline):
model = Note
class PersonAdmin(admin.ModelAdmin):
model = Person
inlines = [NoteInline, ]
admin.site.register(Note, NoteInline)
admin.site.register(Person, PersonAdmin)
But I always get this error message:
<class 'addressbook.admin.NoteInline'>: (admin.E202) 'addressbook.Note' has no ForeignKey to 'addressbook.Note'.
Which I would understand but why should have Note a reference to itself If I am using it from Person?
I don't think you need to separately register the NoteInline admin template. Just register the PersonAdmin template and that should include your NoteInline