How do I get these Textboxes to be collapsible?
I went through the documentation and this is what I wrote, but the changes are not being reflected.
Also, Is there any alternative I can use instead of limiting the user to select a max of 2 project manager or testers or what ever user they want to specify?
(Is there a way such that, the user can click on a + button or something so that another user can be listed is what I mean)
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('Project_Name',
'Project_Description',
'Admin_Name',
'Admin_Mail_ID',
'Project_Manager_1',
'Project_Manager_1_Mail_ID',
'Technician_1',
'Technician_1_Mail_ID',
'Tester_1',
'Tester_1_Mail_ID',
'Status_of_the_project',
'Created',
'Finish_Date',
'Supporting_Documents',
)
}),
('Add More Users', {
'classes': ('collapse',),
'fields': ('Project_Manager_2',
'Project_Manager_2_Mail_ID',
'Technician_2',
'Technician_2_Mail_ID',
'Technician_3',
'Technician_3_Mail_ID',
'Additional_User_1',
'Additional_User_1_Type',
'Additional_User_1_Mail_ID',
'Additional_User_2',
'Additional_User_2_Type',
'Additional_User_2_Mail_ID',
'Additional_User_3',
'Additional_User_3_Type',
'Additional_User_3_Mail_ID',
),
}),
)
Below is exactly how I wrote my codes for the models.py
Project_Name = models.CharField(max_length=100)
Project_Description = models.CharField(max_length=100)
Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+')
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+')
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_1_users+')
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_2_users+', blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_3_users+', blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Tester_1_users+')
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
The Django feature that you're looking for is called Inlines.
Related
I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear:
models.py
class MissionEntry(models.Model):
student = models.ForeignKey(
Student, on_delete=models.DO_NOTHING, blank=True, null=True)
mission = models.ForeignKey(
Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
log_entry = models.ForeignKey(
LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
learning_objective = models.ForeignKey(
LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
grade = models.CharField(
max_length=10, choices=GRADING_VALUE, blank=True, null=True)
note = models.TextField(blank=True, null=True)
debriefing = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.mission) + ' ' + str(self.log_entry)
class Meta:
verbose_name_plural = 'Mission Entries'
class MissionEntryStatus(models.Model):
mission = models.ForeignKey(
Mission, on_delete=models.PROTECT, null=True, blank=True)
student = models.ForeignKey(Student, on_delete=models.PROTECT)
is_completed = models.BooleanField(default=False)
is_failed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class StudentMission(models.Model):
mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
student_training_course = models.ForeignKey(
StudentTrainingCourse, on_delete=models.PROTECT)
mission_status = models.ForeignKey(
MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['mission__name']
def __str__(self):
return self.mission.name
class LogEntry(models.Model):
aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING)
adep = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='adep')
ades = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='ades')
date = models.DateField()
etd = models.TimeField()
ata = models.TimeField()
eet = models.TimeField()
function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT)
student = models.ForeignKey(
Student, on_delete=models.PROTECT, blank=True, null=True)
instructor = models.ForeignKey(
Instructor, on_delete=models.PROTECT, blank=True, null=True)
student_mission = models.ForeignKey(
'mission.StudentMission', on_delete=models.PROTECT, null=True, blank=True)
note = models.TextField(null=True, blank=True)
cross_country = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
def student_mission_list(request, pk):
student = Student.objects.get(id=pk)
student_training_course = StudentTrainingCourse.objects.filter(
student_id=student.id)
missions = StudentMission.objects.filter(
student_training_course_id__in=student_training_course)
mission_entry = MissionEntry.objects.filter(student_id=student)
log_entry = LogEntry.objects.filter(student_mission_id__in=missions)
print(log_entry)
context = {
'student': student,
'missions': missions,
'mission_entry': mission_entry,
}
return render(request, 'mission/student_mission_list.html', context)
In fact, what I need to do, is to obtain a single value for the log_entry. The problem is that, obviously, I am retrieving multiple values of log_entry. But I would like to get the single pk of the log_entry.
Any suggestion? Should I remodel the models.py file?
try this:
log_entry = LogEntry.objects.get(student_mission_id__in=missions)
print(log_entry.id)
In my django project my models.py:
class myCustomUser(AbstractUser):
username = models.CharField(max_length=20, unique="True", blank=False)
password = models.CharField(max_length=200)
isPatient = models.BooleanField(default=False)
isDoctor = models.BooleanField(default=False)
firstName = models.CharField(max_length=200, blank=True, null=True)
lastName = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(unique=True)
dateOfBirth = models.CharField(max_length=200, blank=True, null=True)
address = models.CharField(max_length=200, blank=True, null=True)
contactNo = models.IntegerField(null=True, unique=True)
def __str__(self):
return self.firstName
class Doctor(models.Model):
user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_user')
degree = models.CharField(max_length=200, blank=True, null=True)
speciality = models.CharField(max_length=200, blank=True, null=True)
isApproved = models.BooleanField(default=False)
def __str__(self):
return self.user.firstName
class Patient(models.Model):
user = models.OneToOneField(myCustomUser, null=True, blank=True, on_delete=models.CASCADE, related_name='patient_releted_user')
gender = models.CharField(max_length=200, blank=True, null=True)
class Appointment(models.Model):
pname = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='patient_releted_appointment', null=True, blank=True)
doctor = models.ForeignKey(Doctor, null=True, blank=True, on_delete=models.CASCADE, related_name='doctor_releted_appornment')
date = models.DateTimeField(null=True, blank=True)
isConfiremed = models.BooleanField(default=False)
After 1st migration when I trying to add any doctor object from admin panel it says error like:
TypeError at /admin/app/doctor/add/
__str__ returned non-string (type NoneType)
how can I fix it?
There is no guarantee that a user will have a first name as you set blank=True, null=True on myCustomUser.
To better understand how the null and blank parameters work (and where they differ) check out this answer to another question: https://stackoverflow.com/a/68948701/1720845
THe error upon clicking the POST button on Djangorest Form
The serializer:
class CreatePolicyBenefitsSerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('company','name','benefits','price')
The views:
class CreatePolicyBenefits(CreateAPIView):
queryset = Policy.objects.all()
serializer_class = CreatePolicyBenefitsSerializer
The Policy Model
``
class Policy(TimeStampedModel):
POLICY_CHOICES = (
('life', 'Life'),
('health', 'Health'),
('home', 'Home'),
('car', 'Car'),
('vul', 'VUL'),
)
PREMIUM_INTERVALS = (
('one_time', 'One Time'),
('annual', 'Annual'),
('semi_annual', 'Semi Annual'),
('quarterly', 'Quarterly'),
('monthly', 'Monthly')
)
company = models.ForeignKey(
'Company', related_name='Policies', on_delete=models.CASCADE,
null=True, blank=True)
name = models.CharField(max_length=255, blank=True, null=True, default="")
description = models.TextField(blank=True, null=True, default="")
benefits = models.JSONField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
category = models.CharField(
max_length=64, blank=True, null=True, choices=POLICY_CHOICES, default="")
premium_details = models.CharField(max_length=255, blank=True, null=True)
policy_details = models.CharField(max_length=255, blank=True, null=True)
available_premium_interval = models.CharField(
max_length=64, blank=True, null=True, choices=PREMIUM_INTERVALS)
icon_name = models.CharField(max_length=32, blank=True, null=True)
icon_file = models.FileField(
upload_to=upload_policy_icon, blank=True, null=True)
primary_color = models.CharField(max_length=32, blank=True, null=True)
# file=models.FilePathField(path=os.path.join(settings.MEDIA_ROOT, 'media'))
adminupload=models.FileField(upload_to=pdf_path,max_length=None)
pdfname=models.CharField(max_length=255, blank=True, null=True)
class Meta:
app_label = samplename
def __str__(self):
return '[%s] %s-%s' % (self.id, self.company, self.name)
Here the form
Is it possible when I hit POST button, the data can be displayed on the form? Thanks
I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view
class Aliens(models.Model):
class Meta:
db_table = 'aliens'
verbose_name = ('Introduction Event')
verbose_name_plural = ('Introuction Events')
ordering = ['alien']
alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species",
on_delete=models.CASCADE, null=True, blank=True)
#SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True)
group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE,
blank=True, null=True, default='')
firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True)
med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE,
null=True, blank=True)
origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Origin")
status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Establishement")
created_by = CurrentUserField()
created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now())
photo = models.ImageField(upload_to='photos', blank=True, null=True)
vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways")
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default=CurrentUserField(), null=True)
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class Distributions(models.Model):
class Meta:
db_table = 'distributions'
verbose_name = ('verified occurence')
verbose_name_plural = ('verified occurences')
alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions',
on_delete=models.CASCADE, null=True, blank=True)
country = models.OneToOneField(Country, on_delete=models.CASCADE, verbose_name='Country', blank=True, null=True)
seas = models.OneToOneField(regionalseas, on_delete=models.CASCADE, verbose_name='Regional Sea', blank=True,
null=True)
MSFD = models.OneToOneField(MSFD, on_delete=models.CASCADE, verbose_name='MSFD/EcAp Sub-region', blank=True,
null=True)
area1stSighting = models.DateField('First Areas Sighting', blank=True, null=True, default=datetime.datetime.now())
AreaSuccessType = models.OneToOneField(SuccessType, on_delete=models.CASCADE,
verbose_name='Area Establishement/Success', blank=True, null=True)
Area_citation = models.ForeignKey(biblio, verbose_name=u"Area first citation", on_delete=models.CASCADE, null=True,
blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_created',
default='')
created_at = models.DateField('date of Edition', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default='')
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
dverification = StateField(verbose_name='Validated ')
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class AliensFilter(django_filters.FilterSet):
country = filters.ModelChoiceFilter(label='Country', queryset=Country.objects.all())
msfd = filters.ModelChoiceFilter(label='MSF/EcAp Subregions', queryset=MSFD.objects.all())
regseas = filters.ModelChoiceFilter(label='Regional Seas', queryset=regionalseas.objects.all())
vector = filters.ModelChoiceFilter(label='Vectors/Pathway', queryset=vectors.objects.all())
Species = filters.ModelChoiceFilter(label='Species Name', queryset=Taxonomy.objects.all())
class Meta:
model = Aliens
fields = (
'Species', 'group', 'origin', 'firstsight', 'status', 'vector', 'country', 'msfd', 'regseas')
def search(request):
Aliens_list = Aliens.objects.all().select_related('origin', 'status', 'group', 'Taxonomy')
aliens_filter = AliensFilter(request.GET, queryset=Aliens_list)
# return render(request, 'mamias/list.html', {'filter': aliens_filter})
return render(request, 'mamias/list2.html', {'filter': aliens_filter})
How could I filter based on country for example?
There is no direct relationship between the Aliean and Country models. You would need to instead filter by country through the distributions relationship.
from django_filters import FilterSet, filters
class AlienFilter(FilterSet):
country = filters.ModelChoiceFilter(
field_name='distributions__country',
queryset=Country.objects.all(),
)
I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function:
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"])
return owners
Only problem is that I get an output of:
[<PlanMember: Doe, John (Primary)>, <PlanMember: Doe, Jane(Joint Subscriber)>, etc]
Now is there a way for me to just show their names and the member type (the words in brackets)?
A bit of background code.
Here is my views.py:
if request.POST:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p), request.POST)
if form.is_valid():
selected_plan = form.cleaned_data['plans']
plan = get_object_or_404(Plan, pk=selected_plan.pk)
investment_list = Investment.objects.all().filter(Q(plan = plan)).order_by('maturity_date')
context['investment_list'] = investment_list
context['plan'] = plan
context['today'] = now
context['current_yr'] = current_year
context['next_yr'] = next_year
context['show_report'] = True
else:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p))
context['form'] = form
return render_to_response('reports/planmaturities_year.html', RequestContext(request, context))
And my forms.py:
class PlanMaturityYearForm(forms.Form):
def __init__(self, plans, *args, **kwargs):
super(PlanMaturityYearForm, self).__init__(*args, **kwargs)
self.fields['plans'] = forms.ModelChoiceField(
plans,
required=True,
widget=forms.Select(attrs={'size': 20}),
error_messages={'required':'Please select the plan you wish to build the report for',}
)
Edit:
models.py
class Plan(models.Model):
old_id = models.IntegerField(null=True)
closed = models.BooleanField(default=False, blank=True)
closed_date = models.DateField(null=True)
profile = models.ForeignKey(Profile, default=False)
plan_type = models.ForeignKey(PlanType)
ownership_type = models.ForeignKey(OwnershipType)
status = models.PositiveSmallIntegerField(max_length=2, default=PLAN_OPEN)
timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True)
notes = HTMLField(blank=True, null=True)
bank = models.CharField(max_length=50, blank=True, null=True)
account = models.CharField(max_length=50, blank=True, null=True)
transit = models.CharField(max_length=50, blank=True, null=True)
objects = PlanManager()
class Profile(models.Model):
old_id = models.IntegerField(null=True, blank=True)
label = models.CharField(max_length=255, blank=True, verbose_name='Profile label/description')
location = models.ForeignKey(Location, null=True, blank=True)
client = models.BooleanField(default=False, blank=True)
corp = models.BooleanField(default=False, blank=True)
noncorp = models.BooleanField(default=False, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, default=False)
bak_agent_id = models.CharField(max_length=10, null=True, blank=True)
agent = models.ForeignKey(Agent, related_name='profiles')
check1 = models.BooleanField(default=False, blank=True)
incorp_date = models.DateField(null=True, blank=True)
corp_records = models.BooleanField(default=False, blank=True)
articles_of_incorp = models.BooleanField(default=False, blank=True)
other_corp_articles = models.CharField(max_length=50, null=True, blank=True)
bin = models.CharField(max_length=50, null=True, blank=True, verbose_name='BIN')
phone = models.CharField(max_length=25, null=True)
registration = models.CharField(max_length=45, null=True, blank=True)
num_sigs = models.IntegerField(max_length=1, null=True, blank=True,
verbose_name='Number of signatures required to transaction the account')
charity = models.BooleanField(default=False, blank=True)
donations_solicited = models.BooleanField(default=False, blank=True)
ownership_type = models.CharField(max_length=45, null=True, blank=True)
ownership_other = models.CharField(max_length=45, null=True, blank=True) #work around for other business type selction
business_nature = models.CharField(max_length=45, null=True, blank=True)
date_incept = models.DateField(null=True, blank=True)
bind_power = models.BooleanField(default=False, blank=True)
reg_documents = models.BooleanField(default=False, blank=True)
other_documents = models.CharField(max_length=50, null=True, blank=True)
reg_number = models.CharField(max_length=45, null=True, blank=True)
tax_number = models.CharField(max_length=45, null=True, blank=True)
phone = models.CharField(max_length=25, null=True, blank=True)
fax = models.CharField(max_length=25, null=True, blank=True)
email = models.CharField(max_length=100, null=True, blank=True)
You can use values_list:
owners = self.planmember_set.filter(
ownership_type__code__in=["primary","joint"]
).values_list('name', 'type')
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"]).values_list('name_field', 'ownership_type__code')
return owners
Write where and how you use get_owners if not correct.