Usertype models in Django - python

I'm being confused on where table how I insert my usertypes, I'm just a beginner on Django but surely Im been reading documentation in Django but I can't understand this one , The case is when I register new user there's must be choice what usertype should specify with this user either an admin or etc. but the problem is I think there is no relationship table from authuser even I create another table.slight similar to this problem resources link. For now I'm been thinking to create custom usertype field in authuser table, but when migrate it didn't show updated fields and also like this issue some people or user didn't touch or add any field in authuser table sample it is possible to insert usertype in auth_permission or other default table? Im just really confused of where table I can add my usertype that have a relationship to authuser. Is there any know or explain about this, thanks
Models
class AuthUser(models.Model):
password = models.CharField(max_length=128)
last_login = models.DateTimeField(blank=True, null=True)
is_superuser = models.IntegerField()
username = models.CharField(unique=True, max_length=150)
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
email = models.CharField(max_length=254)
is_staff = models.IntegerField()
is_active = models.IntegerField()
date_joined = models.DateTimeField()
usertype_id = usertype = models.OneToOneField(usertypes,on_delete=models.CASCADE,primary_key=True)
() //this is what i want to add
class Meta:
managed = False
db_table = 'auth_user'
class usertypes(models.Model):
usertype = models.CharField(max_length=264)
description = models.CharField(max_length=264)
status = models.CharField(max_length=264)

There are multiple ways how to do it. The way I recommned is to extend the existing user model.
from django.contrib.auth.models import User
class UserType(models.Model):
user_type = models.CharField(max_length=264)
description = models.CharField(max_length=264)
status = models.CharField(max_length=264)
class AppUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
type = models.ForeignKey(UserType, on_delete=models.CASCADE)
This will create 2 extra tables.
user_type where you will have UserTypes that you probably want to fill and
app_user where will be stored reference on django user record and its type
However, I think you should have a good reason why you do this. Django allows you to group users into the user groups, what should be exactly what you want.

Related

Is there any way to select a value dynamically for a model's related field in runtime?

I want to achieve a functionality, where I need to select a django model (e.g from a drop down list), and after selecting one, all the objects of that model shows up.
class Thread(models.Model):
sender = models.(???) # This need to be a field that can store a different model on a run time.
receiver = models.(???) # same here.
Is there any way that I can dynamically first select the model and then pick an object of that list. I have seen this functionality in odoo. But is there anything in Django?
Use Inheritance for in your Model and map your foreign key to User, and then pass either a teacher of student object.
You can use the many-to-many filed with multiple available choices of "Student" and "Teacher" from another Model.
class UserRole(models.Model):
STUDENT = 'STUDENT'
TEACHER = 'TEACHER'
ROLE_CHOICES = (
(STUDENT, 'student'),
(TEACHER, 'teacher'),
)
role_name = models.CharField(max_length=255, choices=ROLE_CHOICES)
def __str__(self):
return "{}".format(self.role_name)
class User(AbstractUser):
username = models.CharField(max_length=50, unique=True)
email = models.EmailField(_('email address'))
role = models.ManyToManyField(UserRole)
Class Thread(models.Model):
sender = models.OneToOneField(User, on_delete=models.CASCADE)
receiver = models.OneToOneField(User, on_delete=models.CASCADE)
This way you can only put available roles in sender and receiver fields of Thread.
The solution was possible with ajax too, but there also is another way in django which I was searching for.
class Test(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
Have a good one.

How do can I creating and use a custom fields in Django

I am new to django and building a kinda of a package (Shipments) based app in Django and I have these models,
class ShippingLocation(models.Model):
latitude = models.IntegerField()
longitude = models.IntegerField()
class Shipping (models.Model):
email = models.EmailField()
location = models.ForeignKey(ShippingLocation , default=None, on_delete=models.CASCADE )
class Package(models.Model):
name = models.CharField(max_length=30)
supplier = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
to = models.ForeignKey(Shipping, default=None, on_delete=models.CASCADE )
this work okay for now but I wonder if can be able to remove the ShippingLocation model and use a custom field instead of at the location field in the Shipping model? If yes how do I create custom fields and how do I implement them?
so I have something like
class Shipping (models.Model):
email = models.EmailField()
location = models.DictionaryField()
and I get rid of the ShippingLocationModel
This should be work:
delete the SQLite database
change the model
then run the migrate command

Django: Making a value in a model unique specific to a user

I have a model for a project:
class Project(models.Model):
name = models.CharField(max_length=200, unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
I want to make the project name a unique value per user but at the moment if user 1 creates a name of "project 1" then user 2 is unable use that project name.
What is the best way to go about this?
Thanks!
unique_together is probably what you are looking for.
class Project(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User, on_delete=models.CASCADE)
class Meta:
unique_together = (('name', 'user'),)

How to insert data into a relational one to one table in django?

I have a UserProfile table which is in relation with the default Django User table. Here's how it looks.
class UserProfile(models.Model):
user = user.OneToOneField(User, on_delete=models.CASCADE)
section = models.CharField(max_length=255, blank=True)
year = models.IntegerField(null=True, blank=True)
course = models.CharField(max_length=255, blank=True)
qrcode = models.CharField(max_length=255, blank=True)
present = models.BooleanField(default=False)
I am trying to insert the data into the UserProfile table using the Django Shell.
from users.models import UserProfile
a = UserProfile(qrcode="hello")
a.save()
This is how I have always known to insert data into tables, it has always worked. BUT when i try to do this in UserProfile model. I get this exception. NOT NULL constraint failed: users_userprofile.user_id. Which in turn is caused by the following exception Error in formatting: RelatedObjectDoesNotExist: UserProfile has no user.
I somewhat understand that I somehow need to supply a user instance. But I am clueless as to how. Can someone please help me.
Firstly you need to create User.
u1 = User(username='user1')
u1.save()
Create a UserProfile. Pass the ID of the “parent” object as this object’s ID:
v1 = UserProfile(user=u1, ....)
v1.save()
refer this
You need to create your User first
user = User.objects.create(username='user')
and then you can do:
user_profile = UserProfile.objects.create(user=user, ...)

Django filtering queries with multi-table inheritance

I'm using Django multi-table inheritance to implement a notifications system.
It looks like this:
class Notification(models.Model):
# this allows us to check the type without having to query another table
type = models.CharField(max_length=2, choices=type_choices)
user = models.ForeignKey(User, related_name='+', null=True)
date = models.DateTimeField(default=datetime.now)
read = models.BooleanField(default=False)
class Meta:
ordering = ["-date"]
# Users can comment on items.
class CommentNotification(Notification):
comment = models.ForeignKey(Comment, related_name='+')
class ShareNotification(Notification):
share = models.ForeignKey(Share, related_name='+')
# If user unsubscribes from an item, they will not receive notifications of comments on that item
class UnsubscribeItem(models.Model):
user = models.ForeignKey(User, related_name='+')
item = models.ForeignKey(Item, related_name='+')
class Comment(models.Model):
item = models.ForeignKey(Item, related_name='comments')
user = models.ForeignKey(User, related_name='+')
comment = models.TextField()
If I want to get all notifications for a user, I can simply query the Notification table. But I also want to exclude any CommentNotification entries if the user has unsubscribed from that item (only if there is an UnsubscribeItem with user=request.user and item=comment.item).
The problem of course is the field I want to filter is not on the base class. Is it possible to modify the queryset itself to exclude those entries? Or do I need to exclude them while serializing the collection? (I'm using django-rest-framework to serialize for my API, if that helps.)

Categories