Populate model instance with another model data during instance creation - django

I have creating an app as my learning project in Django.
There are 3 model classes:
# MOC class
class Moc(models.Model):
name = models.CharField(max_length=128, blank=True, null=True)
my other fields...
def __str__(self):
return str(self.id)
def save(self, *args, **kwargs):
created = not self.pk
super().save(*args, **kwargs)
if created:
CheckList.objects.create(moc=self)
# Pre Implement class
class CheckList(models.Model):
moc = models.OneToOneField(Moc, related_name='checklist', on_delete=models.CASCADE, default='1')
name = models.CharField(max_length=128, blank=True, null=True)
def __str__(self):
return str(self.id)
def save(self, *args, **kwargs):
created = not self.pk
super().save(*args, **kwargs)
if created:
CheckListItem.objects.create(checklist=self)
# Pre Implement Items class
class CheckListItem(models.Model):
checklist = models.ForeignKey(CheckList, related_name='checklistitems', on_delete=models.CASCADE, default='1')
action_item = models.TextField(max_length=128, blank=True, null=True)
actionee_name = models.ForeignKey(User, related_name='actionee_ready_pre_implements', on_delete=models.CASCADE, default='1')
action_due = models.DateField(blank=True, null=True)
def __str__(self):
return str(self.id)
I am creating Moc instance and on post save signal creating my CheckList class instance and consequently my CheckListItem class instances.
However, imaging that my CheckList once created always should have 10 CheckListItem objects as a pre populated list (like an initial data). I could not figure-out if this is something doable (at least how I am trying to achieve it as per my model relationships).
I do not want to hard code thus items in my HTML, I want to control add/delete of thus CheckListItems for related Moc/CheckList instances as relevant.
Any thoughts please?

I solved this by using InlineFormSets as it is responsible for FK relationships.

Related

How to write a business logic involving two models in Django Rest Framework

I am confused and dont know how to write the business logic in django and django rest framework.
How to validate the student that does not already exist in the registration (registration_no will be provided through front end and it will be included in the json) table at the time of student creation?
class Student(models.Model):
name = models.CharField(max_length=300)
sex = models.CharField(choices=SEX_CHOICES,max_length=255, null=True)
Category = models.CharField(max_length=100, null=True)
def __str__(self):
return self.name
RegisrationModel
class Registration(models.Model):
registration_no = models.CharField(max_length=255, unique=True)
student = models.ForeignKey(Student,
on_delete= models.CASCADE, related_name='registrations')
def __str__(self):
return self.registration_no
You can override save() method of model Registration in order to make your verification and raise an exception if there is an student with the same name and registration number already in the database.
class Registration(models.Model):
registration_no = models.CharField(max_length=255, unique=True)
student = models.ForeignKey(Student,
on_delete= models.CASCADE, related_name='registrations')
def __str__(self):
return self.registration_no
def save(self, *args, **kwargs):
try:
Registration.objects.get(student__name=self.name, registration_no=self.registration_no)
except:
super(Registration, self).save(*args, **kwargs)
else:
raise Exception("Student already registered")

Set ManyToMany field in model save method

I have a problem, I try to save the model and only adds to 'members' the users that belong to the company set in the field 'company'.
This is my code:
class GroupFolderAccess(BaseModel):
name = models.CharField(max_length=128)
members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='belongs')
company = models.ForeignKey('Company', on_delete=models.CASCADE, related_name='folders')
folder = models.ForeignKey('recourse.Folder', null=True, blank=True, on_delete=models.CASCADE, related_name='get_group')
def save(self, *args, **kwargs):
for member in self.members.all():
if self.company != member.company:
print(member)
self.members.remove(member)
return super(GroupFolderAccess, self).save(*args, **kwargs)
When I save, it displays users correctly, but does not remove them from the relationship.

How to create an inline formset with manytomany relation in Django

I want to create an inline formset between Preorder model and Product model. The scenario is that the user will be able to select one or more than one products when he decides to create a preorder. On the other hand a product might be found in one or more than one preorders. With that in mind i created a manytomany relationship.
models.py
class Preorder(models.Model):
client = models.ForeignKey(Client,verbose_name=u'Client')
invoice_date = models.DateField("Invoice date",null=True, blank=True, default=datetime.date.today)
preorder_has_products = models.ManyToManyField(Product, blank=True)
def get_absolute_url(self):
return reverse('preorder_edit', kwargs={'pk': self.pk})
class Product(models.Model):
name = models.CharField("Name",max_length=200)
price = models.DecimalField("Price", max_digits=7, decimal_places=2, default=0)
barcode = models.CharField(max_length=16, blank=True, default="")
eopyy = models.CharField("Code eoppy",max_length=10, blank=True, default="")
fpa = models.ForeignKey(FPA, null=True, blank=True, verbose_name=u'Fpa Scale')
forms.py
class PreorderForm(ModelForm):
class Meta:
model = Preorder
exclude = ('client','preorder_has_products',)
def __init__(self, *args, **kwargs):
super(PreorderForm, self).__init__(*args,**kwargs)
self.fields['invoice_date'].widget = MyDateInput(attrs={'class':'date'})
class ProductForm(ModelForm):
#name = ModelChoiceField(required=True,queryset=Product.objects.all(),widget=autocomplete.ModelSelect2(url='name-autocomplete'))
class Meta:
model=Product
fields = '__all__'
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs)
self.fields['name'].label="Name"
self.fields['price'].label="Price"
and finally the inline formset:
PreorderProductFormSet = inlineformset_factory(Preorder, Product,
form=ProductForm, extra=1)
After run I face up the issue:ValueError at /
'intranet.Product' has no ForeignKey to 'intranet.Preorder'
Why this happening since I created a manytomany relation?
One solution is to create a foreign key relationship between Preorder and Product model inside Product model..but I do not want to do that since product model is used in other areas of my project and do not want to mess it up.
Any suggestions?

Django create instance of model from another models save method

I have an Article model which has a OnetoOne relationship with a Catalog Model. Is it possible to create an instance of Catalog from within the save method of the Article. I'd like to attach an Article with a Catalog of the same name, it would be easiest to create these at the same time.
Here is my Catalog class:
class Catalog(models.Model):
name = models.CharField(max_length=100)
price = models.IntegerField
def __unicode__(self):
return self.name
Article Class:
class Article(models.Model):
catalog = models.OneToOneField(Catalog, related_name='article_products', blank=True, null=True)
title = models.CharField(max_length=200)
abstract = models.TextField(max_length=1000, blank=True)
full_text = models.TextField(blank=True)
proquest_link = models.CharField(max_length=200, blank=True, null=True)
ebsco_link = models.CharField(max_length=200, blank=True, null=True)
def __unicode__(self):
return unicode(self.title)
def save(self, *args, **kwargs):
self.full_text = self.title
super(Article, self).save(*args, **kwargs)
I'd like to some logic similar to this within the save method: I'm not sure if it's possible though
cat = Catalog.create(title = self.title)
cat.save()
You could instead use post_save signal for creating catalog objects at the time of creation of article objects. This would ensure creation of the catalog objects, without having to include non-relevant code in the article models' save method.
from django.db.models.signals import post_save
# method for updating
def create_catalog(sender, instance, created, **kwargs):
if instance and created:
#create article object, and associate
post_save.connect(create_catalog, sender=Article)

Cannot auto add group in Django

I am using Django 1.6 and have a CustomUser.
I want all users that are created to be added to a group by default.
I have tried to add it to the save method for my user but its not working.
class MyUser(AbstractBaseUser, PermissionsMixin):
name = models.CharField(max_length=200)
section = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, null=True)
...
objects = MyUserManager()
def save(self, *args, **kwargs):
group = Group.objects.get(name='myhistory')
self.groups.add(group)
self.section="testing it saves"
super(MyUser, self).save(*args, **kwargs)
It does call the save method as it sets the section as above - but wont set the group.
It finds the group fine - just no setting it.
Can anyone help?
I think you have missed indentation,
class MyUser(AbstractBaseUser, PermissionsMixin):
name = models.CharField(max_length=200)
section = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, null=True)
...
objects = MyUserManager()
def save(self, *args, **kwargs):
group = Group.objects.get(name='myhistory')
self.groups.add(group)
self.section="testing it saves"
super(SCVUser, self).save(*args, **kwargs)