I have a model with start_date and end_date. I would like to add a list of users at the bottom so that an admin can pick from a list of users that are associated with this model.
This is how the model looks in admin panel at the moment
My model looks like this in models.py
class MyPeriod(ValidateOnSaveMixin, models.Model):
start_date = models.DateField(unique=True)
end_date = models.DateField()
In admin.py I tried adding filter_horizontal like this but it gave me errors
class MyPeriodAdmin(admin.ModelAdmin):
list_display = ('start_date', 'end_date',)
filter_horizontal = ('user',)
The value of 'filter_horizontal[0]' refers to 'user', which is not an
attribute of 'MyPeriod'.
Your current model does not contain an association between period and users. You have to specify a ForeignKey relation with the User model, such as:
from django.conf import settings
...
class MyPeriod(ValidateOnSaveMixin, models.Model):
start_date = models.DateField(unique=True)
end_date = models.DateField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
After this addition (and applying migrations to reflect the changes to the actual database) you will be able to assign Users to your MyPeriod model.
Related
model1
class Client(models.Model):
client_name=models.CharField(max_length=20)
company=models.CharField(max_length=200)
finance_contact_email=models.EmailField(max_length=25,default=None)
business_purpose=models.CharField(max_length=50,null=True,default=None)
location=models.CharField(max_length=200)
emergency_contact=models.CharField(max_length=200,null=True,default=None)
website=models.URLField(max_length=200,null=True)
comments=models.TextField(max_length=300,null=True, blank=True)
start_Date = models.DateTimeField(max_length=10,null=True)
end_Date=models.DateField(max_length=10,null=True)
Model2
class Project(models.Model):
project_name = models.CharField(max_length=20)
client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None)
description=models.TextField()
type=models.TextField()
start_date = models.DateTimeField(max_length=10)
end_date=models.DateTimeField(max_length=10)
technical_contact_name = models.CharField(max_length=30)
email=models.EmailField(max_length=254,default=None)
phone = PhoneField(blank=True)
delivery_head_contact_name=models.CharField(max_length=30)
model3
class Job(models.Model):
job_name=models.CharField(max_length=50)
client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client',default=None)
project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project',default=None)
user=models.ForeignKey(User,on_delete=CASCADE,related_name='user',default=None)
hours=models.TimeField(null=True)
start_date = models.DateTimeField(max_length=10)
end_date=models.DateTimeField(max_length=10)
Actually I need to filter the values based on the clients in the Job model. For example we will be giving the project_name on the Project model based on selecting the specific clients. So we need a filter in the Job model like if we select the specific client in the field, it needs to display only the projects available for that client in the project field of Job model.
Now it is displaying all the projects which are inputted. Please help me get this solved as I am new to django.
I am creating a app using django rest-framework to record mensuration date.I have to put a validation to date fields like if one date is already entered in database the app should avoid to enter same date which is already exist in database. Need help to do that
You can make use of a UniqueConstraint [Django-doc] where you include both the user and the date:
from django.conf import settings
class MyModel(models.Model):
date = models.DateField()
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
class Meta:
constraints = [
UniqueConstraint(fields=['user', 'date'], name='unique_date_per_user')
]
Prior to django-2.2, you can make use of unique_together [Django-doc]:
from django.conf import settings
class MyModel(models.Model):
date = models.DateField()
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
class Meta:
unique_together=(('user', 'date'),)
I am creating my own users, Restaurant and Customer. I have extended the AbstractUser class and then created a OneToOneField field for each user. I am wondering if I need to add the AUTH_USER_MODEL in my settings.py. And also wondering what that does exactly...
What I was planning on doing was adding to my settings.py:
AUTH_USER_MODEL = 'myapp.Customer','myapp.Restaurant'
Do I have the right idea here?
My models.py:
class User(AbstractUser):
is_restaurant = models.BooleanField(default=False)
is_customer = models.BooleanField(default=False)
class Restaurant(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
restaurant_name = models.CharField(max_length=50)
def __str__(self):
return self.restaurant_name
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE)
address = models.CharField(max_length=200)
def __str__(self):
return self.user.get_full_name()
No. AUTH_USER_MODEL isn't expecting a tuple, so this won't work.
In any case, Restaurant and Customer are not your user model; your subclassed User is. That's what you should be putting in that setting.
I would suggest create single user table instead of three different tables and add type as restaurant, customer, admin etc. And add only one table into settings file. this won't lead any further issues authentication etc. Having single user table is always robust. In your case having three tables seems not good to maintain.
========== UPDATE ===========
Create model for user named as CustomUser (or name which you feel better) and extends to User Model of Django using AbstractBaseUser,PermissionsMixin. like
class CustomUser(AbstractBaseUser): have all fields which user table has already. and add your desired table to bifurcate type of restaurant and
customer have type field with choices option.
For further help you can check section https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#substituting-a-custom-user-model
I have been getting my head around these basics but I am not getting it right. I am trying to associate my view to my user model using team which is a foreign key. When I try to create of a gps, I get an error saying "team is a required field" but instead it should be read only. The team attribute should be filled automatically with the id of the currentUser
Model
class User(models.Model):
first_name = models.CharField(max_length=200,blank=False)
last_name = models.CharField(max_length=200, blank=False)
class Gps(models.Model):
location = models.CharField(max_length=200,blank=False)
team= models.ForeignKey(User, on_delete=models.CASCADE)
serializers
class GpsSerializer(serializers.ModelSerializer):
class Meta:
model = Gps
fields = ('id','location','team')
view
class Gps_list(generics.ListCreateAPIView):
queryset = Gps.objects.all()
serializer_class = GpsSerializer
team = serializers.PrimaryKeyRelatedField(
read_only=True,
default=serializers.CurrentUserDefault()
)
There are two changes needed. First, team field definition should be moved to serializer class instead of view. Second, you should use Django's contrib.auth.User model instead of your definition of User, as because serializers.CurrentUserDefault() will bring request.user only. So you should remove your User definition and import that to your models.py:
from django.contrib.auth.models import User
Further steps would be to replace read_only=True with queryset=User.objects.all() to allow create.
I have a question regarding the table structure for User if I am extending its functionalities, using a MySQL database.
Given the models.py file
class LibraryUser(models.Model):
user_id = models.OneToOneField(User)
is_catalogue_subscriber = models.IntegerField(default=1)
is_research_subscriber = models.IntegerField(default=1)
library_membership_number = models.CharField(max_length=64)
I have a table structure for SQL
CREATE TABLE library_user(
user_id int(10) primary key
is_catalogue_subscriber integer(1) DEFAULT 1
is_research_subscriber = integer(1) DEFAULT 1
library_membership_number = varchar(16)
)
So now, when I fire up my server and access the accounts in the admin page, Django is throwing an error:
Exception Type: OperationalError
Exception Value:
(1054, "Unknown column 'library_user.id' in 'where clause'")
Use
user = models.OneToOneField(User, primary_key=True)
i.e. drop the _id in the attribute name.
In case you simply want to define a richer user model (i.e. add more attributes) you can
use a one-to-one relationship to a model containing the fields
for additional information. This one-to-one model is often called a
profile model, as it might store non-auth related information about a
site user. For example you might create a LibraryUser model:
from django.contrib.auth.models import User
class LibraryUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_catalogue_subscriber = models.IntegerField(default=1)
is_research_subscriber = models.IntegerField(default=1)
library_membership_number = models.CharField(max_length=64)
Assuming an existing LibraryUser Fred Smith who has both a User and LibraryUser model, you can access the related information using Django’s standard related model conventions:
>>> u = User.objects.get(username='fsmith')
>>> freds_department = u.libraryuser.department
Then to add the profile model’s fields to the user page in the admin do
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from my_user_profile_app.models import LibraryUser
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class LibraryUserInline(admin.StackedInline):
model = LibraryUser
can_delete = False
verbose_name_plural = 'libraryuser'
# Define a new User admin
class UserAdmin(UserAdmin):
inlines = (LibraryUserInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
All taken from the official docs
What you are missing is that by default django models automatically include an id field that maps to models.AutoField().
You need to specify that your DB table id is user_id instead of id.
https://docs.djangoproject.com/en/1.8/topics/db/models/#automatic-primary-key-fields
You want to make your user_id the primary key. It should work by adding primary_key=True to that field, like:
class LibraryUser(models.Model):
user_id = models.OneToOneField(User, primary_key=True)
is_catalogue_subscriber = models.IntegerField(default=1)
is_research_subscriber = models.IntegerField(default=1)
library_membership_number = models.CharField(max_length=64)