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))
Related
What I want to accomplish is to get a unique list of the names of customers with their lastest consultation date.
I have defined these models in my models.py file, using mySQL as my database:
class Customer(models.Model):
class ContactChoice(models.IntegerChoices):
DO_NOT_CONTACT = 0
EMAIL = 1
TXT_SMS_VIBER = 2
mobile_num = models.CharField('Mobile Number', max_length=10, unique=True,)
email_add = models.EmailField('Email', max_length=150, unique=True,)
last_name = models.CharField('Last Name', max_length=30,)
first_name = models.CharField('First Name', max_length=30,)
contact_for = models.CharField('Contact For', max_length=60,)
contact_on = models.IntegerField('Contact Using', choices=ContactChoice.choices, default=0,)
customer_consent = models.BooleanField('With Consent?', default=False,)
def __str__(self):
return self.last_name + ', ' + self.first_name
class Consultation(models.Model):
consultation_date = models.DateTimeField('Date of Consultation', default=now)
customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1)
concern = models.ForeignKey(SkinConcern, on_delete=models.SET_DEFAULT, default=1)
consultation_concern = models.CharField('Other Concerns', max_length=120, null=True,)
product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1)
user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1)
store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT, default=1)
consultation_is_active = models.BooleanField('Is Active', default=True)
def __str__(self):
return self.customer.last_name + ", " + self.customer.first_name
In my views.py, I have this for the Consultations page:
distinct = Consultation.objects.values('customer').annotate(consultation_count=Count('customer')).filter(consultation_count=1)
consults = Consultation.objects.filter(customer__in=[item['customer'] for item in distinct])
As mentioned, I was expecting to get a unique list of customer names with their latest consultation dates. This code results in only 1 record being shown.
Can you point me in the right direction for this? Thank you in advance! :)
As I see it, what you're doing right now is gathering all the customers that only had one consultation. This won't return what you want.
I believe you can use the latest() method for this: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#latest
This is untested code, but you could do something like this:
# gather all the customers
customers = Customer.objects.all()
# for every customer, get their latest consultation date, using the .latest() function
for customer in customers:
try:
latest_consultation = Consultation.objects.filter(customer=customer).latest('consultation_date')
latest_consultation_date = latest_consultation.consultation_date
except Consultation.DoesNotExist:
latest_consultation_date = None
customer.latest_consultation_date = latest_consultation_date
you can then loop over it as so:
for customer in customers:
if customer.latest_consultation_date:
print(customer.latest_consultation_date)
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.
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()
Here are the models I am working with:
class User(db.Model):
__tablename__ = 'user'
uid = db.Column(db.Integer, primary_key=True, index=True)
firstName = db.Column(db.String(100))
lastName = db.Column(db.String(100))
emailAddress = db.Column(db.String(120), unique=True, index=True)
pwHash = db.Column(db.String(256))
userLevel = db.Column(db.Integer())
userAccountType = db.Column(db.Integer())
isUserActive = db.Column(db.Boolean())
isUserLockedOut = db.Column(db.Boolean())
userLastLogin = db.Column(db.DateTime())
lastInvalidLogin = db.Column(db.DateTime())
userCreatedAt = db.Column(db.DateTime())
userConfirmedAt = db.Column(db.DateTime())
userUpdatedAt = db.Column(db.DateTime(), onupdate=datetime.datetime.now())
userAddress = db.relationship('Address', backref='user', lazy='dynamic')
userContactMethod = db.relationship('UserContactMethod', backref='user', lazy='dynamic')
userSensor = db.relationship('Sensor', backref='user', lazy='dynamic')
userReading = db.relationship('Reading', backref='user', lazy='dynamic')
deliveryEvents = db.relationship('logSMTPDeliveryEvents', backref='user', lazy='dynamic')
class Reading(db.Model):
__tablename__ = 'reading'
rid = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.Integer, db.ForeignKey('user.uid'))
sid = db.Column(db.Integer, db.ForeignKey('sensor.sid'))
readingTimestamp = db.Column(db.DateTime())
readingLightValue = db.Column(db.Integer)
readingLightStatus = db.Column(db.String(6))
readingTemp1 = db.Column(db.Float)
readingTemp2 = db.Column(db.Float)
readingHumidity = db.Column(db.Float)
So my table of readings has the User Id set as the foreign key in the readings table. Now when I try and issue a query like this:
queryResult = db.session.query(Reading).filter(Reading.uid == User.uid)
I get all the rows, which is incorrect. How should I be constructing this query?
Thanks!
C
It's not clear what you're trying to filter out from your question; Are you trying to find the Reading rows that correspond to a particular User row?
Supposing you have the email address of a user, and want to find the Reading's that belong to that user, you would need to build your query in three steps:
First, Start with a query that returns rows out of Reading:
q = session.query(Reading)
Next, extend the query to say that you want follow the user link to attributes of User.
q = q.join(Reading.user)
Finally Filter out only the rows that have the desired User features. Make sure you're filtering on a concrete, actual value.
q = q.filter(User.emailAddress == 'alice#example.com')
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.