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

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)

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

django error (no such column: projects_review.project_id)

I can't open my Review table, here's the models of code:
This is the `Project` model:
class Project(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
def __str__(self):
return self.title
And this is the Review model:
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False)
def __str__(self):
return self.title
but I can't open my Review table on admin panel (OperationalError at /admin/projects/review/)
Here's the error details:
I make migrations and do migrate:

Django: How to import model from same app?

I've an app called lists.
This has 3 main models: List, ListItem and School.
Every list could be related to 1 school, or this field could be empty.
But when I'm trying to update my model List to have a school field I'm getting:
ImportError: cannot import name 'School' from 'lists.models' (D:\web_proyects\scolarte\lists\models.py)
(scolarte)
Even thought both models are in the same models.py file.
I've tried:
from .models import School
And:
from lists.models import School
lists/models.py:
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
You don't need to import School since its already in the same model. However you do need to define School first before you can then reference it in another class in the same model file. Update your model so School is defined before List
from django.db import models
from products.models import Product
from roles.models import User
from .models import School
# Create your models here.
class School(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=False)
address_reference = models.CharField(max_length=100, blank=False)
provincia = models.CharField(max_length=100, blank=False, null=True)
canton = models.CharField(max_length=100, blank=False, null=True)
parroquia = models.CharField(max_length=100, blank=False, null=True)
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.name)
class List(models.Model):
LISTA_STATUS = (
('recibida_pagada', 'Recibida y pagada'),
('recibida_no_pagada', 'Recibida pero no pagada'),
('en_revision', 'En revision'),
('en_camino', 'En camino'),
('entregada', 'Entregada'),
('cancelada', 'Cancelada')
)
lista_id = models.CharField(max_length=100)
name = models.CharField(max_length=100)
user = models.OneToOneField(User, on_delete=models.CASCADE)
school = models.OneToOneField(School, on_delete=models.CASCADE)
status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada')
created_at = models.DateTimeField(auto_now_add=True)
modified_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['created_at']
def __str__(self):
return str(self.id)
class ListItem(models.Model):
lista = models.ForeignKey(List, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
comment = models.CharField(max_length=100, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
step_two_complete = models.BooleanField(default=False)
def sub_total(self):
return int(self.product.price)

How can I access objects in a django model composed of two foreign keys?

These are the relevant classes of my app. I want basically understand if the a certain user (form AuthUser) is linked to a business (from BusinessInformation) by looking at UserBusinessInformation. Thanks
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=30)
last_name = models.CharField(max_length=30)
email = models.CharField(max_length=254)
is_staff = models.IntegerField()
is_active = models.IntegerField()
date_joined = models.DateTimeField()
class Meta:
managed = False
db_table = 'auth_user'
class BusinessInformation(models.Model):
business_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
lat = models.CharField(max_length=255)
lng = models.CharField(max_length=255)
formatted_address = models.CharField(max_length=255, blank=True, null=True)
locality = models.CharField(max_length=255, blank=True, null=True)
country = models.CharField(max_length=255, blank=True, null=True)
administrative_area_level_5 = models.CharField(max_length=255, blank=True, null=True)
administrative_area_level_4 = models.CharField(max_length=255, blank=True, null=True)
administrative_area_level_3 = models.CharField(max_length=255, blank=True, null=True)
administrative_area_level_2 = models.CharField(max_length=255, blank=True, null=True)
administrative_area_level_1 = models.CharField(max_length=255, blank=True, null=True)
postal_code = models.CharField(max_length=45, blank=True, null=True)
route = models.CharField(max_length=255, blank=True, null=True)
street_number = models.CharField(max_length=45, blank=True, null=True)
phone = models.CharField(max_length=255, blank=True, null=True)
phone2 = models.CharField(max_length=255, blank=True, null=True)
phone3 = models.CharField(max_length=255, blank=True, null=True)
email = models.CharField(max_length=255, blank=True, null=True)
email2 = models.CharField(max_length=255, blank=True, null=True)
email3 = models.CharField(max_length=255, blank=True, null=True)
website = models.CharField(max_length=255, blank=True, null=True)
facebook = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'business_information'
class UserBusinessInformation(models.Model):
user = models.ForeignKey(AuthUser, models.DO_NOTHING)
business = models.ForeignKey(BusinessInformation, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'user_business_information'
When I try to access to UserBusinessInformation in my views, I do not manage neither using _set.
def school(request, schoolname):
school_searched = BusinessInformation.objects.get(name=schoolname)
user_linked = school_searched.userbusinessinformation_set.all()
I miss the many to many field:
class BusinessInformation(models.Model):
business_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255)
users = models.ManyToManyField(AuthUser,
through='UserBusinessInformation')
...
Then, in your view:
def school(request, schoolname):
school_searched = BusinessInformation.objects.get(name=schoolname)
user_linked = school_searched.users.all()
Quoting Extra fields on many-to-many relationships django docs:
For these situations, Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary.
Let me finish with a little advice, it is true, 'These are the relevant classes of my app', but you can illustrate this sample with just few fields. Learn about How to create a Minimal, Complete, and Verifiable example
[if you want access a field that’s a ForeignKey, you’ll get the related model object just like]
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()`enter code here`
def __str__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __str__(self):
return '%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __str__(self):
return self.title
[you can access like that.... ]
b = Book.objects.get(id=50)
b.publisher
b.publisher.website

Restrict form field choices based on previous model choice in Django

I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this:
I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand.
So far I have this:
models.py
class Race(models.Model):
race_name = models.CharField(max_length=200)
race_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M')
race_speed = models.IntegerField(
default=30)
race_lang = models.CharField(max_length=200, null=True, blank=True)
race_str = models.IntegerField(default=0, null=True, blank=True)
race_dex = models.IntegerField(default=0, null=True, blank=True)
race_con = models.IntegerField(default=0, null=True, blank=True)
race_int = models.IntegerField(default=0, null=True, blank=True)
race_wis = models.IntegerField(default=0, null=True, blank=True)
race_cha = models.IntegerField(default=0, null=True, blank=True)
skill_spend = models.IntegerField(default=0, null=True, blank=True)
race_extra = models.TextField(max_length=2000, blank=True, null=True)
race_source = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.race_name
class Meta:
verbose_name = 'Race'
verbose_name_plural = 'Races'
class Subrace(models.Model):
sub_name = models.CharField(max_length=200)
sub_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M', null=True)
sub_speed = models.IntegerField(
default=30, null=True)
sub_lang = models.CharField(max_length=200, null=True, blank=True)
sub_str = models.IntegerField(default=0, null=True, blank=True)
sub_dex = models.IntegerField(default=0, null=True, blank=True)
sub_con = models.IntegerField(default=0, null=True, blank=True)
sub_int = models.IntegerField(default=0, null=True, blank=True)
sub_wis = models.IntegerField(default=0, null=True, blank=True)
sub_cha = models.IntegerField(default=0, null=True, blank=True)
sub_extra = models.TextField(max_length=2000, null=True, blank=True)
sub_parent = models.ForeignKey(Race, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.sub_name
class Meta:
verbose_name = 'Subrace'
verbose_name_plural = 'Subraces'
class Hero(models.Model):
def roll_stats():
d6 = die.Dice(6)
list_stats = d6.roll(4)
list_stats.sort()
add = sum(list_stats[1:4])
return add
hero_name = models.CharField(max_length=200)
author = models.ForeignKey(User, null=True)
hero_subrace = models.ForeignKey(
Subrace, on_delete=models.CASCADE, null=True, blank=True)
pub_date = models.DateTimeField('date published', blank=True, null=True)
hero_klass = models.ForeignKey(Klass, on_delete=models.CASCADE, null=True)
hero_race = models.ForeignKey(Race, on_delete=models.CASCADE)
background = models.ForeignKey(
Background, on_delete=models.CASCADE, null=True)
health = models.IntegerField(blank=True, null=True)
hero_exp = models.IntegerField(default=0, null=True)
hero_alignment = models.ForeignKey(Alignment, blank=True, null=True)
hero_str = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_dex = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_con = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_int = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_wis = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_cha = models.IntegerField(default=roll_stats, null=True, blank=True)
def save(self, *args, **kwargs):
"Returns a hero's hp"
die_str = str(self.hero_klass.hit_dice)
die_nums = die_str.split("d")
die_val = int(die_nums[1])
die_roll = int(die_nums[0])
hp_die = die.Dice(die_val)
results = hp_die.roll(die_roll)
self.health = sum(results)
super(Hero, self).save(*args, **kwargs)
def __str__(self):
return self.hero_name
def get_absolute_url(self):
return reverse('hero.views.detail', args=[str(self.id)])
class Meta:
verbose_name = 'Hero'
verbose_name_plural = 'Heroes'
views.py
def new_hero(request):
user = request.user
if request.method == "POST":
form = HeroForm(request.POST)
if form.is_valid():
hero = form.save(commit=False)
hero.author = request.user
hero.save()
return redirect('detail', hero.pk)
else:
form = HeroForm()
return render(request, 'new_hero.html', {'form': form, 'user': user})
forms.py
class HeroForm(forms.ModelForm):
class Meta:
model = Hero
fields = ['hero_name', 'hero_race', 'hero_subrace',
'hero_klass', 'hero_exp', 'health', 'background',
'hero_str', 'hero_dex', 'hero_con', 'hero_int',
'hero_wis', 'hero_cha', 'hero_alignment']
def __init__(self, *args, **kwargs):
super(HeroForm, self).__init__(*args, **kwargs)
for fieldname in ['hero_str', 'hero_dex', 'hero_con', 'hero_int', 'hero_wis', 'hero_cha']:
self.fields[fieldname].disabled = True
race = Race.objects.all()
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
I have trialled a few different techniques, but this is where I am now. This:
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
is my most recent addition to my app. At the hero creation screen I am hit with a blank box of choices, as opposed to the full unrestricted list without the loop or queryset.
Basically I'm hoping that someone has some advice for me on a method I may be overlooking, or something that I've missed, or simply not found yet. Also please feel free to critique the rest of the code, like I said this is my first Django App :). Also my first Stack Overflow question, so thanks :)
For anyone that is wondering, I used django-smart-selects to solve my problem.
base.html
<script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
<script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script>
I added the above html to my {% load staticfiles %} call.
and changed models.py:
models.py
from smart_selects.db_fields import ChainedForeignKey
class Hero(models.Model):
....
race = models.ForeignKey(Race, on_delete=models.CASCADE)
subrace = ChainedForeignKey(Subrace,
chained_field="race",
chained_model_field="race",
show_all=False,
auto_choose=True,
blank=True,
null=True)
Now I have a subrace field that is dynamically update when the user chooses a Race.

Categories

Resources