inputs are not being stored in Mysql database - mysql

i am currently having an issue with my program my some of my input are not being saved in the MySQL database - any help will be appreciated
this creates a custom user which are the employee, admin and senior employee - this is a different model so another table
class CustomUser(AbstractUser):
user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee"))
user_type=models.CharField(default=1,choices=user_type_data,max_length=20)
this the model for one of my usertypes
class senioremployee(models.Model):
id = models.AutoField(primary_key=True)
admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE)
Dob = models.DateField()
Nationality = models.TextField()
Address = models.TextField()
Postcode = models.TextField()
Telephone = models.TextField()
Wage = models.TextField()
Passportnumber = models.TextField()
passportexpirydate = models.DateField()
gender = models.CharField(max_length=255)
profile_pic = models.FileField()
kinname = models.TextField()
kinrelation = models.TextField()
kinaddress = models.TextField()
kinphonenumber = models.TextField()
kinemail = models.TextField()
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now_add=True)
objects = models.Manager()
this function add user's data to the table
#receiver(post_save,sender = CustomUser)
def create_user_profile(sender,instance,created,**kwargs):
if created:
if instance.user_type==1:
admin.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "")
if instance.user_type==2:
senioremployee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "")
if instance.user_type==3:
employee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "")
this is the function that is meant to save the inputs into the senioremployee's table and email,password , firstname, lastname,username into the custom user's table but currently it only stores email,password , firstname, lastname,username into the custom user's table and just ignores the other user inputs
def add_seniorEmployee_save(request):
if request.method!="POST":
return HttpResponse("Method Not Allowed")
else:
first_name=request.POST.get("first_name")
last_name=request.POST.get("last_name")
username=request.POST.get("username")
email=request.POST.get("email")
password=request.POST.get("password")
Dob=request.POST.get("Dob")
Nationality=request.POST.get("Nationality")
Address=request.POST.get("Address")
Postcode=request.POST.get("Postcode")
Telephone=request.POST.get("Telephone")
Wage=request.POST.get("Wage")
Passportnumber=request.POST.get("Passportnumber")
passportexpirydate=request.POST.get("passportexpirydate")
gender=request.POST.get("gender")
kinname=request.POST.get("kinname")
kinrelation=request.POST.get("kinrelation")
kinaddress=request.POST.get("kinaddress")
kinphonenumber=request.POST.get("kinphonenumber")
kinemail=request.POST.get("kinemail")
try:
user = CustomUser.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name,user_type=2)
user.senioremployee.Dob = Dob
user.senioremployee.Nationality = Nationality
user.senioremployee.Address = Address
user.senioremployee.Postcode = Postcode
user.senioremployee.Telephone = Telephone
user.senioremployee.Wage = Wage
user.senioremployee.Passportnumber = Passportnumber
user.senioremployee.passportexpirydate = passportexpirydate
user.senioremployee.gender = gender
user.senioremployee.profile_pic=""
user.senioremployee.kinname = kinname
user.senioremployee.kinrelation = kinrelation
user.senioremployee.kinaddress = kinaddress
user.senioremployee.kinphonenumber = kinphonenumber
user.senioremployee.kinemail = kinemail
user.save()
messages.success(request, "Successfully Added Senior Employee")
return HttpResponseRedirect("/add_seniorEmployee")
except:
messages.error(request, "Couldnt add senior employee")
return HttpResponseRedirect("/add_seniorEmployee")

First you have a problem with your senioremployee creation query. You are using Dob and passportexpirydate as DateField.
class senioremployee(models.Model):
Dob = models.DateField()
passportexpirydate = models.DateField()
But when you are creating senioremployee record you are passing empty string which eventually produce exception.
post_save signal
try:
senioremployee.objects.create(admin = instance,Dob="",Nationality="",Address="",Postcode="",Telephone="",Wage="",Passportnumber="",passportexpirydate="",gender="",profile_pic="",kinname="",kinrelation="",kinaddress="",kinphonenumber="",kinemail = "")
except Exception as e:
print("e)
It will return the exception
['“” value has an invalid date format. It must be in YYYY-MM-DD format.']
so pass YYYY-MM-DD date format to Dob and passportexpirydate then senioremployee will be created.
When you are updating record, you are saving user model again which again raise post_save signal and you will be creating duplicate senioremployee record which return UNIQUE constraint failed.
So you must use this line of code to update senioremployee record
user.senioremployee.save()
instead of
user.save()

Related

is there a way to change the date format in django/html?

i am still new to django and i am following a tutorial but when the guy i had the error the method he used didnt work for me - i am get this error althogh the default format for date is yyyy- mm-dd - any help will be appreciated
['“” value has an invalid date format. It must be in YYYY-MM-DD
format.']
this is my save function that inputs the data into the database
def add_seniorEmployee_save(request):
if request.method!="POST":
return HttpResponse("Method Not Allowed")
else:
first_name=request.POST.get("first_name")
last_name=request.POST.get("last_name")
username=request.POST.get("username")
email=request.POST.get("email")
password=request.POST.get("password")
Dob=request.POST.get("Dob")
Nationality=request.POST.get("Nationality")
Address=request.POST.get("Address")
Postcode=request.POST.get("Postcode")
Telephone=request.POST.get("Telephone")
Wage=request.POST.get("Wage")
Passportnumber=request.POST.get("Passportnumber")
passportexpirydate=request.POST.get("passportexpirydate")
gender=request.POST.get("gender")
kinname=request.POST.get("kinname")
kinrelation=request.POST.get("kinrelation")
kinaddress=request.POST.get("kinaddress")
kinphonenumber=request.POST.get("kinphonenumber")
kinemail=request.POST.get("kinemail")
#try:
user = CustomUser.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name,user_type=2)
user.senioremployee.Dob = Dob
user.senioremployee.Nationality = Nationality
user.senioremployee.Address = Address
user.senioremployee.Postcode = Postcode
user.senioremployee.Telephone = Telephone
user.senioremployee.Wage = Wage
user.senioremployee.Passportnumber = Passportnumber
user.senioremployee.passportexpirydate = passportexpirydate
user.senioremployee.gender = gender
user.senioremployee.profile_pic=""
user.senioremployee.kinname = kinname
user.senioremployee.kinrelation = kinrelation
user.senioremployee.kinaddress = kinaddress
user.senioremployee.kinphonenumber = kinphonenumber
user.senioremployee.kinemail = kinemail
user.save()
this is the model for my senior employee who i am adding to the database
this is the model to create the customer user
class CustomUser(AbstractUser):
user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee"))
user_type=models.CharField(default=1,choices=user_type_data,max_length=20)
class senioremployee(models.Model):
id = models.AutoField(primary_key=True)
admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE)
Dob = models.DateField()
Nationality = models.TextField()
Address = models.TextField()
Postcode = models.TextField()
Telephone = models.TextField()
Wage = models.TextField()
Passportnumber = models.TextField()
passportexpirydate = models.DateField()
gender = models.CharField(max_length=255)
profile_pic = models.FileField()
kinname = models.TextField()
kinrelation = models.TextField()
kinaddress = models.TextField()
kinphonenumber = models.TextField()
kinemail = models.TextField()
created_at=models.DateTimeField(auto_now_add=True)
updated_at=models.DateTimeField(auto_now_add=True)
objects = models.Manager()
problem is with this line Dob=request.POST.get("Dob") you are saving a string in Dob , you need to convert it to date format. use strptime() from datetime module for conversion to date object and then save to the database.

How to add a column in table from frontend in django

I want to add columns to my Django app from frontend. For this, I have created a separate table for table fields but I don't know how can I add a field so that it automatically becomes a field in Contact table and how can i make a dynamic form to ask to fill such inputs.
Thanks in advance.
class Contact(models.Model):
fname = models.CharField(max_length=200)
lname = models.CharField(max_length=200)
email = models.CharField(max_length=100)
mobile = models.CharField(max_length=12)
address = models.CharField(max_length=200,default=None)
pincode = models.CharField(max_length=10)
created_date = models.DateField(auto_now=True)
class Field(models.Model):
field_name = models.CharField(max_length=100)
field_type = models.CharField(max_length=50)
is_required = models.BooleanField()

How to serialize relationship in django rest?

Try to serialize this Models
Model:
class Order (models.Model):
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
summ =models.CharField(max_length=15,default='0')
delivery = models.ForeignKey('Delivery')
success = models.BooleanField(default=False)
paymentMethod = models.ForeignKey('Payments')
def __unicode__(self):
return unicode(self.id)
class OrderProduct(models.Model):
order=models.ForeignKey('Order')
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
price = models.IntegerField()
product = models.ForeignKey('product.Product')
additionals = models.IntegerField(null=True,default=0)
count = models.IntegerField()
def __unicode__(self):
return self.id
class Delivery(models.Model):
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
delivery_time = models.DateTimeField()
delivery_adress = models.TextField()
phone = models.TextField()
def __unicode__(self):
return self.phone
class Payments(models.Model):
id = models.AutoField(primary_key=True)
date_create = models.DateField(auto_now_add=True)
date_change = models.DateField(auto_now=True)
title = models.TextField();
def __unicode__(self):
return self.title
Serializers:
class DeliverySerializer(serializers.ModelSerializer):
class Meta:
model = Delivery
fields = ('id', 'delivery_time','delivery_adress','phone')
def create(self, validated_data):
return Delivery.objects.create(**validated_data)
class PaymentsSerializer(serializers.ModelSerializer):
class Meta:
model = Payments
fields = ('id', 'title')
def create(self, validated_data):
return Payments.objects.create(**validated_data)
class OrderSerializer(serializers.ModelSerializer):
delivery = DeliverySerializer(read_only=True)
paymentMethod = PaymentsSerializer(read_only=True)
class Meta:
model = Order
fields = ('id', 'delivery', 'paymentMethod','summ','success')
def create(self, validated_data):
deliverys_data = validated_data.pop('delivery')
paymentsMethod_data = validated_data.pop('paymentMethod')
order = Order.objects.create(**validated_data)
for delivery_data in deliverys_data:
Delivery.objects.create(order=order, **delivery_data)
for paymentMethod_data in paymentsMethod_data:
Payments.objects.create(order=order, **paymentMethod_data)
return order
View:
#api_view(['POST'])
def order_post(request, format=None):
#List all snippets, or create a new snippet.
if request.method == 'POST':
serializer = OrderSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I need to get data by 1 packet, and then write data in DB
EveryTime I get a error:
deliverys_data = validated_data.pop('delivery')
KeyError: 'delivery'
Example of JSON packet
[{"delivery":{"delivery_time":"2016-05-31T12:18:47Z","delivery_adress":"123","phone":"123"},"paymentMethod":{"id":1,"title":"123124123"},"summ":"23","success":false}]
You are getting KeyError: 'delivery' because you have set delivery field as read_only. If DRF finds this field in the input, it will ignore that field.
From docs on read_only argument:
Read-only fields are included in the API output, but should not be
included in the input during create or update operations. Any
'read_only' fields that are incorrectly included in the serializer
input will be ignored.
Also, since you are using paymentMethod field in the create() method, you need to tell DRF to consider that field also in the input.
So, you need to remove the read_only argument from your serializer for both delivery and paymentMethod fields so that these fields are considered when deserializing.
class OrderSerializer(serializers.ModelSerializer):
delivery = DeliverySerializer() # remove read_only argument
paymentMethod = PaymentsSerializer() # remove read_only argument
Secondly, you are sending the data incorrectly. You need to send a single order input instead of list of orders you are sending.
# send without the list
{"delivery":{"delivery_time":"2016-05-31T12:18:47Z","delivery_adress":"123","phone":"123"},"paymentMethod":{"id":1,"title":"123124123"},"summ":"23","success":false}
EveryTime I get a error: deliverys_data = validated_data.pop('delivery') KeyError: 'delivery'
This is to be expected since the OrderSerialzier has DeliverySerializer flagged as read_only.
If you want to get the data writable, you'll need to remove that flag first.

edit and save the already existing data from database in django

models.py is
class Book(models.Model):
book_name=models.CharField(max_length=30)
author_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
def __unicode__(self):
..........
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
def __unicode__(self):
........
def books(self):
return Book.objects.filter(author=self)
I need to perform edit and save the already existing data in a table from database.I am using 2 models.since i did for doing the same by single table,have some confusion to perform with two table.I am a learner of django.plz help me with this
plz check my views.py for edit option.
def editbook(request,book_id):
if request.POST:
book_name =request.POST['book_name']
publisher_name =request.POST['publisher_name']
books=Book.objects.filter(book_id=book_id).update(book_name=book_name, publisher_name=publisher_name)
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email')
age = request.POST.get('age')
author = Author.objects.update(first_name = first_name,last_name = last_name,email=email,age=age)
return redirect('/index/')
else:
books = Book.objects.get(pk=book_id)
return render_to_response('editbook.html',{'books':books},context_instance=RequestContext(request))
ya.this is not working properlly.plz guide me how to perform that.
def editbook(request,book_id):
books = Book.objects.get(pk=book_id)
if request.POST:
book_name = request.POST.get('book_name')
publisher_name = request.POST.get('publisher_name')
books.book_name = book_name
books.publisher = publisher_name
get_author = books.save()
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email')
age = int(request.POST.get('age'))
author = Author.objects.get(pk=get_author.author_id)
author.first_name = first_name
author.last_name = last_name
author.email = email
author.age = age
author.save()
return redirect('/index/')
return render_to_response('editbook.html',{
'books':books
},context_instance=RequestContext(request))

exporting data from a database to another _mysql_exceptions.Warning: Data truncated for column 'x' at row 1

Hi I have a project in PHP and I want develop the same with Django, for many reasons I decided to create a new database, so now I have to export all the data from the old one to the new one,for doing that I use the models I developed for Django, it worked until I stuck with this error:
_mysql_exceptions.Warning: Data truncated for column 'bloomberg' at row 1
this is the model of the table where I am experimenting this issue:
class Contact(models.Model):
company_id = models.ForeignKey(Company)
address = models.CharField(max_length=150)
first_name= models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
role = models.CharField(max_length=20)
sector = models.CharField(max_length=45)
work_phone = models.CharField(max_length=30)
contact_source = models.CharField(max_length=30)
alt_work_phone = models.CharField(max_length=30)
mobile_phone = models.CharField(max_length=30)
work_fax = models.CharField(max_length=30)
bloomberg = models.CharField(max_length=60)
work_email = models.CharField(max_length=60)
research_email = models.CharField(max_length=60)
product_focus = models.CharField(max_length=2)
preferred_email = models.CharField(max_length=60)
job_title = models.CharField(max_length=80)
created_by = models.CharField(max_length=25)
legal_entity_name = models.CharField(max_length=100)
status= models.ForeignKey(Status)
title = models.CharField(max_length=5)
zipcode = models.CharField(max_length=10)
country = models.CharField(max_length=15)
city= models.CharField(max_length=20)
created_date=models.DateTimeField('creation date ')
updated_date=models.DateTimeField('update date ')
updated_by = models.CharField(max_length=20)
parent = models.CharField(max_length=45)
address_line_2 = models.CharField(max_length=100)
new = models.BooleanField()
hided = models.BooleanField()
employee = models.BooleanField()
def __unicode__(self):
s = u" Contact "
return s + self.first_name + " " + self.last_name
the fields in both databases have the same length,so I do not understand the error, after googling I noticed that usually this problem is solved fixing the dimensions of the column, but this is not my case. can somebody tell me how to fix it?
it looks like 60 Chars are not enough for your "bloombergs". Try to set this higher like:
bloomberg = models.CharField(max_length=255)
Notice, that you will also have to do this on database level if you already synced your models. Hope this helps.