HOW DO I DUPLICATE A TABLE WITH SEVERAL DATA WITH ONE FOREIGN KEY IN DJANGO - django-models

I have a django model 'client' and 'amendment of records' where 'amendment of records' is referenced to 'client' model. How do i add several data to the 'amendment of records' table with the same foreign key id?
This is my models
class ClientDetails(models.Model):
Gender_All = (('Male', 'Male'),('Female', 'Female'))
Programmes = (('RGN', 'RGN'),('RM', 'RM'),('RCN', 'RCN'),('PHN', 'PHN'),('NAP', 'NAP'),('NAC', 'NAC'))
FirstName = models.CharField(max_length=20, verbose_name='First Name')
MiddleName = models.CharField(max_length=20, null=True, blank=True, verbose_name='Middle Name')
LastName = models.CharField(max_length=20, verbose_name='Last Name')
DateofBirth = models.DateField(verbose_name='Date of Birth')
Gender = models.CharField(max_length=20, choices=Gender_All)
Programme = models.CharField(max_length=20, choices=Programmes)
RegistrationNumber = models.CharField(max_length=20, primary_key=True, verbose_name='Registration Number')
MobileNumber = models.IntegerField(verbose_name='Mobile Number')
EmailAddress = models.EmailField(verbose_name='E-mail Address')
ContactAddress = models.CharField(max_length=50, verbose_name='Contact Address')
IndexNumber = models.CharField(max_length=17, null=True, blank=True, verbose_name='Index Number')
def __str__(self):
return self.RegistrationNumber
class AmendmentofRecords(models.Model):
SELECTS = (('CHANGE OF NAME', 'CHANGE OF NAME'), ('CHANGE OF DATE OF BIRTH', 'CHANGE OF DATE OF BIRTH'))
Client = models.OneToOneField(ClientDetails, primary_key=True, verbose_name='Registration Number')
DateofRequest = models.DateTimeField(auto_now_add=True)
AmendmentType = models.CharField(max_length=50, choices=SELECTS, verbose_name='Amendment Type')
AmountPaidForAmendment = models.IntegerField(verbose_name='Amount Paid For Amendment')
AmendmentReceiptNumber = models.IntegerField(verbose_name='Amendment Receipt Number')
#UploadDocuments = models.ImageField(null=True, blank=True, verbose_name="Upload Required Files")
def __str__(self):
return str(self.Client)
Initially i filled the client form and added the client to the model database and i also selected 'CHANGE OF NAME' for the client I created earlier.
Now the same client wants to do 'CHANGE OF DATE OF BIRTH', i tried adding but i get an error message that the client already exist.
How do i beat around this?

Related

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

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.

How can I use an if condition in model.py Django?

I would like if a student studies "Computer Science", for example, that in the "Categories" class he can only select certain "Categories". Unfortunately I get the following error:
ERRORS:
accounds.Categories.members: (fields.E305) Reverse query name for 'accounds.Categories.members' clashes with reverse query name for 'accounds.Categories.members_ptr'.
HINT: Add or change a related_name argument to the definition for 'accounds.Categories.members' or 'accounds.Categories.members_ptr'.
from django.db import models
from datetime import date
# Create your models here.
class Members(models.Model):
created_at = models.DateField(default=date.today, null=True)
vorname = models.CharField(max_length=200, null=True)
nachname = models.CharField(max_length=200, null=True)
Studiengang = (("IT & Technik","IT & Technik") ,("Designs & Medie", "Designs & Medie"),
("Personal & Recht","Personal & Recht"), ("Informatik","Informatik"))
studiengang = models.CharField(max_length=200, null=True, choices=Studiengang)
email = models.CharField(max_length=200, null=True)
passwort = models.CharField(max_length=200, null=True)
def __str__(self):
return self.vorname
class Categories(Members):
if Members.studiengang == "Informatik":
Kategorien = (
("Mathematik Grundlagen I", "Mathematik Grundlagen I"),
("Grundlagen der industriellen Softwaretechnik", "Grundlagen der industriellen
Softwaretechnik"),
)
kategorien = models.CharField(max_length=200, null=True, choices=Kategorien)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
class Statistik(models.Model):
fragen_insgesammt = models.IntegerField(null=True)
fragen_richtig_beantwortet = models.IntegerField(null=True)
fragen_falsch_beantwortet = models.IntegerField(null=True)
anzahl_der_punkte = models.IntegerField(null=True)
student = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL)
I would be super happy if someone could help
in Categories Model > members ForeignKey add argument (related_name)
members = models.ForeignKey(Members, null=True,on_delete= models.SET_NULL,related_name="members_list")

How can i add custom fields to ModelSerializer?

i have a PurchaseDetail model like
class PurchaseDetail(NowTimestampAndUserModel):
purchase = models.ForeignKey(PurchaseMaster, default=False, related_name="purchase_details", on_delete=models.CASCADE)
item = models.ForeignKey(Item, default=False, on_delete=models.CASCADE)
item_category = models.ForeignKey(ItemCategory, default=False, on_delete=models.CASCADE)
purchase_cost = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)
sale_cost = models.DecimalField(max_digits=19, decimal_places=2, default=0.0)
qty = models.FloatField(help_text="Purchase quantity")
ref_purchase_order_detail = models.PositiveIntegerField(default=0)
ref_purchase_detail = models.PositiveIntegerField(default=0)
and i have "Item" model and "item_category" models as
ITEM
class ItemCategory(NowTimestampAndUserModel):
name = models.CharField(max_length=50, unique=True, help_text="Category name should be max. of 50 characters")
code = models.CharField(max_length=10, unique=True, help_text="Province name should be max. of 10 characters")
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
ITEM_CATEGORY
class ItemCategoryHist(NowTimestampAndUserModel):
name = models.CharField(max_length=50, help_text="Category name should be max. of 50 characters")
code = models.CharField(max_length=10, help_text="Province name should be max. of 10 characters")
def __str__(self):
return self.name
i want to make serializer class as
class StockSerializer(serializers.ModelSerializer):
item_name = Field(source='get_item_name')
class Meta:
model = PurchaseDetail
# some fields of PurchaseDetail
fields = ['id', 'item_name ', 'item_category']
def get_item_name(self, obj):
item_id = obj.item
item_obj = Item.objects.get(pk=item_id)
name = item_obj.name
return name
I want to serialize item name field only with Purchase Detai. How ca i do it?
What you need are Serializer Method Fields: https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield
The field "item_name" can be a SerializerMethodField, allowing you to have custom code to generate the value for that field.

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

django insert data from 2 tables using a single ModelForm

I want to get data from 2 tables into a form using ModelForm, like this:
fist model:
class Cv(models.Model):
created_by = models.ForeignKey(User, blank=True)
first_name = models.CharField(('first name'), max_length=30, blank=True)
last_name = models.CharField(('last name'), max_length=30, blank=True)
url = models.URLField(verify_exists=True)
picture = models.ImageField(help_text=('Upload an image (max %s kilobytes)' %settings.MAX_PHOTO_UPLOAD_SIZE),upload_to='avatar')
bio = models.CharField(('bio'), max_length=180, blank=True)
expertise= models.ForeignKey(Expertise, blank=True)
date_birth = models.DateField()
second model:
class Expertise(models.Model):
user = models.ForeignKey(User, blank=True)
domain = models.CharField(('domain'), max_length=30, blank=True)
specialisation = models.CharField(('specialization'), max_length=30, blank=True)
degree = models.CharField(('degree'), max_length=30, blank=True)
year_last_degree = models.CharField(('year_last_degree'), max_length=30, blank=True)
lyceum = models.CharField(('lyceum'), max_length=30, blank=True)
faculty = models.CharField(('faculty'), max_length=30, blank=True)
references = models.CharField(('references'), max_length=30, blank=True)
workplace = models.CharField(('workplace'), max_length=30, blank=True)
then i have in forms.py
class CvForm(ModelForm):
class Meta:
model = Cv
fields = ['first_name','last_name','url','picture','bio','date_birth']
class ExpertiseForm(ModelForm):
class Meta:
model = Expertise
fields = ['domain','specialisation']
The point is that i would want to have the both forms into one single form, and a single submit of course. So, i guess i should use a single ModelForm type class. But it doesn't work (if i put the expertise in the CvForm too ).
My form is created automatically from the ModelForm class, that's why i want to make a single class = > a single form.
Help plss,
Thanks a lot
Since there is a foreign key from Expertise to CV, there are potentially multiple expertises for each cv. So you should enable that by using inline formsets.

Resources