Django Admin - Add button to create duplicate fields - django

I am trying to add (+) button on the admin page to duplicate a field. So say I have a field for Father/Mother, and in case someone has a step father or a step mother I could hit the plus button on Father/Mother and duplicate the field and update step Father/Mother info.
I want to be able to do this with other fields as well and not just these two.
I am a newbie. So can you please help me with detailed instructions for how to do this please?
I have been trying to source this info for some time now...but :(
Thanks,
Codie
I have a very simple model structure and no forms as of now. In the future I may have some forms.
class _musi(models.Model):
name = models.CharField(max_length=200)
born = models.DateField()
died = models.DateField()
age = models.IntegerField()
reason_of_death = models.CharField(max_length=200)
birthplace = models.CharField(max_length=200)
father = models.CharField(max_length=200)
mother = models.CharField(max_length=200)

You need to use Django Inlines also to work with inline may be you need to make some changes with your models as you did not show your models so i am not sure about this.
You can refer to Inlines
Django Admin Inlines
Edit :
Please add all fields as Foreignkey with your current model _musi .
You should read how to use Foreign Key relationships
For now if you want with fields father and mother then do like below.
class Father(models.Model):
name = models.CharField(max_length=200)
class Mother(models.Model):
name = models.CharField(max_length=200)
class _musi(models.Model):
name = models.CharField(max_length=200)
born = models.DateField()
died = models.DateField()
age = models.IntegerField()
reason_of_death = models.CharField(max_length=200)
birthplace = models.CharField(max_length=200)
father = models.ForeignKey(Father)
mother = models.ForeignKey(Mother)
Please implement same with your other fields which need this functionality.

Related

Django model design issue with relationship

I have an problem where I can’t decide how to design the models for the following scenario
I want to create a companies table that will hold a list of companies. This table will have a comment field in it
I want that comment field to be able to hold multiple comments that are dated
A company can have multiple comments but a comment can only belong to only one company
Here the Comments table
class Comments(model.Models):
date = models.DateField(auto_now_add=True)
comment_text = models.TextField(required=True)
If I create the Companies table like this;
class Companies(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
comment = models.ForeignKey(Comments, on_delete=models.SET_NULL, null=True)
Then I can only attach one comment to one specific row of the Companies table
If I create the Companies table like this;
class Companies(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
comment = models.ManyToManyField(Comments)
Then a comment can belong to multiple companies which I don’t want.
In the Django documentation https://docs.djangoproject.com/en/2.0/topics/db/examples/ there is only one other options left which is the one-to-one mapping and this is clearly not what I want.
How can achieve what I want ?
You should do this.
class Company(models.Model):
name = models.CharField(max_length=30)
country = models.CharField(max_length=30)
class Comment(models.Model):
company = models.ForeignKey(Company, related_name='comments', on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
comment_text = models.TextField()
When accessing comments of a certain company, It will be;
comments = company.comments.all()
Just put the ForeignKey on Comment, pointing to Company. This does exactly what you want.

Is it possible to have a class as your model field in Django?

I am currently trying to create a health network website in Django.
The idea is that there will be a class called User inside my registration application. One of the states stored inside User is which hospital the user is registered into.
I created another Hospital within the registration app. I want to user that model Hospital as one of the model field for the hospital_used state. How do I do that? Below is a portion of my UML that illustrates the relationship
UML Diagram
Below is a portion of my UML that illustrates the relationship
png
Here is the code I have for it so far. The code where it is encapsulated with an asterisk is what I need help with.
class Hospital(models.Model):
hospital_Name = models.CharField(max_length=150)
def __str__(self):
return "Hospital Name: " + str(self.hospital_Name)
class User(models.Model):
PATIENT = 'Pat'
DOCTOR = 'Doc'
NURSE = 'Nurse'
ADMINISTRATOR = 'Admin'
user_type_choice = {
(PATIENT, 'Patient'),
(DOCTOR, 'Doctor'),
(NURSE, 'Nurse'),
(ADMINISTRATOR, 'Administrator'),
}
name = models.CharField(max_length=50)
dob = models.DateField(auto_now=False)
username = models.CharField(max_length=50)
*preferred_hospital = Hospital(models.CharField(max_length=50))*
patient_type = models.CharField(
max_length=5,
choices=user_type_choice,
)
Thank you StackOverflow Buddies
I would advise you to read this material on tutorials on how to create simple models.
What you want here is to use the ForeignKey method.
name = models.CharField(max_length=50)
dob = models.DateField(auto_now=False)
username = models.CharField(max_length=50)
preferred_hospital = models.ForeignKey(Hospital, on_delete = models.CASCADE)
patient_type = models.CharField(
max_length=5,
choices=user_type_choice,
)
You do not have to use on_delete = models.CASCADE but it is best that you handle what should happen when you delete an Hospital.
Know that you can also have OneToOne, ManyToOne, or ManyToMany fields, that are all described here.

django voting app - relationship between different models

I have a simple voting app which has 2 models Poll and Choice as most voting apps do.
Poll model has the following fields:
question - charField
pub_date - date and time
end_date - date and time
Also, each Poll has 2 choices.
Choice model has the following fields:
Poll - ForeignKey
choice - ImageField
vote - Integer
I have another model Person. A Poll occurs between 2 people from the Person model.
Person Model:
Name - Charfield
age - charfield
image - imagefield
...
I want to accomplish the following in the admin;
Create Poll (this is a simple one)
Create Choice - take image from Person Model rather than uploading new.
if a choice is added against a poll, the choice and the votes on that choice automatically show up as read only fields on Poll.
Person model shows how many Polls has the Person taken part in and how many of them has he won and lost.
Points 2,3 and 4 are the ones I am struggling with. please keep your responses simple, I am a newbie.
class Poll(models.Model):
question = models.CharField(max_length=250)
pub_date = models.DateTimeField()
end_date = models.DateTimeField()
class Choice(models.Model):
Poll = models.ForeignKey(Poll)
choice = models.ImageField(upload_to="choice")
vote = models.IntegerField()
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.IntegerField(blank=True, null=True)
image = models.ImageField(upload_to='img')
let me know if the question is not clear.
It is not totally clear to me what you want to achieve. Implying you want to answer the question in reference to two images I would use the following models:
class Poll(models.Model):
question = models.CharField(max_length=250)
person1 = models.ForeignKey(Person,related_name ="+") #"+" to block reverse reference
person2 = models.ForeignKey(Person,related_name ="+")
pub_date = models.DateTimeField()
end_date = models.DateTimeField()
class Choice(models.Model):
Poll = models.ForeignKey(Poll)
choice = models.ForeignKey(Person)
vote = models.IntegerField()
class Person(models.Model):
name = models.CharField(max_length=200)
age = models.IntegerField(blank=True, null=True)
image = models.ImageField(upload_to='img')
def votes_sum(self):
return len( self.choice_set.all()) #this returns all votes
In the admin you can then add the Choice model as Inline to the Poll.
class ChoiceInline(admin.TabularInline):
model = Choice
extra=1
class ProjectAdmin(admin.ModelAdmin):
inlines = [ChoiceInline]
class VotesAdmin(admin.ModelAdmin):
list_display = ['name', 'votes_sum']
readonly_fields = ('votes_sum',)
I did not test this code but you should get an idea how you can do this.

about multiple relations in django.models? noob here

this is my models.py
from django.db import models
# Create your models here.
class Leagues(models.Model):
LeagueName = models.CharField(max_length=200)
class Team(models.Model):
TeamName = models.CharField(max_length=200)
class LeagueTable(models.Model):
league = models.ForeignKey(Leagues)
team = models.CharField(max_length=200)
matches_played = models.IntegerField()
matches_won = models.IntegerField()
matches_drawn = models.IntegerField()
matches_lost = models.IntegerField()
points = models.IntegerField()
class FixtureTable(models.Model):
league = models.ForeignKey(Leagues)
fixture_date = models.DateField('Fixture Date')
team_one = models.CharField(max_length=200)
team_one_score = models.IntegerField()
team_two = models.CharField(max_length=200)
team_two_score = models.IntegerField()
in the "class FixtureTable", i want team_one and team_two to be linked to two differnt teams in "class Team" models. how to create multiple relations, or is it possible.
PS: this is purely a noob, with a little experience in programming, but no experience with either python or databases.
thankyou.
You can create as many ForeignKeys as you like to the same model. I suspect what's tripping you up is Django giving you an error saying that you need to specify a related name.
By default, Django creates an attribute on the opposite model of the form <model>_set. So in the following scenario:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team)
Django would add a related manager to Team as fixturetable_set. If you then did:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team)
team_two = models.ForeignKey(Team)
Django would attempt to add the same attribute twice and obviously fail. The fix is to specify a related_name, so each can have a unique related manager:
class FixtureTable(models.Model):
team_one = models.ForeignKey(Team, related_name='team_one_fixturetables')
team_two = models.ForeignKey(Team, related_name='team_two_fixturetables')
Then, everything will work fine. You can specify whatever you like for related_name as long as it's unique for the model.

Django admin 'is a' relationships

I've had plenty of experience in Django but I'm very new to the admin app (we usually build everything into the page as per project requirements).
But now I'm working on a project that requires some admin work and I'm stuck on one part.
Say I have Database models - Person, Student, Faculty
Both Faculty and Student 'is a' Person (they inherit those attributes so to speak). How can I show this in the admin view?
So that when someone clicks to add a student they fill out the student only attributes, but also the attributes required the Person model on the same page. Is this possible?
Here's the models, there's also Faculty but it's similar to Student
class Person(models.Model):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
mi = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
cell = models.CharField(max_length=20)
class Student(models.Model):
year = models.CharField(max_length=10)
stud_id = models.IntegerField()
person = models.ForeignKey(Person)
#many to many
Any ideas or further questions would be awesome!
InlineModelAdmin is your answer!
check it out!
Here is the code you need:
class StudentInline(admin.TabularInline):
model = Student
class PersonAdmin(admin.ModelAdmin):
inlines = [
StudentInline,
]
admin.site.register(Person,PersonAdmin)
Another way is to use Django model inheritance like this:
class Person(models.Model):
last_name = models.CharField(max_length=50)
first_name = models.CharField(max_length=50)
mi = models.CharField(max_length=50)
phone = models.CharField(max_length=20)
cell = models.CharField(max_length=20)
class Student(Person):
year = models.CharField(max_length=10)
stud_id = models.IntegerField()
This way, in the Student Admin page, you will get all the fields from Student AND from Person without Inlines. Also Django will deal automatically with the ForeignKey between the 2 tables.
Docs on Model inheritance.