ForeignKey to a Model field? - python

I want a foreign key relation in my model with the username field in the User table(that stores the user created with django.contrib.auth.forms.UserCreationForm).
This how my model looks:
class Blog(models.Model):
username = models.CharField(max_length=200) // this should be a foreign key
blog_title = models.CharField(max_length=200)
blog_content = models.TextField()
The username field should be the foreign key.The Foreign Key should be with this field

Unless I'm missing something, you can have a ForeignKey to a specific field:
class Blog(models.Model):
username = models.ForeignKey(User, to_field='username')
https://docs.djangoproject.com/en/1.11/ref/models/fields/#django.db.models.ForeignKey.to_field

You can't have an ForeignKey to a field, but you can to a row.
You want username which is available through the User model
So:
blog.user.username
If you insist on having blog.username you can define a property like this:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
user = models.ForeignKey(User)
Then to access the field you want use:
blog.user.username
If you insist on having blog.username you can define a property like this:
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
user = models.ForeignKey(User)
#property
def username(self):
return self.user.username
With that property, you can access username through blog.username.
Note on how to import User
user = ForeignKey('auth.User')
or
from django.contrib.auth.models import User
user = ForeignKey(User)
or the more recommended
from django.conf import settings
user = ForeignKey(settings.AUTH_USER_MODEL)

Related

Inherit a custom user models fields from parent class to a child class between two different applications

Hello kings and queens!
I'm working on a project and got stuck on a (for me) complicated issue. I have one model (generalpage.models) where all the common info about the users is stored. In a different app (profilesettings), I have an app where all profile page related functions will be coded.
I tried to inherit the model fields from the User class in generalpage.models into profilesettings.models by simply writing UserProfile(User). When I did this, a empty forms was created in the admin panel. So basically, the information that was already stored generalpage.models were not inherited into the profilesettings.models, I created an entire new table in the database.
my questions are:
Is it possible to create an abstract class for a custom user model?
Is there a proper way to handle classes and create a method in profilesettings.models that fills the UserProfile form with the data already stored in database created by the User class?
Can someone please explain how the information can be passed from one application to another without creating a new empty form?
Filestructure:
Admin panel:
generalpage.models:
from random import choices
from secrets import choice
from unittest.util import _MAX_LENGTH
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, User, PermissionsMixin
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from generalpage.managers import CustomUserManager
from django.conf import settings
from generalpage.managers import CustomUserManager
# Create your models here.
sex_choices = ( ("0", "Man"),
("1", "Kvinna"),
("2", "Trans")
)
class User(AbstractBaseUser, PermissionsMixin):
user = models.CharField(settings.AUTH_USER_MODEL, null=True, max_length=50)
username = models.CharField(_("Användarnamn"), max_length=100, null=True, unique=True)
age = models.IntegerField(_("Ålder"),null=True, blank=False)
email = models.EmailField(_("E-mail"), unique=True, null=False)
country = models.CharField(_("Land"),max_length=50, null=True, blank=True)
county = models.CharField(_("Län"),max_length=50, null=True, blank=True)
city = models.CharField(_("Stad"),max_length=50, null=True, blank=True)
sex = models.CharField(_("Kön"), choices=sex_choices, null=True, blank=False, max_length=50)
profile_picture = models.ImageField(_("Profilbild"),null=True, blank=True, default="avatar.svg", upload_to = "static/images/user_profile_pics/")
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'username' # defines the unique identifier for the User model
REQUIRED_FIELDS = ["email"] # A list of the field names that will be prompted for when creating a user via the createsuperuser management command
objects = CustomUserManager()
def __str__(self):
return self.username
profilesettings.models:
from generalpage.models import User, UserInfo, Room, Message, Topic
from django.db import models
class UserProfile(User):
pass
class Settings(UserInfo):
pass
My models after #viktorblindh suggestion are:
for admin.py:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from profilesettings.models import UserProfile
from generalpage.models import User
class UserProfileInline(admin.StackedInline):
model = UserProfile
min_num = 1
class UserProfileAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)
# admin.site.register(UserProfile)
# admin.site.register(Settings)
and for profilesettings.models:
from generalpage.models import User, UserInfo, Room, Message, Topic
from django.db import models
from django.conf import settings
class UserProfile(User):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Settings(UserInfo):
pass
```
The solution suggested in:
https://stackoverflow.com/questions/42424955/how-to-exchange-data-between-apps-in-django-using-the-database
solved my issue.
Maybe i'm misunderstanding the issue at hand but to me it sounds like you would want to have a OneToOne key on your profilesettings.UserProfile to your generalpage.user. I'm assuming every user have their own unique profilesettings.
from django.conf import settings
class UserProfile(User):
user(models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Then after that you can use an inlineformset in your generalpage.admin to get all the information displayed in the same form.
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from profilesettings.models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
min_num = 1
class UserProfileAdmin(BaseUserAdmin):
inlines = [UserProfileInline, ]
admin.site.register(User, UserProfileAdmin)

Django: use a Foreignkey relationship for custom user model

I am writing a webapp where I want to have a general Person table to uniquely identify any person interacting with the website, e.g. to be able to comply to GDPR requests.
Some Persons will should also be Users in the authentication sense.
I'd like to use Person.email for the username.
However, I cannot manage to make authentication / admin interface work.
Simplified models:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
class Person(models.Model):
name = models.CharField(max_length=255, blank=False)
email = models.EmailField(blank=False, unique=True)
class User(AbstractBaseUser, PermissionsMixin):
person = models.OneToOneField(Person, on_delete=models.PROTECT)
USERNAME_FIELD = ...# what to put here?
I found a very old Django issue that seems related:
https://code.djangoproject.com/ticket/21832
Any idea, how to make this work with a foreign key to hold the basic user information?
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
Here you go for correct way of achieving this
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(unique=True)
USERNAME_FIELD = ['email'] # It's mean you can login with your email
class Person(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Note: If you use AbstractBaseUser models, then you have to write custom model manager.
To avoid writing custom models manager, you should use AbstractUser
class User(AbstractUser):
pass
# here all the required fields like email, name etc item
You can create Person record for the user when a user records creating using django signal:
https://docs.djangoproject.com/en/3.2/topics/signals/

Class relationship in Django model

My project(Django Rest Framework) is blog app where logged in users can Post some texts and any logged in users can add comment to Posts.
What are the changed I need to make in the Post and Comment class to establish the logic ?
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
class User(AbstractUser):
#User model
class Post(models.Model):
postdata = models.CharField(max_length=100)
owner = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
class Comment(models.Model):
body = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
Add a ForeignKey pointing to your Post model in the Comments model:
post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='comments')
As a good practice, keep using settings.AUTH_USER_MODEL instead of User directly

the model field's form disappears in django admin

I have two models, which are User and Record. Each has several fields.
from django.db import models
class User(models.Model):
openid = models.CharField(max_length=20)
nickname = models.CharField(max_length=20,null=True)
def __str__(self):
return self.nickname
class Record(models.Model):
expression = models.CharField(max_length=100)
user = models.ForeignKey(User)
time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.expression
I register them in admin.py
from django.contrib import admin
from .models import User,Record
class RecordAdmin(admin.ModelAdmin):
list_display = ('expression','user','time')
class UserAdmin(admin.ModelAdmin):
empty_value_display = "空"
list_display = ('openid','nickname')
admin.site.register(User,UserAdmin)
admin.site.register(Record,RecordAdmin)
it works well in django admin initially. but one day, the fields of the Record model disppeared. It looks like
.
No field displays. It makes me unable to modify or add the values of the Record model. The other model User works well and all data exists in database. So why?
I think you just have to add on_delete=models.CASCADE in your ForeignKey Field. When you are using this kind of field, you have to specify the comportment when you make an update, a delete or anything else on this field.
So your script should be like this :
class Record(models.Model):
expression = models.CharField(max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE)
time = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.expression
This is the result :
Edit :
You can also modify null=True by default=null
class User(models.Model):
openid = models.CharField(max_length=20)
nickname = models.CharField(max_length=20,default=null)
def __str__(self):
return self.nickname

Using foreign key of the UserCreationForm model User

I have made a signup page using built in UserCreationForm of django.
signup.html
class UserCreationForm(UserCreationForm):
email = EmailField(label=_("Email address"), required=True, help_text=_("Required."))
class Meta:
model = User
fields = ("username", "email", "password1", "password2")
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.email = self.cleaned_data["email"]
if commit:
user.save()
return user
But I also need to make other tables in models.py. So if in another table category I need to make a foreign key of the primary key of this built in User of UserCreationForm. What is the primary key in this?
models.py
class category(models.Model):
uid = models.ForeignKey(#)
cname = models.CharField(max_length=20)
def __unicode__(self):
return u"{} {}".format(self.uid, self.cname)
class Meta:
db_table = "category"
What do I write in place of # ??
Just point to the User model:
from django.contrib.auth import User
uid = models.ForeignKey(User)
or better, in case you might want to customise the User model:
from django.conf import settings
uid = models.ForeignKey(settings.AUTH_USER_MODEL)

Categories