Many-to-one relationships ComboBox filtering - python

Experts!
Having the following models.py
class Country(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Countries Uploaded'
class Users(models.Model):
name = models.CharField(max_length=50)
cUsers = models.ForeignKey(Country)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Users on a country'
class GoalsinCountry(models.Model):
Country = models.ForeignKey(VideoTopic)
name = models.CharField(max_length=50)
descr = models.TextField(blank=True, null=True)
def __unicode__(self):
return self.name
class Meta:
verbose_name = 'Goals Topic'
I would like to filter out the users that belongs to a particular country and not all see all users when choosing a country on the combobox, and be able to save this information to a sqlite3 db.
if I add the following code below Country = Models..
gUser = models.ForeignKey(Users)
Using the Django admin interface, will show all users, not filtering users based on the country they are.. Would this be possible to do with Django + Something else? is there any working example/Tutorial - like the northwind MS Tutorial?
Thank you

Related

How to create a custom student group and add students to that group?

I am creating a student project management system and each student will have a group with project. Only the admin will be able to add the students to the specific group using a drop down list menu. So far, I have create a student model and a group model such as these.
class Student(models.Model):
user = models.OneToOneField(User,null=True,on_delete=models.CASCADE)
id = models.IntegerField(max_length=11,primary_key=True)
course_taken = models.CharField(max_length=50,null=True)
specialization = models.CharField(max_length=50,null=True)
area_of_interest = models.CharField(max_length=50,null=True)
group = models.ForeignKey(Group,null=True)
def __str__(self):
if self.user.first_name and self.user.last_name:
full_name = self.user.first_name + " " + self.user.last_name
return full_name
class Group(models.Model):
id = models.AutoField(primary_key=True)
members = models.OneToManyField(User,through='Student')
project_id = models.ForeignKey(Project,null=True)
How to continue from this ?
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ['headline']
As seen in this example you can do that via Model-Relationship (one-to-one, one-to-many, many-to-one, many-to-many).
I would suggest consulting the documentation:
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
You have to create create three different class to do that task. With the Enrollment class the admin will be able to add the students to the specific group.
class Student(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Course(models.Model):
name = models.CharField(max_length=30)
student = models.ManyToManyField(Student, through='Enrollment')
def __str__(self):
return self.name
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
date_enrolled = models.DateField()
final_grade = models.CharField(max_length=1, blank=True, null=True)
class Meta:
unique_together = [['student', 'course']]

How to display and update model data in Django One-to-one relationships?

I have two models Place and Restaurant with one-to-one relationship. I want to use one model form Restaurantform and display place name in the form edit mode. Upon submitting the form need to update data in both model fields.
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __str__(self):
return "%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(
Place,
on_delete=models.CASCADE,
primary_key=True,
)
name = models.CharField(max_length=50)
serves_pizza = models.BooleanField(default=False)
def __str__(self):
return "%s the restaurant" % self.place.name
class Restaurantform(forms.ModelForm):
class Meta:
model = Restaurant
fields = ['name', 'serves_pizza', 'Name field from Place Model?']
I am not sure how to display place name and process the form submission!
Thank you!

Dynamic Fields with ManyToMany in Django admin

I want to define some fields for my model in another model. Here:
class Setting(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Option(models.Model):
name = models.CharField(max_length=255)
setting = models.ForeignKey(Setting)
def __unicode__(self):
return self.name
class Car(models.Model):
hsn = models.PositiveIntegerField("HSN", max_length=4)
tsn = models.PositiveIntegerField("TSN", max_length=3)
mileage = models.PositiveIntegerField("Kilometerstand")
settings = models.ManyToManyField(Setting)
In the admin I want to have every Settings.name as a field in CarAdmin with a select box of Options.name
How can I do this?
I've run accross a similar problem and solved it as below, I believe it should do the trick.
What you want is to have the Settings as inlines in your Car changeform and a M2M field pointing toward Options in the Setting Inline, overriding its widget to display it as checkboxes.
In your models.py:
class Option(models.Model):
name = models.CharField(max_length=255)
def __unicode__(self):
return self.name
class Car(models.Model):
hsn = models.PositiveIntegerField("HSN", max_length=4)
tsn = models.PositiveIntegerField("TSN", max_length=3)
mileage = models.PositiveIntegerField("Kilometerstand")
def __unicode__(self):
return self.hsn
class Setting(models.Model):
name = models.CharField(max_length=255)
options = models.ManyToManyField(Option, blank=True, null=True)
car = models.ForeignKey(Car, blank=True, null=True)
def __unicode__(self):
return self.name
In your admin.py :
from django.forms import CheckboxSelectMultiple
class OptionAdmin(admin.ModelAdmin):
pass
admin.site.register(Option, OptionAdmin)
class SettingInline(admin.TabularInline):
model = Setting
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
class CarAdmin(admin.ModelAdmin):
inlines = [
SettingInline
]
admin.site.register(Car, CarAdmin)
There might be some caveats with this solution, such as common options for every setting or misplaced help text below checkboxes, I've not looked further but it should be fixable.

Django admin - Wrong model object at edit page

I have 3 inherited classes (Fitters -> Workers -> Staffs) connected with tables in my Database (class names in the plural, but that's not important now).
User can add/edit/remove only Fitters. The Workers and Staffs tables are updated automatically (cascaded).
It works fine: when I add new Fitter, all changes come to all tables in database. But when I want to edit any Fitter via Django admin tool, I go to edit Fitter page and I see incorrectly filled fields.
For example:
In Staffs table I have "John Smith" with id=41
In Workers table I have the record with id=21 and ForeignKey=41 (to John Smith)
In Fitters table I have the record with id=5 and ForeignKey=21 (to record in Workers table)
When I go to edit Fitter "John Smith" page, I see all fields filled by "Kevin Thomas" (id=21 in Staffs table!).
So, Django misses the Workers table and goes directly to the Staffs table.
How can I fix it?
Here is my draft code:
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
def __unicode__(self):
return self.name + " " + self.surname
class Meta:
db_table = u'staffs'
class Workers(Staffs):
idWorker = models.AutoField(primary_key=True, db_column='id')
staffs_idstaff = models.OneToOneField('Staffs', db_column='Staffs_idstaff', parent_link=True)
brigades_idbrigade = models.ForeignKey('Brigades', db_column='Brigades_idBrigade')
def __unicode__(self):
return self.staffs_idstaff.name + " " + self.staffs_idstaff.surname
class Meta:
db_table = u'workers'
class Fitters(Workers):
idFitter = models.AutoField(primary_key=True, db_column='id')
qualification = models.CharField(max_length=135, blank=True)
workers_idworker = models.OneToOneField('Workers', db_column='Workers_idWorker', parent_link=True)
def __unicode__(self):
staff = self.workers_idworker.staffs_idstaff
return staff.name + " " + staff.surname
class Meta:
db_table = u'fitters'
EDIT1:
I tried to change my code like this:
class Staffs(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'staffs'
class Workers(Staffs):
idWorker = models.AutoField(primary_key=True)
brigades_idbrigade = models.ForeignKey('Brigades')
class Meta:
db_table = u'workers'
class Fitters(Workers):
idFitter = models.AutoField(primary_key=True)
qualification = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'fitters'
It's pretty simple now. I synced my database, but I have the absolutely same problem!
EDIT2:
Part of my admin.py file:
from django.contrib import admin
from appclient.models import *
admin.site.register(Fitters)
admin.site.register(Staffs)
admin.site.register(Workers)
...
SOLUTION:
Solution is I don't need use my own id's and ForeignKey's for each model. Djando automatically creates special field for each model and uses it as an id (PrimaryKey) and for link to the parent tables (ForeignKey).
Here is solution:
class Staffs(models.Model):
name = models.CharField(max_length=135, blank=True)
surname = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'staffs'
class Workers(Staffs):
brigades_idbrigade = models.ForeignKey('Brigades')
class Meta:
db_table = u'workers'
class Fitters(Workers):
qualification = models.CharField(max_length=135, blank=True)
class Meta:
db_table = u'fitters'
Thanks to everyone who helped me.
This does seem somewhat strange. However, as far as I understand, Django will automatically setup the required one-to-one mappings between parents and children, when using multi-table inheritance. As you have also set these up manually, it might very well be that some kind of inconsistency is introduced due this.
If you take a look directly in the database, are the two different one-to-one relations consistent?
What happens if you remove the explicit one-to-one fields from your models?

django one to many issue at the admin panel

Greetings, I have these 2 models:
from django.db import models
class Office(models.Model):
name = models.CharField(max_length=30)
person = models.CharField(max_length=30)
phone = models.CharField(max_length=20)
fax = models.CharField(max_length=20)
address = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ForeignKey(Office)
def __unicode__(self):
return self.name
I want to be able to select several Offices for Provinces, which is a one to many model. Here is my admin.py:
from harita.haritaapp.models import Province, Office
from django.contrib import admin
class ProvinceCreator(admin.ModelAdmin):
list_display = ['name', 'numberPlate','content','office']
class OfficeCreator(admin.ModelAdmin):
list_display = ['name','person','phone','fax','address']
admin.site.register(Province, ProvinceCreator)
admin.site.register(Office, OfficeCreator)
Right now, I am able to select one Office per Province at the admin panel while creating a new Province but I want to be able to select more than one. How can I achieve this?
Regards
I'm not sure if I'm misunderstanding you, but your models currently say "an office can be associated with many provinces, but each province may only have one office". This contradicts what you want. Use a ManyToMany field instead:
class Province(models.Model):
numberPlate = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
content = models.TextField()
office = models.ManyToManyField(Office)
def __unicode__(self):
return self.name

Categories

Resources