Get a dropdown of states in Django Admin - django

I made some basic models for a listing of a business, like so:
class Business(models.Models):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=225, blank=True)
address = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=150, blank=True)
state_id = models.IntegerField(null=True, blank=True)
zip = models.CharField(max_length=33, blank=True)
country = models.CharField(max_length=150, blank=True)
url = models.CharField(max_length=765, blank=True)
class States(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=96)
state_abbr = models.CharField(max_length=24, blank=True)
In the admin when I edit each business it shows the state_id field. But how do I connect it with the state model to show a select dropdown listing of the states?
Also, how do I show the state abbreviation in the view of a business?

An alternative that doesn't require a separate state table:
from django.contrib.localflavor.us.us_states import STATE_CHOICES
class Business(models.Models):
...
state = models.CharField(max_length=2, choices=STATE_CHOICES, null=True, blank=True)
...

Edit in 2015 (django 1.8)
you should check the django official localflavor repo: https://github.com/django/django-localflavor.
from localflavor.us.models import USStateField
class Business(models.Models):
…
state = USStateField(null=True, blank=True)
…
Some tests are available on the repo for this specific usage.
Docs available here.

You need to use a ForeignKey field.
Make the following changes.
class Business(models.Models):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=225, blank=True)
address = models.CharField(max_length=150, blank=True)
city = models.CharField(max_length=150, blank=True)
#state_id = models.IntegerField(null=True, blank=True)
# Define a new state field that creates a ForeignKey relationship with States
state = models.ForeignKey('States', null=True, blank=True)
zip = models.CharField(max_length=33, blank=True)
country = models.CharField(max_length=150, blank=True)
url = models.CharField(max_length=765, blank=True)
class States(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=96)
state_abbr = models.CharField(max_length=24, blank=True)
#Define the __unicode__ method, which is used by related models by default.
def __unicode__(self):
return self.state_abbr
By default ForeignKey fields append '_id' to the field name when creating the column name in the database. So, the new "state" field in the Business class will automatically use the column "state_id" that you've previously defined, unless you've changed some of the default behavior of Django.
For more on this:
Check out Django's documentation of
the ForeignKey field
Search "ForeignKey" on stackoverflow.com

Related

How to make a query across multiple models in Django

I'm using Django and I want to know how to get objects through 3 models
These are my models
class Participant(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
is_leader = models.BooleanField(default=False)
team = models.ForeignKey(Team, on_delete=models.CASCADE, null=True, related_name="participants")
application_date = models.DateField(auto_now_add=True, null=True)
resolution_date = models.DateField(null=True, blank=True)
accepted = models.BooleanField(default=False)
class Team(models.Model):
name = models.TextField(default="")
is_public = models.BooleanField(default=False)
institution = models.ForeignKey(Institution, on_delete=models.CASCADE, null=True, related_name='teams')
campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE, null=True, related_name='teams')
class Campaign(models.Model):
name = models.TextField(default="")
description = models.TextField(default="")
initial_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
end_date = models.DateTimeField(auto_now_add=False, null=True, blank=True)
qr_step_enabled = models.BooleanField(default=True)
image_resolution = models.IntegerField(default=800)
sponsor = models.ForeignKey(Sponsor, on_delete=models.CASCADE, null=True, related_name='campaigns')
I have the user through a request, and I want to get all campaigns of that user.
I tried doing it with for loops but I want to do it with queries
this is what I had:
user = request.user
participants = user.participant_set.all()
for participant in participants:
participant.team.campaign.name
is there a way to make a query through these models and for all participants?
A user can have many participants, and each participant has a Team, each team has a campaign
The best way is to merge the two modela Team and Campaign in one model.
Something as simple as this should work:
Campaign.objects.filter(team__participant__user=request.user)
The Django ORM is smart enough to follow foreign key relationships in both directions.
Thanks to Daniel W. Steinbrook to guide me to the answer, I had to do this to get the query:
Campaign.objects.filter(teams__participants__user__exact=request.user)

How to add ArrayField in Django?

my models.py
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_registered = models.IntegerField(default=0)
# registered_students = models.ManyToManyField(RegisteredNames, null=True, blank=True)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass_id = models.ForeignKey
I am creating a endpoint where when a user register himself his name will get added to registered_students , so i had made a registered students ManyToMany Field hoping it will get updated when a user is registered but then i understand that it will contain all the names that are present in the RegisteredNames Model meaning names registered across all the liveclasses but i want only the names that are registered for a particular liveclass in the field so i need a array like field which i think is not possible so please help me in improving my logic, how can i achieve it
The documentation and django tutorials are very good: https://docs.djangoproject.com/en/3.2/topics/db/models/ https://docs.djangoproject.com/en/3.2/intro/tutorial02/#creating-models
Your code is very close. You don’t need the many-to-many field, and you need to specify the type of the Foreign key relationship in the RegisteredNames. You can do this:
class LiveClass_details(models.Model):
standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE)
chapter_details = models.TextField(default='')
mentor_id = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
doubtClass = models.OneToOneField(DoubtClasses, on_delete=models.PROTECT, null=True, blank=True)
isDraft = models.BooleanField(default=True)
ratings = models.FloatField(default=0)
no_of_students_attended = models.IntegerField(default=0)
class Meta:
verbose_name_plural = 'LiveClass_details'
class RegisteredNames(models.Model):
name = models.CharField(max_length=100, unique=True)
liveclass = models.ForeignKey(LiveClass_details, on_delete=Models.CASCADE)
Then, simply:
name = RegisteredNames.objects.create(name="Dhruv", liveclass_id=1)
To get all the registered names from a liveclass_details:
names = LiveClass_details.objects.get(id=1).registerednames_set.all()
num_reg = len(names)

How to achieve dependent foreign keys listing in django-admin?

Suppose I have 3 models:- Address, Country, State
Address Model:
class AddressModel(BaseModel):
country = models.ForeignKey(CountryModel, null=True, blank=True, on_delete=models.PROTECT)
state = models.ForeignKey(StateModel, null=True, blank=True, on_delete=models.PROTECT)
city = models.CharField(max_length=200, null=True, blank=True)
pincode = models.CharField(max_length=6, null=True, blank=True)
address_line_1 = models.TextField(max_length=200, null=True, blank=True)
address_line_2 = models.TextField(max_length=200, null=True, blank=True)
Country Model:
class CountryModel(BaseModel):
name = models.CharField(max_length=100)
code = models.CharField(max_length=30)
and State Model:
class StateModel(BaseModel):
country = models.ForeignKey(CountryModel, on_delete=models.PROTECT)
name = models.CharField(max_length=100)
code = models.CharField(max_length=30)
While adding a new address in django admin, I want to show the list of only those states which belong to the selected country i.e I want to implement something like dependent foreign key list in django-admin.
I would like to achieve it without using jquery or ajax
How can I do that?

How do I get related Model field in Django using the Django Admin

I think that my problem here is Django specific and not necessarily a reflection on
my understanding of relational databases (hopefully).
I have a Django app that stores information on Contacts.
With that one table things seemed to work fine. When I wanted to categorize
the type of relationship - is this a professional relationship, family, friends, etc.
That's when things didn't show up like I wanted. I finally got the migration to work
with the new table.
I'm using python 3 with the latest version of django. I have a mysql
database. I want a one to many relationship, where one contact can
be characterized by many categories. When I work with the django admin
and try to enter a contact, I'm not seeing a field for entering relationship categories.
So, here is my models.py for the contacts app.
from django.db import models
class Resource(models.Model):
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
organization = models.CharField(max_length=60, null=True, blank=True)
street_line1 = models.CharField("Street Line 1", max_length=50, null=True, blank=True)
street_line2 = models.CharField("Street Line 2", max_length=50, null=True, blank=True)
city = models.CharField(max_length=40, null=True, blank=True)
state = models.CharField(max_length=40, null=True, blank=True)
zipcode = models.CharField(max_length=20, blank=True, null=True)
phone1 = models.CharField(max_length=20, null=True, blank=True)
phone2 = models.CharField(max_length=20, null=True, blank=True)
email = models.EmailField(max_length=60, null=True, blank=True)
website = models.URLField(max_length=90, null=True, blank=True)
def __str__(self):
return "%s %s \t%s" % (self.first_name, self.last_name, self.organization)
class Meta:
ordering = ('last_name',)
class Relationship(models.Model):
category = models.CharField(max_length=120)
resource = models.ForeignKey(Resource, related_name='category')
def __str__(self):
return self.category
class Meta:
ordering = ('category',)
Thanks in advance for any help,
Bruce

Foreign key relationship error in django

I am developing a django app where I use a legacy database. This database doesn't have primary key or constraint in any table. This are two of my models
class Provider(models.Model):
id_provider = models.IntegerField(blank=True, null=True, primary_key=True)
name = models.CharField(max_length=50, blank=True)
type = models.CharField(max_length=10, blank=True)
signed = models.CharField(max_length=15, blank=True)
currency = models.CharField(max_length=1, blank=True)
class Meta:
managed = False
db_table = 'mpc_proveedores'
class Master(models.Model):
id_provider = models.ForeignKey(Proveedor)
anio = models.IntegerField(blank=True, null=True)
mes = models.IntegerField(blank=True, null=True)
nombre_prov = models.CharField(max_length=50, blank=True)
tipo_conci = models.CharField(max_length=30, blank=True)
f_recepcion = models.DateField(blank=True, null=True)
e_recepcion = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'mpc_master'
I need to show a table based on the model Master and I need to display the name of the provider instead of the id_provider.
This is my view
def monitorViewV2(request):
table = MonitorTable(Master.objects.all())
RequestConfig(request).configure(table)
return render(request,'monitorv2.html',{'table': table})
When I try to see the template in the browser, the next error is showed
ORA-00904: "MPC_MASTER"."ID_PROVIDER_ID": invalid identifier
I don't know if the error is because I don't have relationships in the database or if I need to create a function in the view to display the name instead of the id_provider.
Can you bring me some snippet or link where I can take some ideas to resolve this issue
Thanks in advance
Django needs there to be an integer DB column for foreign key relations, which will hold the PK of the related object. It looks like that column is id_provider in this case, so you should specify that in your field declaration. I'd also use a different field name to avoid confusion:
provider = models.ForeignKey(Proveedor, db_column='id_provider')
The docs provide a little more context:
https://docs.djangoproject.com/en/1.7/ref/models/fields/#database-representation