How to solve this error? cause
whenever I search the student user I received an error,
error
admin.py
#admin.register(StudentsEnrollmentRecord)
class StudentsEnrollmentRecordAdmin(admin.ModelAdmin):
#inlines = [InLineSubject]
list_display = ('lrn', 'Student_Users', 'Education_Levels', 'Courses', 'Section', 'Payment_Type', 'Discount_Type' ,'School_Year')
#list_select_related = ('Student_Users')
ordering = ('Education_Levels','Student_Users__lrn')
list_filter = ('Student_Users','Education_Levels','Section','Payment_Type')
search_fields = ('Student_Users',)
def lrn(self, obj):
return obj.Student_Users.lrn
my models.py
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='students', on_delete=models.CASCADE,null=True)
School_Year = models.ForeignKey(SchoolYear, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Courses = models.ForeignKey(Course, related_name='+', on_delete=models.CASCADE, null=True, blank=True)
Section = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
Payment_Type = models.ForeignKey(PaymentType, related_name='+', on_delete=models.CASCADE, null=True)
Discount_Type = models.ForeignKey(Discount, related_name='+', on_delete=models.CASCADE, null=True,blank=True)
Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)
UPDATE models
class StudentProfile(models.Model):
lrn = models.CharField(max_length=500,null=True)
Firstname = models.CharField(max_length=500,null=True,blank=True)
Middle_Initial = models.CharField(max_length=500,null=True,blank=True)
Lastname = models.CharField(max_length=500,null=True,blank=True)
Education_Levels= models.ForeignKey(EducationLevel, on_delete=models.CASCADE,blank=True,null=True)
You need to provide a specific field from StudentProfile - currently your search field is
search_fields = ('Student_Users',)
which means only the model itself. You didn't post a schema of your StudentProfile, but for example if it contains a Lastname field, you should use it like this:
search_fields = ('Student_Users__Lastname',)
To include multiple fields you can do
search_fields = ('Student_Users__Lastname', 'Student_Users__Firstname',)
You could also do
search_fields = ('=Student_Users__Lastname',)
to match the last name "exactly", previous example checks whether the field contains the query string
Related
This is my code for the hotel website
models.py
class Rooms(models.Model):
room = models.BigIntegerField(verbose_name='Комната', unique=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name='Категория', related_name='wer')
room_bool = models.BooleanField(verbose_name='Статус', default=True)
price = models.BigIntegerField(verbose_name='Цена', null=True,blank=True)
class Registrations(models.Model):
room_num = models.ForeignKey(Rooms, on_delete=models.CASCADE, verbose_name='Номер', related_name='ertgdb',
limit_choices_to={'room_bool': True})
first_name = models.CharField(max_length=250, verbose_name='Имя')
last_name = models.CharField(max_length=250, verbose_name='Фамилия')
tel_num = models.BigIntegerField(verbose_name='Номер телефона')
img = models.FileField(verbose_name='Паспорт', null=True, blank=True)
visit_date = models.DateField(default=now, verbose_name='Дата прибытия')
leave_date = models.DateField(blank=True, null=True, help_text='Дата отбытия')
guest_count = models.IntegerField(default=1, verbose_name='Кол-во людей')
room_relevant = models.BooleanField(default=False, verbose_name='Статус')
price = models.BigIntegerField(verbose_name='Цена', default=100)
serializers.py
class RegistrationSer(serializers.ModelSerializer):
class Meta:
model = Registrations
fields = ('id', 'room_num', 'first_name', 'last_name', 'tel_num', 'img',
'visit_date', 'guest_count', 'room_relevant')
I need the room_num field (in the picture) to have not Id but room_num as in the Input form
SlugRelatedField doesn't work because I can't make POST PUT requests later
You can do the following:
class RegistrationSer(serializers.ModelSerializer):
room = serializers.CharField(source="room_num.room")
class Meta:
model = Registrations
fields = ('id', 'room', 'first_name', 'last_name', 'tel_num', 'img',
'visit_date', 'guest_count', 'room_relevant')
Will you help me to figure out why Django raises this error?
SolutionsForLanguagesApp.LanguageLevel: (fields.E336) The model is
used as an in termediate model by
'SolutionsForLanguagesApp.UserProfile.languages', but it does not
have a foreign key to 'UserProfile' or 'Language'.
I'm confused because, as you can see, there is a foreign key to Language in LanguageLevel already:
class LanguageLevel(models.Model):
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
class Meta:
unique_together = (('level', 'language'),)
Do you know what to do?
EDIT - Added UserProfile:
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='userprofile')
date_of_birth = models.DateField(null=True, blank=True)
telephone = models.CharField(max_length=40, null=True, blank=True)
IBAN = models.CharField(max_length=40, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
MARITAL_STATUS_CHOICES = (
('single', 'Single'),
('married', 'Married'),
('separated', 'Separated'),
('divorced', 'Divorced'),
('widowed', 'Widowed'),
)
marital_status = models.CharField(max_length=40, choices=MARITAL_STATUS_CHOICES, null=True, blank=True)
HOW_DO_YOU_KNOW_ABOUT_US_CHOICES = (
('coincidence', u'It was coincidence'),
('relative_or_friends', 'From my relatives or friends'),
)
how_do_you_know_about_us = models.CharField(max_length=40, choices=HOW_DO_YOU_KNOW_ABOUT_US_CHOICES, null=True,
blank=True)
# TRANSLATOR ATTRIBUTES
is_translator = models.BooleanField(default=False)
# language_tuples = models.ManyToManyField(LanguageTuple,blank=True)
languages = models.ManyToManyField(Language, through='LanguageLevel')
rating = models.IntegerField(default=0)
number_of_ratings = models.BigIntegerField(default=0)
def __unicode__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
def __str__(self):
return '{} {}'.format(self.user.first_name, self.user.last_name)
Your LanguageLevel model is missing a ForeignKey to the UserProfile:
class LanguageLevel(models.Model):
language = models.ForeignKey(Language)
level = models.ForeignKey(Level)
# Add Foreign Key to UserProfile
userprofile = models.ForeignKey(UserProfile)
class Meta:
unique_together = (('level', 'language'),)
Also I'm not sure that the unique_together constraint is what you want - it will mean that only one user can have any one combination of language/level. A more likely constraint would be ('userprofile', 'language') so that a language can only be mapped to a user once.
My models:
class StudentsEnrollmentRecord(models.Model):
Student_Users = models.ForeignKey(StudentProfile, related_name='+', on_delete=models.CASCADE,null=True)
School_Year = models.ForeignKey(SchoolYear, on_delete=models.CASCADE, null=True, blank=True)
Courses = models.ForeignKey(Course, on_delete=models.CASCADE, null=True, blank=True)
Section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True,blank=True)
Payment_Type = models.ForeignKey(PaymentType, related_name='paymenttype', on_delete=models.CASCADE, null=True)
Education_Levels = models.ForeignKey(EducationLevel, related_name='gradelevel', on_delete=models.CASCADE,null=True)
Discount_Type = models.ForeignKey(Discount, on_delete=models.CASCADE,null=True)
Remarks = models.TextField(max_length=500,null=True)
def __str__(self):
suser = '{0.Student_Users} {0.Education_Levels}'
return suser.format(self)
what i want to search:
class StudentsEnrolledSubject(models.Model):
Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,null=True)
Subject_Section_Teacher = models.ForeignKey(SubjectSectionTeacher, related_name='+', on_delete=models.CASCADE,null=True)
def __str__(self):
suser = '{0.Students_Enrollment_Records} {0.Subject_Section_Teacher}'
return suser.format(self)
Image:
Can i search here if i select what ever i want in section, my search will appear below?
Do you guys have an idea or better solution?
admin.py
from django.contrib import admin
from yourappname.models import Question
class QuestionAdmin(admin.ModelAdmin):
search_fields = ['question_text'] # select which field you want to search
list_filter = ['Remarks']
https://docs.djangoproject.com/en/2.2/ref/contrib/admin/
here is my model, serializer and output but when i want to create a new page it ask me to add a whole new user as its just a foreign-key it need to be a number like 1 (user id) and same in the case of categories how can i solve it.... help me please
serializers.py
class TeamMembersSerializer(serializers.ModelSerializer):
class Meta:
model = TeamMembers
fields = [
'user',
'page',
]
depth = 1
class SocialAccountsSerializer(serializers.ModelSerializer):
social = SocialCatSerializer()
class Meta:
model = SocialAccounts
fields = [
'page',
'social',
'link'
]
depth = 1
class PageImageSerializer(serializers.ModelSerializer):
class Meta:
model = PageImages
fields = [
'page',
'image',
]
depth = 1
class PageSerializer(serializers.ModelSerializer):
owner = UserSerializer()
catagory = BusinessCatSerializers()
business_type = BusinessTypeSerializer()
TeamMembers = TeamMembersSerializer(read_only=True)
social_accounts = SocialAccountsSerializer(read_only=True)
images = PageImageSerializer(read_only=True)
class Meta:
model =Page
fields = [
'id',
'owner',
'catagory',
'name',
'username',
'images',
'start_date',
'business_type',
'contect_number',
'email_address',
'website',
'TeamMembers',
'social_accounts',
'about',
'impression',
'Awards',
'Product',
'privacy_policy',
'is_active',
]
Models.py
class Page(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
catagory = models.ForeignKey(BusinessCatagories, on_delete=models.CASCADE, null=True, blank=True, default=None)
name = models.CharField(max_length=254, unique=True ,default=None, blank=True)
username = models.CharField(max_length=254, unique=True, blank=True)
start_date = models.DateTimeField(auto_now_add=True)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE, null=True, blank=True, default=None)
contect_number = models.CharField(max_length=254, default=None, blank=True)
email_address = models.EmailField(default=None, blank=True)
website = models.URLField(default=None, blank=True)
about = models.TextField(default=None, blank=True)
impression = models.TextField(default=None, blank=True)
Awards = models.CharField(max_length=254, default=None, blank=True)
Product = models.CharField(max_length=254, default=None, blank=True)
privacy_policy = models.URLField(default=None, blank=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
class TeamMembers(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, default=None, blank=True)
page = models.ForeignKey(Page, on_delete=models.CASCADE, default=None, blank=True)
def __str__(self):
return self.user.name
class SocialAccounts(models.Model):
page = models.ForeignKey(Page, on_delete=models.CASCADE, default=None, blank=True)
social = models.ForeignKey(SocialCats, on_delete=models.CASCADE, default=None, blank=True)
link = models.URLField(default=None, blank=True)
def __str__(self):
return self.link
class PageImages(models.Model):
page = models.ForeignKey(Page, on_delete=models.CASCADE, default=None, blank=True)
image = models.ImageField(default=None, blank=True, upload_to=settings.MEDIA_ROOT)
def __str__(self):
return self.page.name
output is this but i need images field TeamMember field in it but its not appearing plus it want me to add a new user instead of asking for Foreignkey "id"
What you want is to use Primary key related field. It helps you to represent the target of the relationship using its primary key.
It should look somewhat like this.
Note: Mind the typo for any name
class PageSerializer(serializers.ModelSerializer):
owner = serializers.PrimaryKeyRelatedField(queryset = User.objects.all())
catagory = serializers.PrimaryKeyRelatedField(queryset = BuisnessCat.objects.all())
business_type = BusinessTypeSerializer()
TeamMembers = TeamMembersSerializer(read_only=True)
social_accounts = SocialAccountsSerializer(read_only=True)
images = PageImageSerializer(read_only=True)
You can read more about PrimaryKeyRelatedField here.
Now whenever creating any Page, all you need to supply are primary key for owner and category.
You are looking for Writable Nested Serializer.
In short you have to override create() method of PageSerializer
class PageSerializer(serializers.ModelSerializer):
....
....
your code
def create(self, validated_data):
# pop data of every related fields like "owner", "cateagory" etc from validated_data
owner = validated_data.pop("owner")
owner = User.objects.create(**owner)
category = validated_data.pop("category")
# create or retrieve category instance ,as above
...
...
...
# finally
return Page.objects.create(**validated_data,owner=owner,category=category, and other related instances)
this is my code above.
model.py
class Produto(models.Model):
usuario = models.ForeignKey(User, null=True, blank=True)
nome = models.CharField(max_length=255)
descricao = models.TextField(null=True, blank=True, verbose_name="Descrição")
slug = models.SlugField()
class Categoria(MPTTModel):
produto = models.ManyToManyField(Produto, null=True, blank=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children',verbose_name="Categoria Pai")
nome = models.CharField(max_length=255)
descricao = models.CharField(max_length=255, null=True, blank=True)
slug = models.SlugField()
ativo = models.BooleanField(default=True)
mostra_menu = models.BooleanField(default=False)
ordem_menu = models.IntegerField(default=0)
admin.py
class CategoriaProdutoInline(admin.TabularInline):
model = Categoria.produto.through
class ProdutoAdmin(admin.ModelAdmin):
list_display = ('__unicode__','sku','descricao_curta', 'preco', 'preco_desconto', 'ativo', 'categorias', 'link')
inlines = [CategoriaProdutoInline, ImagemInLine, TagInLine]
search_fields = ('nome', 'sku', 'categoria__nome')
list_filter = ('preco', 'created_at')
prepopulated_fields = {"slug": ('nome',)}
readonly_fields = ['link']
fields = ('usuario','nome','descricao','ativo','preco','preco_desconto','slug')
Actually, the product update admin looks like this.
Insert Product Admin Page
I´ve tried to use some implementations like TreeNodeChoiceField as seem here but not works