Django admin site customization - python

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/

Related

How to filter Many to Many field in django admin page using a foreign key value?

I am trying to filter my many to many variation fields with respect to the product. means, I only want the variations related to the current product to show in the admin page. now its showing all the variations available for every product.
I added formfield_for_manytomany() function to my admin.py but how can I get the current product(id) in the cart or order to filter the variations?
most of the questions in stack overflow Is based on the current user, which is easy to get? but how should I get the specific product(id) that is opened in the admin panel.
admin.py
from django.contrib import admin
from .models import *
from products.models import Variation
class CartAdmin(admin.ModelAdmin):
list_display = ('cart_id', 'date_created')
class CartItemAdmin(admin.ModelAdmin):
list_display = ('user','cart', 'product', 'quantity','is_active')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "variation":
product = Products.objects.get(id='??') # how I get the current product in the cart or order
kwargs["queryset"] = Variation.objects.filter(product=product.id)
return super().formfield_for_manytomany(db_field, request, **kwargs)
admin.site.register(Cart, CartAdmin)
admin.site.register(CartItem, CartItemAdmin)
CartItem Model
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation = models.ManyToManyField(Variation, blank=True)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
created_date = models.DateTimeField(auto_now_add=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
Product and Variation Model
class Products(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = AutoSlugField(populate_from='name', max_length=100, unique=True)
isbn = models.CharField(max_length=20, unique=True, blank=True, null=True)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
language = models.ForeignKey(Language, on_delete=models.SET_NULL, null=True)
author = models.CharField(max_length=100)
Publisher = models.CharField(max_length=100, blank=True, default=None)
release_date = models.DateField(blank=True, null=True, default=None)
price = models.IntegerField(default=None)
stock = models.IntegerField(default=None)
is_available = models.BooleanField(default=True)
cover_image = models.ImageField(upload_to='images/products')
image1 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image2 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
image3 = models.ImageField(upload_to='images/products', blank=True, default=None, null=True)
description = models.TextField(max_length=2000, blank=True, default=None)
create_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
number_of_pages = models.IntegerField(blank=True, null=True)
weight = models.IntegerField(blank=True, null=True)
width = models.IntegerField(blank=True, null=True)
height = models.IntegerField(blank=True, null=True)
spine_width = models.IntegerField(blank=True, null=True)
class Meta:
verbose_name = 'Product'
verbose_name_plural = 'Products'
def get_url(self):
return reverse('product-view', args=[self.slug])
def __str__(self):
return self.name
class Variation(models.Model):
product = models.ForeignKey(Products, on_delete=models.CASCADE)
variation_category = models.CharField(max_length=100, choices=variation_category_choice)
variation_value = models.CharField(max_length=100, choices=variation_value_choice)
is_available = models.BooleanField(default=True)
date_added = models.DateTimeField(auto_now_add=True)
objects = VariationManager()
def __str__(self):
return self.variation_value

integerity error in django(i think its about that new foregn key)

im have post model and a profile model on profile model i have a OneToOneField this is my profile model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
GENDER_CHOICES = [('boy', 'پسر'), ('girl', 'دختر'), ('i prefer not to say', 'ترجیح میدهم نگویم')]
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField(upload_to='profile_pictures', blank=True, default='default.jpg')
name = models.CharField(max_length=30)
age = models.IntegerField(default="0")
birth_day = models.CharField(max_length=30)#DateField(blank=True)
gender = models.CharField(max_length=20, choices=GENDER_CHOICES)
address = models.CharField(max_length=30, blank=True, default="---")
bio = models.TextField(max_length=300, blank=True, default="---")
phone = models.IntegerField(blank=True, null=True)
skills = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorites = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_books = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_movies = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_musics = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
favorite_sports = models.TextField(max_length=200, blank=True, default="ترجیح میدهم نگویم")
and this is my post model:
from django.db import models
# from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
from taggit.managers import TaggableManager
from user.models import Profile
class Post(models.Model):
STATUS_CHOICES = [('published', 'published'), ('draft', 'draft')]
title = models.CharField(max_length=60)
slug = models.CharField(max_length=120, unique=True)
image = models.ImageField(blank=True, upload_to="posts_images", null=True)
image_alt = models.CharField(max_length=35, blank=True, null=True)
body = models.TextField()
date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
publish_date = models.DateTimeField(default=timezone.now)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published')
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
tags = TaggableManager()
published_manager = PublishedManager()
def __str__(self):
return self.title
class Meat:
ordering = ('-publish_date',)
def get_absolute_url(self):
return reverse('post:post_details', args=[self.slug,])
and i can change the previuos posts and save them but i can't add a new post get this error
IntegrityError at /admin/post/post/add/
NOT NULL constraint failed: post_post.owner_id
you can see that owner_id before i add the profile model i connect djangouser with a foregnkey with post model and its variable was 'owner' but now i deleted but i still get it's error and also when i migrated the new profile i get somethings like error but they was'nt error they was some things like warnings or something like that thanks for helping

Django search_field

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

Am I able to classify models with folders on django admin dashboard?

I'm fresh of the django boat, working on a project that need to do 'one to many'. Here's what I'm trying to make my admin dashboard look like:
Patients
Patient001
Profile
Record
Inputoutput
Day1
Day2
Patient002
Profile
Record
Inputoutput
Day1
The "Patient", "Profile", "Record", "Inputoutput" are all models and related with a foreign key "name" in "Patient" model. I hope to achieve to add or edit the data in each model by clicking in folders on django admin dashboard. How should I do this. I've been googling for days. What I found that looks like I'm looking for is a "custom django admin dashboard", but still not sure how to do this. Anyone has an idea? =)
What I want to achieve is:
first>> create a "Patient" model (admin create a Patient Folder shows on dashboard)
then>> create a "Profile" model (click into the Patient Folder we just create and add a Profile model)
I want all these created models to show in levels of folders on admin, and you can just click in to the folders to add or edit instead of all of the registered models showing together on the very first page of admin.
Here are my models:
--patient.py--
from django.db import models
class Patient(models.Model):
name = models.CharField(default="", max_length=200)
def __str__(self):
return self.name
class Meta:
app_label = 'vsform'
--profile.py--
from django.db import models
from django.utils import timezone
import datetime
class Profile(models.Model):
patient = models.ForeignKey('Patient', on_delete=models.CASCADE)
name = models.CharField(max_length=200)
record_number = models.CharField(max_length=200)
bed_number = models.CharField(max_length=200)
gender = models.CharField(max_length=1, choices=(('男', '男'), ('女', '女')))
operation_date = models.DateTimeField(default=timezone.now)
chart_start_time = models.IntegerField(default=4)
class Meta:
app_label = 'vsform'
def __str__(self):
return self.name
--record.py--
from django.db import models
class Record(models.Model):
patient = models.ForeignKey('Patient', on_delete=models.CASCADE)
blood_pressure_day1_1 = models.CharField(max_length=200, blank=True)
blood_pressure_day1_2 = models.CharField(max_length=200, blank=True)
blood_pressure_day2_1 = models.CharField(max_length=200, blank=True)
blood_pressure_day2_2 = models.CharField(max_length=200, blank=True)
blood_pressure_day3_1 = models.CharField(max_length=200, blank=True)
blood_pressure_day3_2 = models.CharField(max_length=200, blank=True)
blood_pressure_day4_1 = models.CharField(max_length=200, blank=True)
blood_pressure_day4_2 = models.CharField(max_length=200, blank=True)
blood_pressure_day5_1 = models.CharField(max_length=200, blank=True)
blood_pressure_day5_2 = models.CharField(max_length=200, blank=True)
height_day1 = models.CharField(max_length=200, blank=True)
weight_day1 = models.CharField(max_length=200, blank=True)
height_day2 = models.CharField(max_length=200, blank=True)
weight_day2 = models.CharField(max_length=200, blank=True)
height_day3 = models.CharField(max_length=200, blank=True)
weight_day3 = models.CharField(max_length=200, blank=True)
height_day4 = models.CharField(max_length=200, blank=True)
weight_day4 = models.CharField(max_length=200, blank=True)
height_day5 = models.CharField(max_length=200, blank=True)
weight_day5 = models.CharField(max_length=200, blank=True)
special_drug1 = models.CharField(max_length=200, blank=True)
special_drug2 = models.CharField(max_length=200, blank=True)
special_drug3 = models.CharField(max_length=200, blank=True)
special_drug4 = models.CharField(max_length=200, blank=True)
exam1 = models.CharField(max_length=200, blank=True)
exam2 = models.CharField(max_length=200, blank=True)
exam3 = models.CharField(max_length=200, blank=True)
exam4 = models.CharField(max_length=200, blank=True)
exam5 = models.CharField(max_length=200, blank=True)
exam6 = models.CharField(max_length=200, blank=True)
exam7 = models.CharField(max_length=200, blank=True)
exam8 = models.CharField(max_length=200, blank=True)
exam9 = models.CharField(max_length=200, blank=True)
exam10 = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.patient.name
class Meta:
app_label = 'vsform'
--inputoutput.py--
from django.db import models
class InputOutput(models.Model):
patient = models.ForeignKey('Patient', on_delete=models.CASCADE)
def __str__(self):
return self.patient.name
class Meta:
app_label = 'vsform'
--day.py--
from django.db import models
class Day(models.Model):
inputoutput = models.ForeignKey('InputOutput', on_delete=models.CASCADE)
day_number = models.SmallIntegerField(default=0)
injection_7to3 = models.IntegerField(default=0)
injection_3to11 = models.IntegerField(default=0)
injection_11to7 = models.IntegerField(default=0)
food_7to3 = models.IntegerField(default=0)
food_3to11 = models.IntegerField(default=0)
food_11to7 = models.IntegerField(default=0)
transfusion_7to3 = models.IntegerField(default=0)
transfusion_3to11 = models.IntegerField(default=0)
transfusion_11to7 = models.IntegerField(default=0)
excrete_times_7to3 = models.SmallIntegerField(default=0)
excrete_times_3to11 = models.SmallIntegerField(default=0)
excrete_times_11to7 = models.SmallIntegerField(default=0)
urine_7to3 = models.IntegerField(default=0)
urine_3to11 = models.IntegerField(default=0)
urine_11to7 = models.IntegerField(default=0)
vomit_7to3 = models.IntegerField(default=0)
vomit_3to11 = models.IntegerField(default=0)
vomit_11to7 = models.IntegerField(default=0)
drain_7to3 = models.IntegerField(default=0)
drain_3to11 = models.IntegerField(default=0)
drain_11to7 = models.IntegerField(default=0)
def __str__(self):
return "Day " + str(self.day_number)
class Meta:
app_label = 'vsform'
And here's admin.py
--admin.py--
from django.contrib import admin
from .models.patient import Patient
admin.site.register(Patient)

How to implement ManyToManyField as Checkboxes using django-mptt Structure in Admin?

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

Categories

Resources