Connecting a Symptom Object to and Identity Object in my Health App - django

I am creating a Health App that will take the Identity, Symptom, Disease and Treatment of the patient.
I have created models: Identity, Symptom, Disease, Treatment.
I am using form.ModelForm so that I can save the data to the db i.e. sqlite3.
I have created class based views that will handle forms, take field values, sanitize the data, and render the required form and values.
Problem: Each time I attempt to save values for the Symptom form it
seems to save it, and redirect to a new form but I am not seeing it in
the Admin Backend.
Code:
Model document
from django.db import models
from django.utils import timezone
import datetime
class Identity(models.Model):
NIS =models.CharField(max_length = 200, primary_key = True)
timestamp = models.DateTimeField(auto_now = True)
first_name = models.CharField(max_length = 80, null = True)
last_name = models.CharField(max_length = 80, null = True )
contact = models.CharField(max_length = 15, null = True)
location = models.CharField(max_length = 100, blank = True)
birthday= models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return '%s, %s' % (self.first_name ,self.last_name)
class Symptom(models.Model):
condition_name = models.CharField(max_length = 80, default = '')
description = models.TextField(max_length = 1000, default = '')
def __str__(self):
return self.condition_name
class Disease(models.Model):
disease_name = models.CharField(max_length = 80, default = '')
description = models.TextField(max_length = 1000, default = '')
def __str__(self):
return self.disease_name
class Treatment(models.Model):
term = models.CharField(max_length = 80, default = '')
treatment = models.TextField()
patient = models.ManyToManyField(Identity, through = 'Consultation')
date_done = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return self.Term
class Consultation(models.Model):
patient_identity = models.ForeignKey(Identity)
patient_condition = models.ForeignKey(Symptom)
patient_disease = models.ForeignKey(Disease)
patient_treatment = models.ForeignKey(Treatment)
date_seen = models.DateField(auto_now = False, auto_now_add = False, blank = True, null = True)
def __str__(self):
return '%s' %(self.patient_identity)
Views document
from django.shortcuts import render, redirect
from django.views.generic import CreateView, ListView, DetailView, FormView, TemplateView
from patient.models import Identity, Symptom, Treatment, Disease, Consultation
from patient.forms import IdentityScript, SymptomScript
class Identity_view(CreateView):
model = Identity
template_name = 'patient/script.html'
def get(self, request):
form = IdentityScript()
script = Identity.objects.all()
var = {'form':form, 'script':script}
return render(request, self.template_name, var)
def post(self, request):
form = IdentityScript(request.POST)
being = None
if form.is_valid():
NIS = form.save(commit = False)
NIS.user = request.user
NIS.save()
being = form.cleaned_data['first_name']
form = IdentityScript()
return redirect('script:script')
var = {'form':form, 'being':being}
return render(request, self.template_name, var)
class Identity_list_view(ListView):
model = Identity
template_name = 'patient/Identity_list.html'
def get(self, request):
form = IdentityScript()
script = Identity.objects.all().order_by('-Timestamp')
var = {'form':form, 'script':script}
return render(request, self.template_name, var)
class Medical_document(CreateView):
model = Symptom
template_name = 'patient/medical_document.html'
def get(self, request, pk):
form = SymptomScript()
expression = Symptom.objects.all()
var = {'form':form, 'expression':expression, 'pk':pk}
return render(request, self.template_name, var)
def post(self, request, pk):
form = SymptomScript()
state = None
if form.is_valid():
manuscript = form.save(commit = False)
manuscript.user = request.user
state = form.cleaned_data['description']
manuscript.save()
patient = Identity.objects.get(pk=pk)
form = SymptomScript()
redirect('script:script')
else:
print(form)
var = {'form': form, 'state':state, 'pk':pk}
return render(request, self.template_name, var)
Forms document
from django import forms
from patient.models import Identity, Symptom, Disease
class IdentityScript(forms.ModelForm):
NIS = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter NIS',
'class' : 'form-control'
}
)
)
first_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter First Name',
'class' : 'form-control'
}
)
)
last_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Last Name',
'class' : 'form-control'
}
)
)
contact = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder':'Enter Contact',
'class':'form-control'
}
)
)
born = forms.DateField(
widget = forms.TextInput(
attrs = {
'placeholder' : 'Enter Birth',
'class':'form-control'
}
)
)
location = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder':'Enter location',
'class':'form-control'
}
)
)
class Meta:
model = Identity
fields = ('NIS', 'first_name', 'last_name', 'birthday', 'location', 'contact', )
class DiseaseScript(forms.ModelForm):
disease_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Disease Name',
'class' : 'form-control'
}
)
)
description = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter description',
'class' : 'form-control'
}
)
)
class Meta:
model = Disease
fields = ('disease_name', 'description')
# Create SymptomScript form
class SymptomScript(forms.ModelForm):
condition_name = forms.CharField(
widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Condition Name',
'class' : 'form-control'
}
)
)
description = forms.CharField(
widget = forms.Textarea(
attrs = {
'placeholder': 'Enter Description',
'class' : 'form-control'
}
)
)
class Meta:
model = Symptom
fields = ('condition_name', 'description')

Related

Create view with more models

hi everyone I have a doubt with the use of forms and models.
I have to create a code that creates records in multiple tables and I don't know how to do it.
my goal is to create a page where I can enter all the data and when I save it creates the various tables filled in with the data provided by the user.
I'm a beginner I still have to learn the mechanism well =)
forms.py
from django import forms
from .models import Schede, DatiGruppi, Gruppi
class CreaSchedaForm(forms.ModelForm):
nome_scheda = forms.CharField(
required = True,
label ='Nome scheda',
widget = forms.TextInput(
attrs = {
'class': 'form-control',
'placeholder' : 'nome scheda',
'autocomplete' : 'off'
}
)
)
data_inizio = forms.DateField(
label='Data inizio',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data inizio'
}
)
)
data_fine = forms.DateField(
label='Data fine',
widget = forms.DateInput(
attrs= {
'type': 'date',
'class': 'form-control',
'placeholder' : 'data fine'
}
)
)
class Meta:
model = Schede
fields = ['nome_scheda','data_inizio','data_fine']
class CreaDtGruppoForm(forms.ModelForm):
giorni_settimana = forms.ChoiceField(
choices = DatiGruppi.giorni_settimana_scelta
)
dati_gruppo = forms.ModelChoiceField(
queryset = Gruppi.objects.all(),
empty_label = "-",
required = True
)
class Meta:
model = DatiGruppi
fields = ['giorni_settimana', 'dati_gruppo']
views.py
#login_required
def creaScheda(request):
if request.method == "POST":
form = CreaSchedaForm(request.POST)
if form.is_valid():
scheda = form.save(commit = False)
scheda.utente = request.user
scheda.save()
else:
form = CreaSchedaForm()
context = {"form": form}
return render(request, "crea_scheda.html", context)

Initializing foriegnkey in CRUD operation

i am working on a project to manage animal farm. The backend is with django and the frot end is with bootstrap. The project has several apps as in django documentation.
views.py
from django.shortcuts import render,redirect, get_object_or_404
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from livestockrecords.models import *
from .models import *
from .forms import *
from .models import *
from .forms import *
def save_feedin_form(request, form, template_name):
data = dict()
if request.method == 'POST':
if form.is_valid():
form.save()
data['form_is_valid'] = True
livestocks = Livestock.objects.all()
context ={
'livestocks': livestocks
}
data['html_livestock_list'] =
render_to_string('includes/_list_feeding.html', context)
else:
data['form_is_valid'] = False
context = {'form': form}
data['html_form'] = render_to_string(template_name, context, request=request)
return JsonResponse(data)
def feeding_add(request, pk):
livestocks = get_object_or_404(Livestock, pk=pk)
data = dict()
if request.method == 'POST':
form = FeedingForm(request.POST , initial={'livestock': pk})
else:
form = FeedingForm(initial={'livestock': livestocks})
return save_feedin_form(request, form, 'includes/_add_feeding.html')
models.py
from django.db import models
from livestockrecords.models import Livestock
# Create your models here.
class Addmedication(models.Model):
MEDICATIONTYPE = (
('Drugs', 'Drugs'),
('Vaccination', 'Vaccination'),
)
name = models.CharField(max_length=200, null=True)
medicationType = models.CharField(max_length=200, null=True, choices= MEDICATIONTYPE)
def __str__(self):
return self.name
class Adddisease(models.Model):
name = models.CharField(max_length=200, null=True)
description = models.TextField(null=True)
def __str__(self):
return self.name
class DailyRecords(models.Model):
livestock = models.ForeignKey(Livestock, null=True, on_delete = models.SET_NULL)
dateAdded =models.DateTimeField(auto_now_add=True, null=True)
datepurchased=models.DateField(auto_now_add=False, null=True)
class Meta:
abstract = True
class Mortality(DailyRecords):
qty = models.IntegerField()
cause = models.TextField(null=True)
class Medication(DailyRecords):
medication = models.ForeignKey(Addmedication, null=True, on_delete = models.SET_NULL)
disease = models.ForeignKey(Adddisease, null=True, on_delete = models.SET_NULL)
class Feeding(DailyRecords):
feedname = models.CharField(max_length=200, null=True)
qty = models.FloatField()
forms.py
from django import forms
from django.forms import ModelForm
from .models import *
class FeedingForm(ModelForm):
class Meta:
model = Feeding
fields = ['livestock','datepurchased', 'feedname', 'qty']
labels = {
'livestock':'',
'datepurchased': '',
'feedname': '',
'qty': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'feedname':forms.TextInput(attrs = {
'placeholder': 'feed name *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Quantity of feed in kg *',
'class': 'form-control'}),
}
class mortalityForm(ModelForm):
class Meta:
model = Mortality
fields = ['livestock','datepurchased', 'qty', 'cause']
labels = {
'livestock':'',
'datepurchased': '',
'qty': '',
'cause': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'cause':forms.TextInput(attrs = {
'placeholder': 'Cause of Mortality *',
'class': 'form-control'}),
'qty':forms.TextInput(attrs = {
'placeholder': 'Number *',
'class': 'form-control'}),
}
class MedicationForm(ModelForm):
class Meta:
model = Medication
fields = ['livestock','datepurchased', 'medication', 'disease']
labels = {
'livestock':'',
'datepurchased': '',
'medication': '',
'disease': '',
}
widgets = {
'livestock': forms.HiddenInput(),
'datepurchased':forms.TextInput( attrs={
'placeholder': 'Date Added *',
'class': 'form-control',
'type': 'date',
}),
'medication':forms.Select(attrs = {
'placeholder': 'Drug name *',
'class': 'form-control'}),
'disease':forms.Select(attrs = {
'placeholder': 'Disease Name *',
'class': 'form-control'}),
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
# livestockrecords
path('', views.daily_home, name = "daily-home"),
path('daily-feeding/<str:pk>/', views.feeding_add, name = "daily-feeding"),
]
In the view.py, the form is an ajax form. it display but when i hit the add button it will not capture the foriegnkey.
When i run the code i get this: error raise e.class(
ValueError: Field 'id' expected a number but got 'None'.
Please i need help

How to set initial values for Django Model Form

I am trying to set initial values for my django model form
but when I try in my views.py:
add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'})
It doesn't work. If I specify default values in the model they work fine.
Models.py:
class contact(models.Model):
name = models.CharField(max_length=20, blank=True)
email = models.EmailField(primary_key=True)
tel = PhoneField(null=True, blank=True)
contact_relations = [
('Supplier', 'Supplier'),
('Customer', 'Customer'),
('Other', 'Other'),
]
relation = models.CharField(max_length=50, choices=contact_relations)
Forms.py:
class newContactForm(forms.ModelForm):
class Meta:
model = contact
fields = [
'name',
'email',
'tel',
'relation',
]
widgets = {
'relation': forms.RadioSelect(),
}
Views.py:
def add_contact_view(request):
add_contact_form = newContactForm(request.POST, initial={'relation':'Customer'})
if add_contact_form.is_valid():
add_contact_form.save()
else:
add_contact_form = newContactForm()
context = {
"add_contact_form":add_contact_form,
}
return render(request, 'contacts/new_contact.html', context)
thats because you are not setting them when the page loads, you are initializing when the form is submitted.
def add_contact_view(request):
add_contact_form = newContactForm(request.POST)
if add_contact_form.is_valid():
add_contact_form.save()
else:
add_contact_form = newContactForm(initial={'relation':'Customer'})
context = {
"add_contact_form":add_contact_form,
}
return render(request, 'contacts/new_contact.html', context)

form.is_valid() failing in Django unit test

I'm running a unit test for a Django form, and form.is_valid() keeps returning False and I cannot find the error.
Here's the code for forms.py:
class CustomClearableFileInput(forms.ClearableFileInput):
template_name = 'forums/templates/clearable_file_input.html'
class NewQuestionForm(forms.ModelForm):
category = forms.ModelChoiceField(widget = forms.Select(attrs = {}),
queryset = FossCategory.objects.order_by('name'),
empty_label = "Select a Foss category",
required = True,
error_messages = {'required':'Select a category'})
title = forms.CharField(widget = forms.TextInput(),
required = True,
error_messages = {'required':'Title field required'},
strip=True)
body = forms.CharField(widget = forms.Textarea(),
required = True,
error_messages = {'required':'Question field required'},
strip=True)
is_spam = forms.BooleanField(required = False)
spam_honeypot_field = HoneypotField()
image = forms.ImageField(widget = CustomClearableFileInput(), help_text = "Upload image", required = False)
def clean_title(self):
title = str(self.cleaned_data['title'])
if title.isspace():
raise forms.ValidationError("Title cannot be only spaces")
if len(title) < 12:
raise forms.ValidationError("Title should be longer than 12 characters")
if Question.objects.filter(title = title).exists():
raise forms.ValidationError("This title already exist.")
return title
def clean_body(self):
body = str(self.cleaned_data['body'])
if body.isspace():
raise forms.ValidationError("Body cannot be only spaces")
if len(body) < 12:
raise forms.ValidationError("Body should be minimum 12 characters long")
body = body.replace(' ', ' ')
body = body.replace('<br>', '\n')
return body
class Meta(object):
model = Question
fields = ['category', 'title', 'body', 'is_spam', 'image']
And here's the code for tests.py:
class NewQuestionFormTest(TestCase):
#classmethod
def setUpTestData(cls):
FossCategory.objects.create(name = 'TestCategory', email = 'example#example.com')
def test_too_short_title(self):
category = FossCategory.objects.get(name = "TestCategory")
title = 'shorttitlefsodzo'
form = NewQuestionForm(data = {'category': category, 'title': title, 'body': 'Test question body'})
self.assertTrue(form.is_valid())
This is what I get with print(form.errors):
<ul class="errorlist"><li>category<ul class="errorlist"><li>Select a valid choice. That choice is not one of the available choices.</li></ul></li>
Since it's a model choice field, try using the primary key of the category instead of the instance itself.
form = NewQuestionForm(data = {'category': category.pk, 'title': title, 'body': 'Test question body'})

How do you limit choices in a Django Inlineformset_factory based on User?

I have a Timesheet app and I want to limit the Projects a User can allocate their time to the Projects they are working on.
MODELS My models look like this
class Project (models.Model):
name = models.CharField(
verbose_name = 'Project Title',
max_length = 80
)
code = models.CharField(
verbose_name = 'Project Code',
max_length = 15
)
supervisor = models.ForeignKey (
User,
on_delete=models.CASCADE
)
staff = models.ManyToManyField (
User,
related_name= "project_resources"
)
def __str__(self):
return u'%s' % (self.name)
class Meta:
ordering = ['name']
class Timesheet (models.Model):
user = models.ForeignKey (
User,
on_delete=models.CASCADE)
start_date = models.DateField (
verbose_name = "Start Date"
)
def __str__(self):
return u'%s | %s' % (self.user, self.start_date)
class Meta:
ordering = ['user','start_date']
class TimesheetRow (models.Model):
''' specifies a timesheet row which is unique based on Timesheet, Project and Labour Category
'''
timesheet = models.ForeignKey(
Timesheet,
on_delete=models.CASCADE
)
project = models.ForeignKey(
Project,
on_delete=models.CASCADE
)
labor = models.ForeignKey(
LaborCategory,
on_delete=models.CASCADE
)
sunday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
monday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
tuesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
wednesday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
thursday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
friday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
saturday = models.DecimalField (default = 0, max_digits=4, decimal_places=2)
def __str__(self):
return u'%s | %s' % (self.timesheet.user, self.timesheet.start_date)
class Meta:
unique_together = ('timesheet', 'project', 'labor',)
ordering = ['timesheet', 'project','labor']
And my FORMS look like this.
class TimesheetForm(forms.ModelForm):
class Meta:
model = Timesheet
fields = ['id', 'user', 'start_date']
widgets = {
'user' : forms.HiddenInput(),
'id' : forms.HiddenInput(),
'start_date' : forms.HiddenInput(),
}
class TimesheetRowInlineForm(forms.ModelForm):
class Meta:
model = TimesheetRow
exclude =['timesheet']
widgets = {
'id' : forms.HiddenInput(),
'project' : forms.Select(attrs={'class' : 'form-control'}),
'labor' : forms.Select(attrs={'class' : 'form-control'}),
'sunday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'monday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'tuesday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'wednesday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'thursday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'friday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'saturday' : forms.NumberInput(attrs={'class' : 'form-control'}),
}
TimesheetRowInlineFormSet = forms.inlineformset_factory(
Timesheet,
TimesheetRow,
form=TimesheetRowInlineForm,
extra=1,
exclude = ['id'],
can_delete=True,
can_order=False)
This gives me a fine form and everything works fine through the views but I cannot work out how to limit the Projects dropdown on the TimesheetRowInlineForm to those users in staff.
For completeness, this is the VIEW
class TimesheetView (LoginRequiredMixin, UpdateView):
model = Timesheet
form_class = TimesheetForm
success_url = '/'
def get_start_date(self, *args, **kwargs):
try:
start_date = self.kwargs['start_date']
except:
today = datetime.date.today()
start_date = today - datetime.timedelta(7+ ((today.weekday()+1)%7) )
return start_date
def get_object(self, *args, **kwargs):
obj, created = Timesheet.objects.get_or_create(user=self.request.user, start_date=self.get_start_date())
return obj
def get_context_data(self, **kwargs):
data = super(TimesheetView, self).get_context_data(**kwargs)
if self.request.POST:
data['timesheetrows'] = TimesheetRowInlineFormSet(self.request.POST, instance=self.get_object())
else:
data['timesheetrows'] = TimesheetRowInlineFormSet(instance=self.get_object())
return data
def get_initial(self):
return { 'user': self.request.user,
'start_date' : self.get_start_date() }
def form_valid(self, form):
context = self.get_context_data()
timesheetrows = context['timesheetrows']
with transaction.atomic():
self.object = form.save()
if timesheetrows.is_valid():
timesheetrows.instance = self.object
timesheetrows.save()
return super(TimesheetView, self).form_valid(form)
EDIT
I've worked out how to do this within admin, namely:
class TimesheetRowAdmin(admin.ModelAdmin):
def get_model_perms(self, request):
"""
Return empty perms dict thus hiding the model from admin index.
"""
return {}
admin.site.register(TimesheetRow, TimesheetRowAdmin)
class TimesheetRowInline(admin.TabularInline):
model = TimesheetRow
can_delete = True
extra = 1
def formfield_for_foreignkey(self, db_field, request=None,**kwargs):
field = super(TimesheetRowInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
if db_field.name == 'project':
if request.user is not None:
field.queryset = field.queryset.filter(staff=request._obj_.user)
if not field.queryset:
field.queryset = field.queryset.all()
else:
field.queryset = field.queryset.none()
return field
class TimesheetAdmin(admin.ModelAdmin):
list_display = ['user', 'start_date']
ordering = ['user','start_date']
inlines = [TimesheetRowInline]
def get_form(self, request, obj=None, **kwargs):
request._obj_ = obj
return super().get_form(request, obj, **kwargs)
admin.site.register(Timesheet, TimesheetAdmin)
I still need to reflect that for a non-staff user.
Having solved it in Admin above. This is how I solved it in my view. I effectively dynamically create the form within my view.
class TimesheetView (LoginRequiredMixin, UpdateView):
model = Timesheet
form_class = TimesheetForm
success_url = '/'
def create_inline_form(self):
class DynamicTimesheetRowInlineForm (forms.ModelForm):
project = forms.ModelChoiceField(queryset=Project.objects.filter(staff=self.request.user),
widget=forms.Select(attrs={'class' : 'form-control'}))
class Meta:
model = TimesheetRow
exclude =['timesheet']
widgets = {
'id' : forms.HiddenInput(),
#'project' : forms.Select(attrs={'class' : 'form-control'}),
'labor' : forms.Select(attrs={'class' : 'form-control'}),
'sunday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'monday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'tuesday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'wednesday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'thursday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'friday' : forms.NumberInput(attrs={'class' : 'form-control'}),
'saturday' : forms.NumberInput(attrs={'class' : 'form-control'}),
}
return DynamicTimesheetRowInlineForm
def get_start_date(self, *args, **kwargs):
try:
start_date = self.kwargs['start_date']
except:
today = datetime.date.today()
start_date = today - datetime.timedelta( ((today.weekday()+1)%7) )
return start_date
def get_object(self, *args, **kwargs):
obj, created = Timesheet.objects.get_or_create(user=self.request.user, start_date=self.get_start_date())
return obj
def get_context_data(self, **kwargs):
data = super(TimesheetView, self).get_context_data(**kwargs)
DynamicTimesheetRowInlineFormSet = forms.inlineformset_factory(
Timesheet,
TimesheetRow,
form=self.create_inline_form(),
extra=1,
exclude = ['id'],
can_delete=True,
can_order=False)
data['timesheetrows'] = DynamicTimesheetRowInlineFormSet(self.request.POST or None,
instance=self.get_object())
return data
def get_initial(self):
return {'user': self.request.user,
'start_date' : self.get_start_date() }
def form_valid(self, form):
context = self.get_context_data()
timesheetrows = context['timesheetrows']
print (timesheetrows.errors)
with transaction.atomic():
self.object = form.save()
if timesheetrows.is_valid():
timesheetrows.instance = self.object
timesheetrows.save()
return super(TimesheetView, self).form_valid(form)