when I try to feel department field is show me this error.
I don't understand this error.. please help me out
Cannot assign "'HR'": "Employee.department" must be a "Department" instance.
here is my model.py
class Department(models.Model):
name = models.CharField(max_length= 20,null=True)
def __str__(self):
return self.name
class Employee(models.Model):
employee_name = models.CharField(max_length= 20, null=True)
surname = models.CharField(max_length= 20, null=True)
address = models.CharField(max_length = 50, null=True)
qualification = models.CharField(max_length = 30,null=True)
contact_num = models.IntegerField(null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
def __str__(self):
return self.employee_name
here is my form.py
class AdForm(forms.ModelForm):
employee_name = forms.CharField()
surname = forms.CharField ()
address = forms.CharField ()
qualification = forms.CharField ()
contact_num = forms.IntegerField ()
department = forms.CharField()
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
here is my view.py
def create(request):
if request.method == 'POST':
form = AdForm(request.POST)
if form.is_valid(): #getting error on this
form.save()
return HttpResponseRedirect(reverse('employee-list'))
else:
form = AdForm()
return render(request, 'employee/create.html', {'form': form})
The department field on your Employee model is a ForeignKey field, but in your AdForm you define it as CharField.
You could fix the field definition in your form. Alternatively, you could also simply remove the explicit field definition. When using a model form, Django will select the correct field type for you.
class AdForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
This will render the department field as a <select> widget, allowing you to select from your (pre-existing) departments.
Related
I have a form class (incorrect) :
class TeamGoalForm(ModelForm):
class Meta:
employees = forms.ModelMultipleChoiceField(queryset=Employee.objects.filter(departament=Department.objects.get(manager=Manager.objects.get(end_user_id = request.user.username.upper())),widget=forms.CheckboxSelectMultiple()))
department = forms.ModelChoiceField(queryset=Department.objects.all())
model = TeamGoal
fields = '__all__'
widgets = {
'employees' : forms.Select(attrs={'class': 'form-control', 'placeholder':'Select employees'}),
}
'department':forms.Select(attrs={'class': 'form-control', 'placeholder':'Select department'}),
I want to pass parameter request.user.username.upper() which I have in my view.py. How to implement this in my TeamGoalForm?
my view.py
#login_required(login_url='login')
def add_team_goal(request):
form = TeamGoalForm(is_manager(request))
if request.method == 'POST':
form = TeamGoalForm(request.POST)
if form.is_valid():
form.save()
return redirect('team_goal')
team = get_team(request)
if team.exists():
return render(request, 'smth.html', {'form':form,'team':team})
My Employee model:
# Employee section
class Employee(models.Model):
name = models.CharField(max_length=30, verbose_name='Name')
lastname = models.CharField(max_length=30, verbose_name='Lastname')
.............
history = HistoricalRecords()
def __str__(self):
return self.name + ' ' + self.lastname
My Department:
class Department(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=30)
.........
manager = models.ForeignKey(Manager, related_name='manager_name', null=True, on_delete = models.SET_NULL)
history = HistoricalRecords()
My Managers:
class Manager(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
lastname = models.CharField(max_length=30)
history = HistoricalRecords()
def __str__(self):
return self.name + ' ' + self.lastname
My TeamGoal:
class TeamGoal(models.Model):
team_goal_title = models.CharField(max_length=30, verbose_name='Title')
team_goal_description = models.CharField(max_length=100, blank=True, verbose_name='Description')
department = models.ForeignKey(Department, verbose_name='Department', on_delete = models.CASCADE, related_name='+', blank=True, null=True, help_text=u'If you assign the team goal for the whole department, please fill only Department field and skip Employee field.')
employees = models.ManyToManyField(Employee, null=True, blank=True, symmetrical=False, related_name='employee_name')
......
history = HistoricalRecords()
In my app I can create Team goal for whole department or for specific group of employees.
I would really advise not to give Manager the same name as a user and then match on that: it makes keeping records in sync quite hard. You can link to the user model with:
from django.conf import settings
class Manager(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
history = HistoricalRecords()
def __str__(self):
return f'{self.user.first_name} {self.user.lastname}'
you can pass the user as parameter to the ModelForm and then filter the queryset:
class TeamGoalForm(ModelForm):
def __init__(self, *args, user=None, **kwargs):
super().__init_(*args, **kwargs)
if user is not None:
self.field['employees'] = Employee.objects.filter(
department__manager__user=user
)
class Meta:
model = TeamGoal
fields = '__all__'
widgets = {
'employees' : forms.SelectMultiple(attrs={'class': 'form-control', 'placeholder':'Select employees'}),
'department':forms.SelectMultiple(attrs={'class': 'form-control', 'placeholder':'Select department'})
}
and in the view pass the logged in user to the TeamGoalForm:
#login_required(login_url='login')
def add_team_goal(request):
if request.method == 'POST':
form = TeamGoalForm(request.POST, user=request.user)
if form.is_valid():
form.save()
return redirect('team_goal')
else:
form = TeamGoalForm(user=request.user)
team = get_team(request)
return render(request, 'smth.html', {'form':form,'team':team})
In the database there is class Borrowing which contains employee_id that will borrow item and tag_id (the item) and subscriber_id
in my code, if an employee request a borrowing, he can choose subscriber_id.
I need to set the subscriber_id to 1, without even asking the employee to choose.
in the models.py file
class Borrowing(models.Model):
borrowing_id = models.IntegerField(null=True)
start_date = models.DateField(auto_now_add=True, null=True)
end_date = models.DateField(null=True)
employee_id = models.ForeignKey(Employee, null=True, on_delete= models.SET_NULL)
tag_id = models.ForeignKey(Tag, null=True, on_delete= models.SET_NULL)
subscriber_id = models.ManyToManyField(Subscriber)
def __str__(self):
return str(self.borrowing_id)
in forms.py file
class BorrowingForm(ModelForm):
class Meta:
model = Borrowing
fields = ['end_date', 'employee_id', 'tag_id', 'subscriber_id']
in views.py
def createBorrowing(request, pk):
BorrowingFormSet = inlineformset_factory(Employee, Borrowing, fields=('end_date','tag_id','subscriber_id'))
employee = Employee.objects.get(id=pk)
formset = BorrowingFormSet(queryset=Borrowing.objects.none(), instance=employee)
if request.method == 'POST':
formset = BorrowingFormSet(request.POST, instance=employee)
if formset.is_valid():
formset.save()
return redirect('/login')
context = {'formset':formset}
return render(request, 'assetstracking/createBorrowing.html', context)
You must set a default value in the Models.py
class Borrowing(models.Model):
...
subscriber_id = models.ManyToManyField(Subscriber, default=default_subscriber)
...
def __str__(self):
return str(self.borrowing_id)
And if you don't need the employee to chose you can remove subscriber_id from the fields in the forms.py
Notice that default_subscriber needs to be a subscriber.
I connected my database to django. I want to enable user (teacher) insert the name of a student and get test results on certain subjects.
I run python3 manage.py inspectdb and inserted it into models.py
class Profilez(models.Model):
student = models.CharField(max_length=255)
schgroup = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profilez'
class Schoolz(models.Model):
profilez_id = models.AutoField(primary_key=True)
lit = models.IntegerField(blank=True, null=True)
math = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'schoolz'
in forms.py i put:
class StudentForm(forms.ModelForm):
SUB = (
('lit', 'lit'),
('math', 'math')
)
student = forms.CharField(max_length=150, label='', widget=forms.TextInput)
class Meta:
model = Schoolz
fields = ('student',)
in views.py:
def home(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
form1 = form.save(commit=True)
name = form1.student
ab=schoolz.objects.all()
context={
'name':name,
}
return render(request, 'book/analysis.html', context)
else:
form = StudentForm()
return render(request, 'book/search.html', {'form': form})
Can you please help me to understand what i am doing wrong and how to get value for certain subject for exmaple math subject.
I would appreciate help and guidance to undertand and execute it. I am struggling a month.
Notes
Add a field in Profile that should be unique for each student. Currently I am assuming name and surname combination will be unique.
If you use ajax, you can get score without refresh. Current way I have used is not very good.
You don't have to write models if you already have in DB. You can remove your models. add already present models in models.py and makemigrations and migrate.
Add a ForiegnKey field in Class10
class Class10(models.Model):
profile_id = models.IntegerField()
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='stud_name') # add this in model
class Meta:
managed = False # make this True otherwise makemigrations won't get the changes.
db_table = 'class_10'
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
views.py
def home(request):
if request.method == "POST":
form = StudentlForm(request.POST)
if form.is_valid():
form_1 = form.save(commit=False)
name = form_1.student_name
surname = form_1.student_surname
subject = form_1.subject
fil = Q(student__student_name=name) & Q(student__student_surname=surname)
student_1 = StudentScore.objects.filter(fil).values()
score = student_1[0][subject] # answer
context={
'score':score
}
return render(request, 'school/analysis.html', context)
else:
form = StudentlForm()
return render(request, 'school/search.html', {'form': form})
forms.py
class StudentForm(forms.ModelForm):
SUB = (
('math', 'math'),
('literature', 'literature'),
('biology', 'biology')
)
student_name = forms.CharField(max_length=150, label='', widget=forms.TextInput)
student_surname = forms.CharField(max_length=150, label='', widget=forms.TextInput)
subject = forms.CharField(widget=forms.Select(choices=SUB))
class Meta:
model = Profile
fields = ('student_name', 'student_surname', 'subject')
#Nina,
Please look on the relationship> it's general idea for the Student & Gradesheet model
class Student(models.Model):
std_name = models.CharField(max_length=100)
def __str__(self):
return self.std_name
class Gradesheet(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
sub = models.CharField(max_length=50)
grade = models.CharField(max_length=50)
def __str__(self):
return self.student.std_name
So if you need to search for a student grade for particular subject:
std_info = Student.objects.get(std_name='Nina')
Then you will get a Student Class instance for Nina.
Now fetch the data by relationship:
std_grade = std_info.gradesheet_set.filter(sub='math')
You will get QuerySet. Then just :
std_grade[0].grade
You will get your student's grade for particular subject. Look its a model relationship. So you may use other filtering options also to get your desired result.
According to your given model:
Instead of the profile_id you should use the Profile object which will help you to take the control through django ORM.
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
class Class10(models.Model):
#profile_id = models.IntegerField()
profile = models.OneToOneField(Profile, on_delete=models.CASCADE,related_name='profile')
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
class Meta:
managed = False
db_table = 'class_10'
So your query can be build by:
std_profile = Profile.objects.get(student_name='SomeoneName')
Now turn it for get the grade. Result would be:
math_grade = std_profile.profile.math
biology_grade = std_profile.profile.biology
literature_grade = std_profile.profile.literature
average_grade = ((math_grade + biology_grade + literature_grade)/3)
Here, your model relationship:Profile to Class10 is OneToOne
I'm really having some trouble with this. I've got some custom user's setup and those users can be attached to companies via foreign key. I'm just having trouble saving them. I've tried a ton of different variations of getting the user attached to a company and I just can't crack it. The forms do work and it does both create a "customer" and a "customer company".
I know this needs to be a variation of:
if customer_form.is_valid() and customer_company_form.is_valid():
customer_company = customer_company_form.save()
customer = customer_form.save(commit=False)
customer.user = customer_company
customer_company.save()
models.py
class CustomerCompany(models.Model):
COUNTRIES = (
('USA', 'United States'),
('CAN', 'Canada')
)
name = models.CharField(max_length=100, blank=True, unique=True)
website = models.CharField(max_length=100, blank=True)
phone = models.CharField(max_length=10, blank=True)
address = models.CharField(max_length=100, blank=True)
city = models.CharField(max_length=255, blank=True)
state = USStateField(blank=True, null=True)
us_zipcode = USZipCodeField(blank=True, null=True)
ca_province = models.CharField(max_length=50, blank=True, null=True)
ca_postal_code = models.CharField(max_length=7, blank=True, null=True)
country =models.CharField(max_length=3, choices=COUNTRIES,
blank=True)
def get_absolute_url(self):
return reverse('accounts:customer_company_detail',kwargs={'pk':self.pk})
def __str__(self):
return self.name
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,
primary_key=True, related_name='customer_profile')
company = models.ForeignKey(CustomerCompany, on_delete=models.CASCADE, null=True)
phone = models.CharField(max_length=10)
def __str__(self):
return self.user.first_name + ' ' + self.user.last_name
forms.py
class CustomerSignupForm(UserCreationForm):
first_name = forms.CharField(max_length=50, required=True)
last_name = forms.CharField(max_length=50, required=True)
phone = forms.CharField(max_length=10, required=True)
email = forms.EmailField(required=True)
class Meta(UserCreationForm.Meta):
model = User
#transaction.atomic
def save(self, commit=True):
user = super(CustomerSignupForm, self).save(commit=False)
user.is_customer = True
user.first_name = self.cleaned_data.get('first_name')
user.last_name = self.cleaned_data.get('last_name')
user.email = self.cleaned_data.get('email')
user.save()
customer = Customer.objects.create(user=user)
customer.phone = self.cleaned_data.get('phone')
customer.save()
return user
class CustomerCompanyCreateForm(forms.ModelForm):
ca_province = CAProvinceField(required=False, label="Province")
ca_postal_code = CAPostalCodeField(required=False, label="Postal Code")
class Meta:
model = CustomerCompany
fields = ['name', 'website', 'phone', 'address', 'city', 'state',
'us_zipcode', 'country', 'ca_province', 'ca_postal_code']
labels = {
"us_zipcode": "Zipcode",
}
views.py Updated with working code
def customer_signup(request):
if request.method == 'POST':
customer_form = CustomerSignupForm(request.POST)
customer_company_form = CustomerCompanyCreateForm(request.POST)
if customer_form.is_valid() and customer_company_form.is_valid():
# first save the user object
user_obj = customer_form.save(commit=False)
# Then use this object to get to my Customer model via the related name
customer = user_obj.customer_profile
# now save the CustomerCompany
company = customer_company_form.save()
# attach the customer to the Company
customer.company = company
# now fully save the customer after he's attached to his company
customer.save()
return redirect('customer_dashboard:customer_dashboard')
else:
messages.error(request, 'Please correct the errors below.')
else:
customer_form = CustomerSignupForm()
customer_company_form = CustomerCompanyCreateForm()
return render(request, 'accounts/registration/customer_signup_combined.html', {
'customer_form' : customer_form,
'customer_company_form' : customer_company_form,
})
You're saving both forms in your view but you're not connecting the two objects.
Calling save on the customer_form will return a User object since its a User ModelForm. You can use this object to get to the Customer object via the customer_profile related_name and set the company field to the Company instance returned when you save the customer_company_form.
It should look like this:
if customer_form.is_valid() and customer_company_form.is_valid():
user_obj = customer_form.save(commit=True)
customer = user_obj.customer_profile
company = customer_company_form.save(commit=True)
customer.company = company
customer.save()
return redirect('customer_dashboard:customer_dashboard')
models.py
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
def __unicode__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author, blank=True)
publisher = models.ForeignKey(Publisher, blank=True, null=True)
def __unicode__(self):
return self.title
forms.py
class Books(forms.ModelForm):
class Meta:
model = Book
fields = ('title', 'authors', 'publisher',)
class Authors(forms.ModelForm):
class Meta:
model = Author
fields = ('first_name', 'last_name', 'email',)
class Publishers(forms.ModelForm):
class Meta:
model = Publisher
fields = ("id","name", 'address', 'city', 'state_province', 'country',)
views.py
def demo(request):
form1 = Books(request.POST)
form2 = Authors(request.POST)
form3 = Publishers(request.POST)
if (form1.is_valid() & form2.is_valid() & form3.is_valid()):
form3.save()
form2.save()
// Here I want to access id of just saved data of Model Publisher and Model Authors
form1.cleaned_data['publisher'] = form3.data['id']
return render(request, 'files/demo.html', {'form1': form1, 'form2': form2, 'form3': form3})
In Above code I want to save all data of all models in single view But errro is that Book model has ForenignKey relation with Publisher and Publisher doens't not have any unique data to identify the ID of just saved data. So My real question is that how can I access the Publisher and Author ID that data is saved using `
form3.save() and form2.save()
`I'm very confused to save multiple model data with same time with handle forenignkey relation between them.
save() returns the object, so you just need to do
publisher_obj = form3.save()
author_obj = form2.save()
book_obj = form1.save(commit=False)
book_obj.publisher = publisher_obj
book_obj.save()
book_obj.authors.add(author_obj)
and remove the 'id' from the form. You don't need it.