In Django, when one of the children is deleted, all information is deleted? - django-models

I'm trying to create a program in Django for an employee database
How do I solve a problem when deleting one of the children, the employee and all his other information is deleted?
I use
class EmployeesAdmin(admin.ModelAdmin):
inlines = [PersonalInfoInline,ChildrenInline,]
class Employees(models.Model):
code = models.CharField(_('رقم التسجيل '), max_length=20)
image_profile = models.ImageField(_(" الصورة الشخصية "), upload_to="profile", blank=True, null=True)
firstname = models.CharField(_('الاسم '), max_length=100)
middlename = models.CharField(_('اسم الاب '), max_length=100, blank=True, null=True)
lastname = models.CharField(_('اسم الجد '), max_length=100, blank=True, null=True)
data_birth = models.DateField(_('تاريخ الولادة '), blank=True, null=True)
nikename = models.CharField(_('اللقب '), max_length=100, blank=True, null=True)
class Meta:
ordering = ['date_hired']
get_latest_by = 'date_hired'
class Children(models.Model): # المعلومات الابناء ===================================
employee = models.ForeignKey(Employees, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
sex = models.CharField(max_length=32, choices=(('ذكر', 'ذكر'), ('انثى', 'انثى'), ('otherother', 'other')),
blank=True)
dob = models.DateField(blank=True, null=True)
def __str__(self):
return self.name or ''
Each employee has his own children

At What does on_delete do on Django models?, it says that SET_NULL sets the reference to NULL if it is nullable. For instance, when you delete a User, you might want to keep the comments he posted on blog posts. It never said anything about the children being set to NULL.

Related

Creating a simple messaging function (NOT REAL TIME) using Django

Please I'm trying to implement a SIMPLE messaging function (NOT A REAL TIME CHAT)
But I keep getting this error message I understand what it says or mean but I'm not sure why I am unable to establish this relationship
Please I need help to alternative if I can't do things this way
This is my profile(Engineer) models
class Engineer(AbstractUser):
username = models.CharField(max_length=200, null=True)
email = models.EmailField(unique=True, null=True)
bio = models.TextField()
avatar = models.ImageField(default="profile.png")
country = models.CharField(max_length=200)
years_of_experience = models.PositiveIntegerField(null=True, blank=True)
tech_stack = models.CharField(null=True, blank=True, max_length=300)
inbox = models.ForeignKey(Inbox, null=True, on_delete=models.CASCADE)
USERNAME_FIELD = "email"
REQUIRED_FIELDS = ["username"]
def __str__(self):
return self.username
and this is my Inbox models
class Inbox(models.Model):
sender = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey(Engineer, null=True, on_delete=models.CASCADE, related_name="mail_receiver")
message = models.CharField(max_length=500)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created"]
def __str__(self):
return self.sender.username
Just make the Engineer import as follows
sender = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name='mail_sender')
receiver = models.ForeignKey('Engineer', null=True, on_delete=models.CASCADE, related_name="mail_receiver")

Please explain the _set.all() method in django>

I have this models and the view for user profile.
class Room(models.Model):
admin = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
group_photo = models.ImageField(null=True, upload_to = 'images/', default='avatar.svg')
name = models.CharField(unique=True, max_length=100)
description = models.TextField(null=True, blank=True)
members = models.ManyToManyField(User, related_name='members', blank=True)
created = models.DateTimeField(auto_now_add=True)
views.py
#login_required(login_url= 'login')
def userprofile(request, pk):
user = User.objects.get(username=pk)
#groups = user.room_set.all()
groups = Room.objects.filter(admin=user)
all_groups = Room.objects.filter(members=user)
return render(request, 'base/profile.html', {'user':user, 'groups':groups, 'all_groups':all_groups})
Please explain how _set.all method filter method are doing the same job.
I don't understand where the room is coming from (there is only (Room) model.
explain the mechanism of user.room_set.all line respect to filter;

filter objects by same value

Hey there i have a Order table which has created_at field, as multiple objects will be created at same date i want to list the objects by date.Such as i want to group the objects by date .Thank you.
#model
class SalesOrder(models.Model):
invoice_id = models.CharField(max_length=50, blank=True, null=True)
code = models.CharField(max_length=50, blank=True, null=True)
amount = models.FloatField(default=0.0, null=True, blank=True)
branch = models.ForeignKey('shop.Branch', on_delete=models.SET_NULL, null=True, blank=True)
customer = models.CharField(max_length=50, null=True, blank=True)
customer_contact = models.CharField(max_length=50, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.code)
def get_context_data(self, **kwargs): #View
cxt = super().get_context_data()
cxt['dates'] = SaleOrder.objects.annotate(
count=Count('created_at__date'))
# import pdb;pdb.set_trace()
cxt['form'] = SalesOrderForm(self.request.POST or None)

Django models save 2 Foreinkeys to same Model

Following this link and documentation, somehow it still can't save an Object with 2 Foreinkeys.
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #User.photo_set.all() returns all Photo objects of the photo
photoURL = models.CharField(max_length=256, null=True)
secondPhoto = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=1000, null=True)
is_private = models.BooleanField(default=False)
class Clash(models.Model):
win_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="wins", null=True)
loss_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="losses", null=True)
is_private = models.BooleanField(default=False) #we will filter those out for user quality calculations

How to build a form for nested models?

I am building an app in Django 1.9 with the models Customers and Addresses:
class Customers(models.Model):
name = models.CharField(db_column='NAME', max_length=400)
email = models.CharField(db_column='EMAIL', max_length=255, unique=True)
phone_number = models.CharField(db_column='PHONE_NUMBER', max_length=200, blank=True, null=True)
address = models.ForeignKey(Addresses, db_column='ADDRESS_ID', related_name='customer_address', null=True)
class Addresses(models.Model):
street = models.TextField(db_column='STREET', max_length=2000)
city = models.CharField(db_column='CITY', max_length=400, blank=True, null=True)
postal_code = models.CharField(db_column='POSTAL_CODE', max_length=200, blank=True, null=True)
country = models.ForeignKey(Country, db_column='COUNTRY_ID', null=True)
I am new in Django, so please forgive me if this has too much mistakes.
I want to create a new Customer using a form:
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
phone_number = forms.IntegerField(label=_(u'Phone Number'), required=False, widget=TextInput(attrs={'style': 'width:80px'}))
But I still want to be able to add the address. I read some stuff about nested forms, but I didn't understand.
Could you, please, help in building a form that creates a Customer with name, email, phone_number and address?
I figured it out! :)
You have to override the save method of the form.
class CustomersForm(ModelForm):
name = forms.CharField(label=_(u'Name'), widget=TextInput())
email = forms.CharField(label=_(u'Email'), widget=TextInput())
a_street = forms.CharField(label=_(u'Street'), widget=TextInput(), required=False)
a_postal_code = forms.CharField(label=_(u'Postal Code'), widget=TextInput(), required=False)
a_city = forms.CharField(label=_(u'City'), widget=TextInput(), required=False)
a_country = forms.CharField(label=_(u'Country'), widget=TextInput(), required=False)
# Override the save method like this
def save(self, commit=True):
c = super(CustomersForm, self).save(commit=False)
# Address
if c.address:
a = c.address
else:
a = Addresses()
a.street = self.cleaned_data.get('a_street')
a.city = self.cleaned_data.get('a_city')
a.postal_code = self.cleaned_data.get('a_postal_code')
a.country = self.cleaned_data.get('a_country')
if commit:
a.save()
c.address = a
c.save()
return c

Resources