I have two models:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Category(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="categories")
name = models.CharField(max_length=30, unique=True, primary_key=True)
class Todo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='todos')
# TODO: Add confirmation before deleting category
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name="todos_in_category", null=True)
item = models.CharField(max_length=50)
added = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
Previously, Category's PK was the default id, however, I changed it to the name field. When I ran the migrations, i received the operational error. Thinking that it was perhaps due to a conflict between the existing id fields and the new primary key, I cleared the data in the database but with no success. Any ideas as to what could be the issue here? Thanks!
Related
I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model
class Customer(models.Model):
id = models.AutoField(primary_key=True)
User = models.OneToOneField(
Account, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, default='0', null=True, blank=True)
address = models.CharField(
max_length=200, default=' ', null=True, blank=True)
city = models.CharField(max_length=200, default=' ', null=True, blank=True)
def __str__(self):
if self.name == None:
return "ERROR-CUSTOMER NAME IS NULL"
return self.name
Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created
I think it would be better to extend the User model, and add more fields rather than creating a new model (which has a User onetoonefiled in it).
Something like this:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField(max_length=500, blank=True)
location = models.CharField(max_length=30, blank=True)
birth_date = models.DateField(null=True, blank=True)
This is the kind of approach I use in my projects.
Here you have the default User model fields:
User model default fields
You don't need to add these in your Profile class.
I based this on this article: How to extend User Django Model
don't forget to add to the admin.py:
from django.contrib import admin
from .models import Profile
# Register your models here.
admin.site.register(Profile)
to see the Profiles in the admin page
Got it fixed by setting the user in the Customer model when a user is created
Customer.objects.create(user=request.user, name=username, email=email, phone=phone)
I have a condition that has one to many relationship scenarios because I will have multiple projects inside one account.
models.py
class Account(models.Model):
name = models.CharField(max_length=255, default='')
class Project(models.Model):
account = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
how can I manage this scenario, currently I'm getting the following error:
django.db.utils.ProgrammingError: relation "project_account_id_7d9b231b" already exists
account = models.ForeignKey(Account, on_delete=models.CASCADE, null=True)
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.
My admin page is working fine except when logged in it is not showing any user models. It is hindering my work as I cannot manage users.
I have made custom models as shown below.
Database is MySQL.
models.py
class User(AbstractUser):
is_customer = models.BooleanField(default=False)
is_restaurant = models.BooleanField(default=False)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
food_pref = models.CharField(max_length=10, default='veg')
class Restaurant(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
restaurant_name = models.CharField(max_length=100, blank=False)
Regisrar your models inadmin.py file.
from . models import Model_Name
Then you can register your models in two ways:
I) admin.site.register(Model_Name)
II)
#admin.register(Model_Name)
Class Xyz(admin.ModelAdmin):
pass
Second method gives you more flexibility like list_display, list_filter, date_hierarchy, etc. for customising your Admin section/site.
You can look more about customising admin site at https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#module-django.contrib.admin
Have You registered them in admin.py?
from .models import ModelName
admin.site.register(ModelName)
I would like to ask how I could list all objects of logged current user via class based view in django.
I have two apps in the project. One is called users and the other one is badminton.
users/models.py
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
name = models.CharField(max_length=200, null=True)
badminton/models.py
from django.db import models
from users import models as users_models
class Player(models.Model):
name = models.OneToOneField(users_models.Profile ,null=True, on_delete=models.CASCADE)
matches_played = models.IntegerField(default=0, blank=True, null=True)
class Match(models.Model):
player_home = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_home')
player_away = models.OneToOneField(Player, null=True, on_delete= models.SET_NULL, related_name='player_away')
How I can access all matches of logged user via queryset? Thank you for your help!
You can list Matches for which the request.user has as Player object player_home and/or player_away for that match with:
from django.db.models import Q
Match.objects.filter(
Q(player_home__name__user=request.user) |
Q(player_away__name__user=request.user)
)
Note: A foreign key refers to an object, not to the string representation of that
object. Therefore name is not really a good name to refer to a Profile object. You
might want to consider renaming it to profile.