My models of Employee registration is as follow.
class EmployeeRegistration(models.Model):
#Departmental Details
EmpId = models.IntegerField(verbose_name='EmpId')
EmpImage = models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
EmpSafetyCard= models.ImageField(default='default.png',upload_to='profile_pic/%Y/%m/%d')
Site = models.ForeignKey(Site,on_delete=models.CASCADE,max_length=150,verbose_name='Site')
Department = models.ForeignKey(Department,on_delete=models.CASCADE,max_length=150,verbose_name='Department')
Category = models.ForeignKey(Category,on_delete=models.CASCADE,max_length=150,verbose_name='Category')
Designation = models.ForeignKey(Designation,on_delete=models.CASCADE,max_length=150,verbose_name='Designation')
PfApplicable = models.BooleanField(default = True,verbose_name='Pf Applicable')
EsiApplicable = models.BooleanField(default = True,verbose_name='Esic Applicable')
Uan = models.PositiveIntegerField(null = True,verbose_name='Uan')
Esic = models.PositiveIntegerField(null = True,verbose_name='Esic')
AttendenceAward = models.BooleanField(default = True)
AttendenceAllowance = models.BooleanField(default = True)
ProfesionalTax = models.BooleanField(default = False)
Name = models.CharField(max_length=150,verbose_name='Name')
Father = models.CharField(max_length=150,verbose_name='Father')
Dob = models.DateField()
Male = models.BooleanField(default = True)
Female = models.BooleanField(default = False)
MaritalStatus = models.BooleanField(default = True)
Address = models.CharField(max_length=200,verbose_name='Address')
Aadhar = models.PositiveIntegerField(null=True)
pan = models.CharField(max_length=10)
choices = [('Working','WORKING'),('NotWorking','NOT WORKING'),('Leave','Leave')]
Status = models.CharField(choices=choices,blank = False,max_length=10,verbose_name='Status')
Doj = models.DateField(default = date.today)
Doe = models.DateField(blank = True,verbose_name = 'Doe',null = True)
def __str__(self):
return f'{self.Name}({self.EmpId})'
def save(self):
super().save()
empimg = Image.open(self.EmpImage.path)
empsafetycard = Image.open(self.EmpSafetyCard.path)
if empimg.height>300 or empimg.width>300:
output_size = (300,300)
empimg.thumbnail(output_size)
empimg.save(self.EmpImage.path)
if empsafetycard.height>300 or empsafetycard.width>300:
output_size = (300,300)
empsafetycard.thumbnail(output_size)
empsafetycard.save(self.EmpSafetyCard.path)
This is my newEmployeeForm code
class newEmployeeForm(forms.ModelForm):
class Meta:
model = EmployeeRegistration
fields = '__all__'
labels ={
'EmpImage':'Upload Employee Image',
'EmpSafetyCard':'Upload Safety Card',
'Dob':'Date of Birth',
'Doj':'Date of Joining',
'Doe':'Date of Exit'
}
widgets = {
'Dob':DateInput(),
'Doj': DateInput(),
'Doe': DateInput()
}
This is my View for regitering new employee
def registration_view(request,id=0):
form = newEmployeeForm()
record = RecordsId.objects.all()
empid = 0
for data in record:
empid = data.EmpId
emp_id = empid+1
if(empid!=0 or empid==0):
get_emp = RecordsId.objects.get(EmpId=empid)
EmployeeId={"EmpId":emp_id}
print(request.POST)
if(request.method == 'POST'):
if(id==0):
form = newEmployeeForm(request.POST or None,request.FILES,initial=EmployeeId)
print("id= 0")
else:
print(id)
employee = EmployeeRegistration.objects.get(pk=id)
form = newEmployeeForm(instance=employee)
if form.is_valid():
print("valid")
get_emp.EmpId = emp_id
get_emp.save()
form.save()
print("saved")
form = newEmployeeForm(initial=EmployeeId)
messages.success(request,'Successfully Updated')
return redirect('emplist')
else:
print("Form is not valid")
context = {
'form':form,
"contact":"active"
}
return render(request,"employee/NewEmployee.html",context)
I have a view for registering new employee at the same time in the same view i am updating the records of employee. But when i am trying to update the existing record. It is creating new record. i don't know why this is happening. Please help me.
Related
I made a multiplechoicefield form (to ask what category user wants to select), but i can't get the answer back...it always renders "None".
I added some 'print' in the code to be sure that it was the problem and it is.
I don't understand why.
forms.py:
class Category(forms.ModelForm):
class Meta:
model = Auctions
fields = ("category",)
#fields = ('category',)
#widgets = {'category' : forms.RadioSelect()}
catform = forms.MultipleChoiceField(choices=fields, widget=forms.CheckboxSelectMultiple())
models.py
'''
class Auctions(models.Model):
Category = [('FASHION', 'Fashion'),('TOYS','Toys'),('ELECTRONICS','Electronics'),('HOME','Home')]
ID_auction = models.AutoField(primary_key = True)
title = models.CharField(max_length = 80)
description = models.TextField()
startingbid = models.IntegerField()
image = models.URLField(blank = True)
category = models.CharField(max_length = 80, choices = Category)
author_id = models.ForeignKey(User,on_delete = models.CASCADE, related_name = "auteur")
highest_bid = models.IntegerField("Bid", blank = True, null = True)
buyer = models.ForeignKey(User, on_delete = models.CASCADE, related_name = "acheteur")
active = models.BooleanField(default=True)
'''
views.py
'''
def filter_cat(request):
if request.method == "POST":
form = Category(request.POST)
print(form)
if form.is_valid():
cat = form.cleaned_data.get("catform")
print(cat)
auctions = Auctions.objects.filter(category = cat)
return render(request, "auctions/index.html",{
'active_listing' : auctions, 'cat' : cat
})
else :
form = Category()
return render(request, "auctions/filter_cat.html",{'form' : form})
'''
when I select FASHION for example i get this on the terminal :
for print(form):
Category:
---------
Fashion
Toys
Electronics
Home
for print(cat):
None
I am creating an api which returns weather data of particular city for n number of days given.(api definition: weatherdata/city_name/ndays/).I have problem sorting out data for ndays.
I sorted out the city name using simple icontains. similarly I want to sort out for ndays. previous ndays data needs to be shown. example: suppose today is 2019-08-29, on providing ndays to be 6, weather data of particular city has to be provided from 2019-08-24 to 2019-08-26.
views.py
class weatherDetail(APIView):
def get_object(self, city_name, ndays):
try:
x = weatherdata.objects.filter(city_name__icontains=city_name)
now = datetime.datetime.now()
fromdate = now - timedelta(days=ndays)
y =
return x
except Snippet.DoesNotExist:
raise Http404
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_object(city_name,ndays)
serializer = weatherdataserializer(snippet,many =True)
return Response(serializer.data)
models.py
class weatherdata(models.Model):
city_name = models.CharField(max_length = 80)
city_id = models.IntegerField(default=0)
latitude = models.FloatField(null=True , blank=True)
longitude = models.FloatField(null=True , blank=True)
dt_txt = models.DateTimeField()
temp = models.FloatField(null = False)
temp_min = models.FloatField(null = False)
temp_max = models.FloatField(null = False)
pressure = models.FloatField(null = False)
sea_level = models.FloatField(null = False)
grnd_level = models.FloatField(null = False)
humidity = models.FloatField(null = False)
main = models.CharField(max_length=200)
description = models.CharField(max_length=30)
clouds = models.IntegerField(null=False)
wind_speed = models.FloatField(null = False)
wind_degree = models.FloatField(null = False)
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('weatherdata/', views.weatherList.as_view()),
path('weatherdata/<str:city_name>/<int:ndays>/', views.weatherDetail.as_view()),
]
I want 'y' to be filtering objects based on dates. previous ndays data has to be returned. get_object should return the objects which falls under both x and y what needs to be modified in my code.
You have to change your query like below
class weatherDetail(APIView):
def get_queryset(self, city_name, ndays):
x = weatherdata.objects.filter(city_name__icontains=city_name)
today_date = timezone.now().date()
fromdate = today_date - timedelta(days=ndays)
x = x.filter(dt_txt__gte=fromdate).order_by('dt_txt')
return x
def get(self,*args,**kwargs):
city_name = kwargs['city_name']
snippet = self.get_queryset(city_name, ndays)
serializer = weatherdataserializer(snippet, many=True)
return Response(serializer.data)
I made a create view that should be able to save an object and then redirect bit form some reasons the form is not valid and it's not saving the object. If anybody knows the answer then please write the whole answer with code.
My create view
class Submit_Property(generic.CreateView):
model = models.Property
form_class = forms.Property_Form
template_name = 'profile_details/submit-property.html'
Here's the model for This
class Property(models.Model):
title = models.CharField(max_length = 210,default = 'None')
STATUS_CHOICES = (
('RENT','Rent'),
('SALE','Sale'),
)
status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'Rent')
price = models.IntegerField()
area = models.CharField(max_length = 210,default = 'None')
ROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('MORE','More'),
)
rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = '1')
BATHROOM_CHOICES = (
('1','1'),
('2','2'),
('3','3'),
('4','4'),
)
bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = '2')
address = models.CharField(max_length = 210,default = 'None')
state = models.CharField(max_length = 210,default = 'None')
code = models.CharField(max_length = 210,default = 'None')
images = models.ImageField(upload_to = 'images',)
info = models.TextField(max_length = 1000,default = 'None')
parking = models.BooleanField(default = False,verbose_name = 'Parking')
air = models.BooleanField(default = False)
swimming = models.BooleanField(default = False)
laundry = models.BooleanField(default = False)
dealer_name = models.CharField(max_length = 210,default = 'None')
dealer_email = models.EmailField(max_length = 210,default = 'abc#gmail.com')
dealer_number = models.CharField(max_length = 210,default = 'Not mentioned')
user = models.ForeignKey(User,related_name = 'user',default = True)
timpestamp = models.DateTimeField(auto_now_add = True)
category = models.ManyToManyField(Category,related_name = 'categories',default = None)
def get_absolute_url(self,*args,**kwargs):
return reverse('profile_details:property')
def __str__(self):
return self.title
It's right here in form valid
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super().form_valid(form)
But don't write like this
def form_valid(self, form):
form.instance.user = self.request.user
form.save()
return super(models.Property, self).form_valid(form)
class Hardware(models.Model):
date = models.PositiveSmallIntegerField()
node = models.ForeignKey('Node', on_delete=models.CASCADE,null = True)
slot = models.PositiveSmallIntegerField(null = True)
server = models.CharField(max_length=20,null = True)
server_state = models.CharField(max_length=20,null = True)
adapter = models.CharField(max_length=20,null = True)
adapter_state = models.CharField(max_length=20,null = True)
class Meta:
unique_together = ('date', 'node','slot')
order_with_respect_to = 'node'
def __str__(self):
return self.node.name +" " + self.server
class Node(models.Model):
name = models.CharField(max_length = 40, primary_key = True)
def __str__(self):
return self.name
def inventory_by_node(request):
day = (arrow.now().day) - 1
nodes = Node.objects.prefetch_related("hardware_set").all()
return render(request, 'automation/inventory_by_node.html',{'nodes':nodes})
I need to filter hardware_set based on date which is equal to currrent day. I tried
nodes = Node.objects.prefetch_related(Prefetch("hardwares", quesryset=Hardware.objects.filter(date=day)).all()
but It didn't works says no Pretch is defined
Try this:
prefetch = Prefetch("hardware_set", queryset=Hardware.objects.filter(date=day))
nodes = Node.objects.prefetch_related(prefetch).all()
My Models are look like .....
Student(models.Model):
name = models.CharField(max_length = 60, blank = False)
r_no = models.CharField(max_length = 60, blank = False)
created_date = models.DateTimeField(null = False, blank = False, default = datetime.datetime.now())
StudentPotential(models.Model):
aka_name = models.CharField(max_length = 60, blank = True)
-----
-----
StudentCorrespondence(models.Model):
student = models.ForeignKey('Student', related_name = "Student_FK")
student_p = models.ForeignKey('Student', related_name = "Student_FK")
emailed_date = models.DateTimeField(null = True, blank = True)
phoned_date = models.DateTimeField(null = True, blank = True)
My Form in form.py
class StudentPotentialForm (forms.ModelForm):
class Meta:
model = StudentPotential
class StudentCorrespondenceForm(forms.ModelForm):
class Meta:
model = StudentCorrespondence
exclude = ('student', 'student_p')
Finally My view.py
def add_student_company_potential(request, student_id):
from cdradmin.forms import StudentPotentialForm, StudentCorrespondenceForm
if request.method == 'POST':
### HOW TO SAVE THE two from for the student have its it 'student_id' ####
else:
StudentPotentialForm = StudentPotentialForm()
StudentCorrespondenceForm = StudentCorrespondenceForm()
context = {'StudentCorrespondenceForm':StudentCorrespondenceForm, "StudentPotentialForm":StudentPotentialForm}
return render_to_response('cdradmin/studentform.html', context, context_instance = RequestContext(request))
Once the data is post to the view, How can i able to save this data for the student has his/her id is 'student_id'
You can try this
if request.method == 'POST':
spf = StudentPotentialForm(request.POST)
if spf.is_valid():
osp = spf.save()
else :
#raise error
student = Student.objects.get(id=student_id)
scf = StudentCorrespondenceForm(request.POST)
if scf.is_valid():
osc = scf.save(commit=False)
osc.student = student
osc.student_p = osp
osc.save()
else:
# raise error.