I am building a hospital management app and I am currently building the Nurse's webpage. In that webpage, I would like the following to display: a list of all employed nurses, a list of their workshifts, and what departments they work for.
I am trying to get the department section to display but I keep getting an error "too many values to unpack (expected 2)".
What can I do so that the nurses' department shows?
Models.py
from django.db import models
# Create your models here.
#Work Related aka Department and Work Shift
class Department(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name
class WorkShift(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
start_datetime = models.DateTimeField(null=True, blank=True)
end_datetime = models.DateTimeField(null=True, blank=True)
def __str__(self):
return self.name
#Personel Related aka Employees and Patients
class Doctor(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
department = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Nurse(models.Model):
name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, null=True)
phone = models.CharField(max_length=200, null=True)
sector = models.ForeignKey(Department, null=True, blank=True, on_delete=models.CASCADE)
reports_to = models.ForeignKey(Doctor, blank=True, null=True, on_delete=models.CASCADE)
work_shift = models.OneToOneField(WorkShift, default="", blank=True, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Patient(models.Model):
STATUS = (
('Sick', 'Sick'),
('Healing', 'Healing'),
('Cured', 'Cured'),
('Deceased', 'Deceased'),
)
name = models.CharField(max_length=200, null=True, blank=True)
description = models.TextField(blank=True, null=True)
status = models.CharField(max_length=200, null=True, blank=True, choices=STATUS)
department = models.ForeignKey(Department, default="", null=True, blank=True, on_delete=models.CASCADE)
care = models.ForeignKey(Nurse, default="", blank=True, null=True, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
def __str__(self):
return self.name
from django.shortcuts import render, redirect
Views.py
# Create your views here.
from django.shortcuts import render
from .models import Doctor, Nurse, Patient, Department, WorkShift
from django.http import HttpResponse
from .forms import DoctorForm, NurseForm, PatientForm
# Create your views here.
def index(request):
patient = Patient.objects.all()
nurse = Nurse.objects.all()
doctor = Doctor.objects.all()
department = Department.objects.all()
total_patient = patient.count()
sick = patient.filter(status='Sick').count()
healing = patient.filter(status='Healing').count()
cured = patient.filter(status='Cured').count()
total_nurse = nurse.count()
# if request.method == 'POST':
# form =
context = {
'patient':patient, 'nurse':nurse,
'doctor':doctor, 'total_patient':total_patient,
'sick':sick, 'healing':healing, 'cured':cured,
'total_nurse':total_nurse,
'department':department
}
return render(request, 'lifesaver/index.html', context)
#All Patient Related
def patient(request):
patient = Patient.objects.all()
context = {'patient':patient}
return render(request, 'lifesaver/patient.html', context)
def patient_add(request):
patient = Patient.objects.all()
form = PatientForm()
if request.method == 'POST':
form = PatientForm(request.POST)
if form.is_valid():
print("Patient Form is Valid")
form.save()
else:
print("Patient Form is Invalid")
print(form.errors)
return redirect('patient')
context = {'form':form,}
return render(request, 'lifesaver/patient_add.html', context)
def patient_update(request, pk):
patient = Patient.objects.get(id=pk)
form = PatientForm(instance=patient)
if request.method == 'POST':
form = PatientForm(request.POST, instance=patient)
if form.is_valid():
print('Update completed')
form.save()
return redirect('patient')
else:
print('Update not completed')
print(form.errors)
context = {'form':form}
return render(request, 'lifesaver/patient_update.html', context)
#All Doctor Related
def doctor(request):
doctor = Doctor.object.all()
context = {}
return render(request, 'lifesaver/doctor.html', context)
def doctor_add(request):
doctor = Doctor.object.all()
form = DoctorForm()
context = {'doctor':doctor, 'form':form}
return render(request, 'lifesaver/doctor')
def doctor_update(request):
doctor = Doctor.object.all()
form = DoctorForm()
context = {'doctor':doctor, 'form':form}
# Nurse Related
def nurse(request):
nurse = Nurse.objects.all()
workshift = WorkShift.objects.all()
department = Nurse.objects.get('sector')
context = {'nurse':nurse, 'workshift':workshift, 'department':department}
return render(request, 'lifesaver/nurse.html', context)
def nurse_add(request):
nurse = Nurse.objects.all()
form = NurseForm()
if request.method == 'POST':
form = NurseForm(request.POST)
if form.is_valid():
print("Nurse Form is Valid")
form.save()
else:
print("Nurse Form is Invalid")
print(form.errors)
return redirect('nurse')
context = {'form':form,}
return render(request, 'lifesaver/nurse_add.html', context)
def nurse_update(request):
nurse = Nurse.objects.all()
form = NurseForm()
context = {}
return render(request, 'lifesaver/nurse_update.html', context)
#Work Related
def department(request):
department = Department.objects.all()
context = {'department':department}
return render(request, 'lifesaver/department.html', context)
Forms.py
from django import forms
from django.forms import ModelForm
from .models import Doctor, Nurse, Patient, Department, WorkShift
from django.contrib.auth.forms import UserCreationForm
class DoctorForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Doctor',
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs=
{
'class': 'selectpicker',
'placeholder': 'Department',
}
))
class Meta:
model = Doctor
fields = ['name', 'department']
class NurseForm(forms.ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
class Meta:
model = Nurse
fields = ['name']
class PatientForm(ModelForm):
name = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': 'Add a New Nurse',
'class': 'form-control'
}
))
description = forms.CharField(widget = forms.TextInput(attrs =
{
'placeholder': "Describe the patient's symptoms",
'class': 'form-control'
}
))
department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs=
{
'class': 'selectpicker',
'placeholder': 'Select Department',
}
))
class Meta:
model = Patient
fields = ['name', 'description', 'department', 'care', 'status']
#Work Related
class WorkShiftForm(ModelForm):
class Meta:
model = WorkShift
fields = '__all__'
Nurse.html
{% extends 'lifesaver/main.html' %}
{% block content %}
{% for nurse in nurse %}
{{nurse.name}}
{{nurse.report_to}}
{{nurse.care}}
{{nurse.work_shift}}
{{department}}
{% endfor %}
{% endblock %}
In models.py, Nurse object has field 'sector' which is a Foreign Key to a Department record. So part of the problem is you're trying to output the wrong field name in your template as there is no actual department field defined on Nurse model.
Try these edits to views.py:
nurses = Nurse.objects.all()
then in your context: context = {..., 'nurses': nurses, ...}
Then in nurse.html:
{% for nurse in nurses: %}
...
{{ nurse.sector.name }}
{% endfor %}
That should at least get your nurse objects rendered in the template. But you have a potential issue in calling nurse.sector when that FK is defined in the Nurse model with null=True. So a better practice would be to define an accessor method in the Nurse model to check if sector is present before calling it's name, i.e.:
# in Nurse model
def department_name(self):
if self.sector_id:
return self.sector.name
else:
return '' # or some other default
Then you could edit nurse.html again replacing my code above with:
{% for nurse in nurses: %}
...
{{ nurse.department_name }}
{% endfor %}
This is just scratching the surface of how you could handle this but it hopefully answers your question and prevents a common error once you make these edits.
You'll also probably want to look into Django QuerySet API's select_related() and prefetch_related() methods to avoid N+1 query issues that are possible in your current code. See here and here for more background.
So for example, to avoid N+1, instead of calling nurses = Nurse.objects.all() instead do nurses = Nurse.objects.select_related('sector').all(). That will do a join to the Department model on the FK. This answer to one of the above N+1 questions has more details.
you need to pass a field and a value, e.g.
Nurse.objects.get('sector' = 'dentistry')
or if you want to display a specific nurses department you would use this in your template:
{{nurse.department.name}}
Related
I have a form in my template which I have used the django-crispy-forms to implement. I have the models.py, and then created the forms.py and then used it in my views.py. I don't know why I keep having the "This field is required." whenever I load the page. I have some feelings that it has to do with the views.py thou. I would be glad if i could receive some solutions. Thanks
This is the image of the page.
models.py
class add_courses(models.Model):
Course_Name = models.CharField(max_length=200)
Manager_Name = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE)
choices = (
("online", "online"),
("in person", "in person")
)
description = models.TextField(default='')
syllabus = models.TextField(default='')
classroom = models.CharField(choices=choices, default='in person', max_length=12)
location = models.CharField(max_length=40, default='')
course_code = models.CharField(max_length=14, default='')
student = models.ManyToManyField(add_students_by_manager)
teacher = models.ManyToManyField(add_teacher_by_manager)
schedule = models.ForeignKey(course_schedule, on_delete=models.CASCADE)
def __str__(self):
return self.Course_Name
views.py
def manager_page(request):
if request.method=="POST":
manager_id = request.POST.get('manager_id')
manager_name = request.POST.get('manager_name')
form3 = AddCourses()
if request.method == "POST":
form3 = AddCourses(request.POST)
if form3.is_valid():
form3.save()
return redirect("/")
# get_course_details = add_course.objects.all()
courses = add_courses.objects.all().order_by('-id')
get_supervisor_man=manager_supervisor.objects.filter(manager_id=manager_id)
Manager_login_information_get1 = Manager_login_information.objects.get(manager_ID=manager_id)
# print(Manager_login_information_get1)
manager_usid = Manager_login_information_get1.manager_ID
manager_usname = Manager_login_information_get1.manager_Name
context9 = {'manager_id':manager_id, 'manager_name':manager_name, 'form1':form1, 'form2':form2, 'form3':form3, 'courses':courses, 'Manager_login_information_get1':Manager_login_information_get1}
return render(request, 'manager_page.html', context9)
else:
return redirect('/')
In your model, you have to add blank=True to allow blank fields.(default is False)
So you model will look something like this:
class add_courses(models.Model):
Course_Name = models.CharField(max_length=200, blank=True)
...
...
I have a django ecommerce project that works fine till I decided to improve it. User place order and every time they place an order they have to always input their details (name, emil, address etc) , I decided to upgrade the application so if user had registered before no need to enter details again .
orders/models.py
from django.db import models
from django.contrib.auth.models import User
from shop.models import Product
from decimal import Decimal
from django.core.validators import MinValueValidator,MaxValueValidator
from coupons.models import Coupons
class order(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
address = models.CharField(max_length=250)
postal_code = models.CharField(max_length=50)
city = models.CharField(max_length=100)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True)
discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)])
class Meta:
ordering = ('-created',)
verbose_name = "order"
verbose_name_plural = "orders"
def __str__(self):
return 'Order {}'.format(self.id)
def get_total_cost(self):
return sum(item.get_cost() for item in self.items.all())
def get_total_cost_after_discount(self):
total_cost = sum(item.get_cost() for item in self.items.all())
return total_cost - total_cost * (self.discount / Decimal('100'))
class OrderItem(models.Model):
order = models.ForeignKey(order,related_name='items',on_delete=models.CASCADE)
product = models.ForeignKey(Product,related_name='order_items',on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10,decimal_places=2)
quantity = models.PositiveIntegerField(default=1)
class Meta:
verbose_name = "OrderItem"
verbose_name_plural = "OrderItems"
def __str__(self):
return '{}'.format(self.id)
def get_cost(self):
return self.price * self.quantity
I create account app and extended django user so that user can register address so that the user does not have to type it every time when place an order.
accounts/models.py
class UserProfile(models.Model):
user = models.OneToOneField(User,related_name='UserProfiles',on_delete=models.CASCADE)
country = models.CharField(max_length=300, default='Saudi Arabia')
city = models.CharField(max_length=100, default='')
phone = models.CharField(max_length=15,default='')
image = models.ImageField(upload_to='profile_image', blank=True)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(null=True)
def __str__(self):
return self.user.username
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = UserProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
and rewrite:
orders/models.py
class order(models.Model):
user = models.ForeignKey(User,on_delete=models.DO_NOTHING)
address = models.ForeignKey(UserProfile,on_delete=models.DO_NOTHING)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
paid = models.BooleanField(default=False)
coupon = models.ForeignKey(Coupons,related_name='orders',on_delete=models.CASCADE ,null=True,blank=True)
discount = models.IntegerField(default=0,validators=[MinValueValidator(0),MaxValueValidator(100)])
now my problem is how can I fix the view to show form of user address with information if user entered before or the user fill form with address
views.py
#login_required
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if cart.coupon:
order.coupon = cart.coupon
order.discount = cart.coupon.discount
order.save()
for item in cart:
OrderItem.objects.create(
# user = User.username,
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
context = {
'order':order,
}
return render(request, 'created.html',context)
else:
form = OrderCreateForm()
context = {
'cart':cart,
'form':form
}
return render(request, 'create.html',context)
orders/forms.py
from django import forms
from .models import order
class OrderCreateForm(forms.ModelForm):
class Meta:
model = order
fields = ('first_name','last_name','email','address','postal_code','city',)
I don't see your OrderCreateForm, but I'm assuming it has fields that match the ones in UserProfile. If so, try changing the view code to pull data from the profile to populate the initial data:
#login_required
def order_create(request):
cart = Cart(request)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
if cart.coupon:
order.coupon = cart.coupon
order.discount = cart.coupon.discount
order.save()
for item in cart:
OrderItem.objects.create(
# user = User.username,
order=order,
product=item['product'],
price=item['price'],
quantity=item['quantity'])
cart.clear()
context = {
'order':order,
}
return render(request, 'created.html',context)
else:
if request.user and hasattr(request.user, 'UserProfiles'):
profile = request.user.UserProfiles
initial = {
'first_name', request.user.first_name,
'last_name', request.user.last_name,
'email', request.user.email,
'address': profile.address,
'city': profile.city
}
else:
initial = {}
form = OrderCreateForm(initial=initial)
context = {
'cart':cart,
'form':form
}
return render(request, 'create.html',context)
I am a newbie in Django and I have learn some basic things about it. My problem is, I get data from django models but I am not able to pass/display it to a form. I would like to have a forms.py with 1 phone_id Selector and 3 textInputs in order to insert data to the desired phone.
My models.py:
class Phone(models.Model):
user = models.ForeignKey(User)
num_calls = models.CharField(max_length=20, null=True, blank=True)
time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
psap = models.CharField(max_length=30, null=True, blank=True)
My forms.py:
from django import forms
class phoneForm(forms.Form):
NumberOfCalls = forms.CharField(
min_length = 1,
widget=forms.TextInput({'class': 'form-control'})
)
TimeBetweenCalls = forms.CharField(
widget=forms.TextInput({'class': 'form-control'})
)
PSAP = forms.CharField(
min_length = 1,
widget=forms.TextInput({'class': 'form-control'})
)
def __init__(self, *args, **kwargs):
phone_choices = kwargs.pop('phone_choices')
super(Send2tcu, self).__init__(*args, **kwargs)
self.fields['phone'] = forms.MultipleChoiceField(
required = True,
widget = forms.Select({'class': 'form-control'}),
choices = phone_choices
)
I just create a form with the 3 textInputs and the MultipleChoiceField where I need to display the data from the differents phone_id.
My view.py:
def phone_config(request):
phones = Phone.objects.filter(user_id = request.user.id).values_list('id', flat=True)
if request.method == 'POST':
form = phoneForm(request.POST, phone_choices=phones)
if form.is_valid():
cleaned_data = form.cleaned_data
phone_id = cleaned_data.get('phone')
NumberOfCalls = cleaned_data.get('NumberOfCalls')
TimeBetweenCalls = cleaned_data.get('TimeBetweenCalls')
PSAP = cleaned_data.get('PSAP')
Tcu.objects.filter(id=phone_id).update(
num_calls = NumberOfCalls,
time_btwn_calls = TimeBetweenCalls,
psap = PSAP,
)
return redirect(reverse('gracias'))
else:
form = phoneForm(phone_choices=phones)
return render(request, 'configurer/configurer.html', {'form': form})
def gracias_view(request):
return render(request, 'configurer/gracias.html')
In my view first of all, I get the all the phone_id for the current user. Then I check if the method is post and I get the data from the form and also I pass to the form the different phone_ids.Then I check if the form is valid and I create the object Phone. After that assign the different parameters to the selected phone_id and save them.
There is something wrong in my code. I am getting this error:
TypeError at /configurer/
'int' object is not iterable
return render(request, 'heroconfigurer/heroconfigurer.html', {'form':
form})
models.py:
class Phone(models.Model):
user = models.ForeignKey(User)
num_calls = models.CharField(max_length=20, null=True, blank=True)
time_btwn_calls = models.CharField(max_length=20, null=True, blank=True)
psap = models.CharField(max_length=30, null=True, blank=True)
forms.py:
from django.forms.widgets import TextInput, Select
class PhoneViewForm(ModelForm):
class Meta:
model = Phone
widgets = {'user': Select(attrs={'class': 'form-control'}),
'num_calls': TextInput(attrs={'class': 'form-control'}),
'time_btwn_calls': TextInput(attrs={'class': 'form-control'}),
'psap': TextInput(attrs={'class': 'form-control'})
}
fields = ['user',
'num_calls',
'time_btwn_calls',
'psap'
]
If you manipulate model objects in your form Django recommends you to use ModelForm. You also may fill this form with initial model instance. Hope that helps.
I load the form. I need to in the text field city shows the initial value.
models:
class City(models.Model):
city = models.CharField(
max_length=40, blank=True,
)
class UserProfile(User):
family = models.CharField(
'Фамилия', max_length=30, blank=True, null=True,
)
city = models.ForeignKey(
City, verbose_name='Город', max_length=50, blank=True, null=True,
)
forms:
class PersonalDataForm(forms.ModelForm):
city = forms.CharField(
label='Город',
required=False,
)
class Meta:
model = UserProfile
fields = (
'family',
)
def save(self):
obj = super(PersonalDataForm, self).save(commit=False)
city_name = self.cleaned_data.get('city', None).strip()
if city_name:
if City.objects.filter(city=city_name).exists():
obj.city = City.objects.get(city=city_name)
else:
rec = City(city=city_name)
rec.save()
obj.city = rec
else:
obj.city = None
return obj.save()
views:
def personal_data_page(request):
entry_user_profile = UserProfile.objects.get(user_ptr_id=request.user.id)
form = PersonalDataForm(instance=entry_user_profile)
if request.method == 'POST':
form = PersonalDataForm(request.POST, instance=entry_user_profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/userprofile/personal_data_page_changed/')
t = loader.get_template('personal_data_page.html')
c = RequestContext(request, {
'form': form,
}, [custom_proc])
return HttpResponse(t.render(c))
template.html:
{{ family.city }}
{{ form.city }}
the problem is that when loading the form field 'city' is empty. but it must contain the value from the table (table full of values)
If you use this pattern, the initial value should be visible:
if request.method=='POST':
data=request.POST
else:
data=None
form=MyForm(data, initial=...)
if (not data is None) and form.is_valid():
form.save()
return django.http.HttpResponseRedirect(...)
return HttpResponse(render(...))
I am very new to Django as well as Python. I am trying to build a small Resource management tool. Below is what I have come up with till now.
I Extended a User Model
I have created other required models like Current address Permanent Address etc.
I have a sample form in forms.py
I have a profile.html page.
As of now when a user is logged , and when he clicks on update profile he is redirected to Profile.html page where he gets fields from ModelForm Employee (Data pulled from DB) which is just a extended userModel. (Infact user should not be able to edit any of the field in this form, this should be just a read only field as this will be set by Admin, but this Problem is later part for me, I do not know how to bring as a ReadOnly field have not researched yet on this)
What I want to do is now I want to show all the other forms also (ModelForms of Current Address, Permanent address etc on the same same page for that particular user so he can update the records) Till now I tried different methods but I couldn't get hold of any proper solution Can anyone help me on this. Below are my models, views, forms and html page. I am open for any alternative solution which is easy and secure as this I have started recently so I am ok to change whatever required to be changed. All the other models are linked to foreign Key emp_id from Employee model. Apologies for the Long question but I am stuck at this point and I unable to go ahead from this point.
Forms:
#User Profile Form to update the user profile
class UserProfileForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper(self)
# You can dynamically adjust your layout
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
Field('text_input', css_class='input-xlarge'),
Field('textarea', rows="3", css_class='input-xlarge'),
'radio_buttons',
Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),
AppendedText('appended_text', '.00'),
PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),
PrependedText('prepended_text_two', '#'),
'multicolon_select',
FormActions(
Submit('save_changes', 'Save changes', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
)
)
self.helper.layout.append(Submit('save_changes', 'Update'))
class Meta:
model = Employee
exclude = ('user',)
Views:
#login_required
def user_profile(request):
if request.method == 'POST':
form = UserProfileForm(request.POST, instance=request.user.profile)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/loggedin/')
else:
user = request.user
profile = user.profile
form = UserProfileForm(instance=profile)
args = {}
args.update(csrf(request))
args['form'] = form
return render_to_response('profile.html', args)
profile.html:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h2> Profile </h2>
{% crispy form %}
{% endblock %}
Models.
#Department Model
class Dept(models.Model):
dept_name = models.CharField(max_length=30)
def __unicode__(self):
return self.dept_name
#Extending User Model
class Employee(models.Model):
user = models.OneToOneField(User, null=True, blank = True, verbose_name="User Id")
emp_id = models.IntegerField(primary_key=True, max_length=5, verbose_name="Employee Id")
emp_first = models.CharField('First Name',max_length=20)
emp_middle = models.CharField('Middle Name', blank=True, max_length=20)
emp_last = models.CharField('Last Name',max_length=20)
emp_email = models.EmailField('Email Id')
emp_dept = models.ForeignKey(Dept, verbose_name="Department")
def __unicode__(self):
return self.emp_first
User.profile = property(lambda u: Employee.objects.get_or_create(user=u)[0])
#Current Address Model
class CurrentContact(models.Model):
emp = models.ForeignKey(Employee)
emp_add = models.TextField('Current Address')
emp_city = models.CharField('City', max_length=20, default = 'Bangalore')
emp_state = models.CharField('State', max_length=20, default= 'Karnataka')
emp_country = models.CharField('Country', max_length=20, default = 'India')
emp_mobile1 = models.IntegerField('Mobile1',max_length=12)
emp_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emp_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emp_PerEmail = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.emp
#Permanent Address Model
class PermanentContact(models.Model):
emp = models.ForeignKey(Employee)
emp_add = models.TextField('Permanent Address')
emp_city = models.CharField('City', max_length=20, default = 'Bangalore')
emp_state = models.CharField('State', max_length=20,default= 'Karnataka')
emp_country = models.CharField('Country', max_length=20, default = 'India')
emp_mobile1 = models.IntegerField('Mobile1',max_length=12)
emp_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emp_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emp_PerEmail = models.EmailField('Personal Email Id', blank=True)
def __unicode__(self):
return self.emp
#Emergency Contact Model
class Emergency(models.Model):
emp = models.ForeignKey(Employee)
emrg_name = models.CharField('Full Name', max_length=30)
emrg_add = models.TextField('Full Address')
emrg_city = models.CharField('City', max_length=20, default = 'Bangalore')
emrg_state = models.CharField('State', max_length=20,default= 'Karnataka')
emrg_country = models.CharField('Country', max_length=20, default = 'India')
emrg_mobile1 = models.IntegerField('Mobile1', max_length=12)
emrg_mobile2 = models.IntegerField('Mobile2', null=True, blank=True, max_length=12)
emrg_landline = models.IntegerField('Land Line',null=True, blank=True, max_length=12)
emrg_PerEmail = models.EmailField('Email Id', blank=True)
def __unicode__(self):
return self.emp
Have you taken a look here:
Django: Changing User Profile by forms
It seems like an almost identical question to yours.