Add Depandent drop down list for Django admin user - django

I have created 4 models in my django Country, State, and City, and also add them in admin.site.register How Can I add dependent drop down list for Country State City for admin user whenever user try to create Aplications object, they get state name list depends on Country name selected by admin user, and also for city.
Models.py
from django.db import models
from django.db.models import ForeignKey
from multiselectfield import MultiSelectField
class Country(models.Model):
name = models.CharField(max_length=250)
phone_code = models.CharField(max_length=250)
currency = models.CharField(max_length=250)
def __str__(self):
return self.name
class State(models.Model):
name = models.CharField(max_length=250)
country = models.ForeignKey(to=Country, on_delete=models.CASCADE)
def __str__(self):
return self.name
class City(models.Model):
state = models.ForeignKey(to=State, on_delete=models.CASCADE)
name = models.CharField(max_length=250)
def __str__(self):
return self.name
class Applications(models.Model):
country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True)
state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True)
city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=20)
phone_number = models.IntegerField()
email_id = models.EmailField()
home_address = models.CharField(max_length=255, blank=True, null=True)
birthdate = models.DateField(null=True, blank=True)
current_company = models.TextField(max_length=250, blank=True, null=True)
def __str__(self):
return str(self.name)

they get state name list depends on Country name selected by admin user, and also for city
Since you said a dropdown list, I will suggest switching over to a multiple choice field where the choices will be set to a certain range of values and will appear as a dropdown in the admin dashboard.

Related

Django find common instances data in two models

I have models like:
class Hospital(models.Model):
name = models.CharField(max_length=200, unique=True)
manager_name = models.CharField(max_length=200, default='')
manager_id = models.CharField(max_length=200)
def __str__(self):
return f'{self.name}'
class Sick(models.Model):
name = models.CharField(max_length=200, default='')
nationalID = models.CharField(max_length=200)
illName = models.CharField(max_length=200)
hospital = models.ForeignKey(Hospital, related_name='sicks', on_delete=models.DO_NOTHING)
def __str__(self):
return f'({self.name}, {self.nationalID})'
class Employee(models.Model):
name = models.CharField(max_length=200, default='')
nationalID = models.CharField(max_length=200)
company = models.ForeignKey(Company, related_name='employees', on_delete=models.CASCADE)
def __str__(self):
return f'({self.name}, {self.nationalID})'
views:
#api_view(['POST'])
def get_sick_employee_by_hospital(request):
pass
and a serializer like :
from rest_framework import serializers
class NameSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=200, allow_null=False)
my problem is :
my view get_sick_employee_by_hospital() receives a hospital name and it must return all sick peoples that are employees and They have visited that hospital, in a dictionary with keys 1,2,3,..., n and values like "(name, nationalID)".
Pay attention that it does not matter which value is assigned to which key.
What is the best way to do that ? how can i get all sick peoples that are employees and They have visited a hospital?

Error for my model with ManyToManyField in Django

I am working for a personal project that is using an API and having user authentication with JWT (but used in serializer). I wanted to implement ManyToManyField for user and city but it doesn't work properly. This is the extended model I have found and django aggregation . I want that the UserSearchLocation to store the City and when logged in to see the city, while other users will not see it until the search same city.
models.py
class UserSearchLocation(models.Model):
city_name = models.CharField(max_length=85, blank=False)
def __str__(self):
return self.city_name
class City(models.Model):
user_searched_locations = models.ManyToManyField(User,
through='UsersLocations',
through_fields=('city', 'user'),
related_name="my_cities",
blank=True)
id = models.AutoField(primary_key=True, editable=False)
location = models.CharField(max_length=85)
country = models.CharField(max_length=85, blank=True)
country_code = models.CharField(max_length=2, blank=True)
latitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
longitude = models.DecimalField(max_digits=6, decimal_places=4,
null=True, blank=True)
zip_code = models.PositiveIntegerField(default=0)
#users_location = models.ManyToManyField(UserSearchLocation)
def __str__(self):
return f'{self.location}, {self.country_code}'
def save(self, *args, **kwargs):
self.location = self.location.capitalize()
self.country = self.country.capitalize()
self.country_code = self.country_code.capitalize()
return super(City, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'cities'
unique_together = ("location", "country_code")
class UsersLocations(models.Model):
id = models.AutoField(primary_key=True, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
city = models.ForeignKey(City,
on_delete=models.CASCADE,
related_name='locations_by_users',
null=True)
To add in localhost/admin/ a City works, but when to add a UserSearchLocation I have this error:
Exception Value:
column base_usersearchlocation.user_id does not exist
LINE 1: SELECT "base_usersearchlocation"."user_id", "base_usersearch...
Your error says the city.location doesn't exist - location is a CharField on your City model - are you sure you've run migrations and don't have any naming conflicts?

How do I show only a subset of options in a Django dropdown menu

I have an app that allows users to signup and register for courses (from a 'TrainingInstance' model). These events have names etc and are categorised as Past or Current in the database (in the 'Training' model). When I show the BuildOrderForm in my template, I want only options for Current trainings to be shown in the dropdown menu. How can this be done in Django without javascript or Ajax?
I have the following form in forms.py:
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
And the following models in models.py:
class Training(models.Model):
""" Model which specifies the training category (name) and whether they are Past or Present"""
YEAR = (
('current', 'current'),
('past', 'past'),
)
name = models.CharField(max_length=200, null=True)
year= models.CharField(max_length=200, null=True, choices=YEAR, default='current')
def __str__(self):
return self.name
class TrainingInstance(models.Model):
""" Creates a model of different instances of each training ( May 2021 etc) """
name = models.CharField(max_length=200, null=True, blank=True)
venue = models.CharField(max_length=200, null=True, blank=True)
training = models.ForeignKey(Training, on_delete= models.CASCADE, null = True)
training_month = models.CharField(max_length=200, null=True, blank=True)
participant_date = models.CharField(max_length=20, null=True, blank=True)
staff_date = models.CharField(max_length=20, null=True, blank=True)
graduation_date = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class Order(models.Model):
REGSTATUS = (
('registered', 'registered'),
('enrolled', 'enrolled'),
('holding', 'holding'),
('withdrawn', 'withdrawn'),
('waiting', 'waiting'),
)
customer = models.ForeignKey(Customer, on_delete= models.CASCADE, null = True)
training_registered = models.ForeignKey(TrainingInstance, on_delete= models.SET_NULL, blank = True, null = True)
registration_date = models.DateTimeField(null=True,blank=True)
regstatus = models.CharField(max_length=200, null=True, choices=REGSTATUS, default='registered')
def __str__(self):
return self.customer.username
Here is what I have done - which works but I'm also open to feedback about good/bad practice.
class BuildOrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['training_registered']
def __init__(self,*args,**kwargs):
super (BuildOrderForm,self ).__init__(*args,**kwargs)
self.fields['training_registered'].queryset = TrainingInstance.objects.filter(training__year ="current")

How to show specific subcategory for a selected category in django

Recently I'm working on a blog. where a post has category and subcategory.
This is my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
class Category(models.Model):
title = models.CharField(max_length=50, unique=True)
def __str__(self):
return f"{self.title}"
class SubCategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=50, unique=True)
def __str__(self):
return f"{self.title}"
class Author(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(max_length=100)
phone_no = models.CharField(max_length=14)
details = models.TextField(null=True,blank=True)
def __str__(self):
return f"{self.name}"
class Post(models.Model):
author = models.ForeignKey(Author, default=1,blank=True,
null=True, on_delete=models.SET_DEFAULT)
category = models.ForeignKey(Category,on_delete=models.CASCADE,
null=True)
sub_category = models.ForeignKey(SubCategory,
on_delete=models.CASCADE, null=True, blank=True)
title = models.CharField(max_length=250)
featured_image = models.ImageField(
upload_to="post_featured_image",null=False )
content = RichTextUploadingField()
podcast = models.FileField(upload_to="post_podcast",
blank=True,null=True)
uploaded_on = models.DateTimeField(default=timezone.now)
viewed = models.IntegerField(default=0,editable=False)
def __str__(self):
return f"{self.title}"
Now I can choose category and subcategory for a post from Django admin panel. But the problem is I can choose one category and any subcategory even the subcategory is not the child of the selected category. So a post has a category and a subcategory. But the subcategory's parent category is not same as post's category. So I want that I can only choose those subcategories which is the child of selected categories that I choose for the post. Like next field has to be dependent on the previous field. How to do that?
sorry for my bad English. Thank you.

Simple Django Model (Add to Cart)

This is my first Django project and I am trying to implement add-to-cart features.
What changes should I make in this model so that multiple "Item" can be added into "Order", and also keep track of item quantity?
from django.db import models
from django.utils import timezone
# Create your models here.
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
phone = models.CharField(max_length=50)
def __str__(self):
return self.first_name
class Item(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
description = models.TextField(null=True)
summary = models.TextField(null=True)
type = models.CharField(max_length=50, null=True)
brand = models.CharField(max_length=50, null=True)
weight = models.DecimalField(default=0.00, max_digits=100, decimal_places=3)
picture = models.ImageField(null=True, upload_to='images/')
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class OrderQuantity(models.Model):
product = models.ForeignKey('Item')
quantity = models.PositiveIntegerField()
You need to create ManyToManyField in Order Model
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(Item)
Then you can add items to order in this way:
someorder.items.add(someItem)
Use ManyToManyField in your Item Model
class Item(models.Model):
orders = models.ManyToManyField(Order)
---
So one item have many orders. You can access it by order.item_set or item.orders
It depends on what your Item model is.
If Item is contains a type of product - you may want to use many-to-many field in your Order model, like so:
class Order(models.Model):
...
items = models.ManyToManyField(Item)
...
If Item describes one real item (not type of items), the proper way would be using ForeignKey in your Item model:
class Item(models.Model):
...
order = models.ForeignKey(Order)
...