def house_bill_add(request, pk): house = get_object_or_404(House, pk=pk) if request.user.id != house.user.id: raise Http404 if request.method == 'POST': formset = BillFormset(request.POST, request.FILES) if formset.is_valid(): for form in formset: if not check_format(form.cleaned_data['date']): return render(request, 'houses/house_bill_add.html', {'error': 'You have entered the date in an incorrect format! Use yyyy-mm-dd', 'house': house, 'formset': formset}) bill = Bill() bill.user = request.user bill.type = form.cleaned_data['type'] bill.amount = form.cleaned_data['amount'] bill.date = form.cleaned_data['date'] if isinstance(form.cleaned_data['date'], datetime.date): parsed_date = form.cleaned_data['date'] else: parsed_date = datetime.datetime.strptime(form.cleaned_data['date'], '%Y-%m-%d') month = parsed_date.month year = parsed_date.year existing_billset = BillSet.objects.filter(house=house).filter(year=year).filter(month=month) if existing_billset.count() == 0: new_billset = BillSet() new_billset.house = house new_billset.month = month new_billset.year = year new_billset.save() bill.set = new_billset else: bill.set = existing_billset.first() bill.save() if form.cleaned_data['file'] is not None: billfile = BillFile() billfile.user = request.user billfile.file = form.cleaned_data['file'] billfile.bill = bill billfile.save() send_bill_email(house, bill) return redirect('house_detail', house.pk) else: return render(request, 'houses/house_bill_add.html', {'error': 'You have entered invalid bill data', 'house': house, 'formset': formset}) else: formset = BillFormset() return render(request, 'houses/house_bill_add.html', {'house': house, 'formset': formset})
def test_Bill_creation(self): billset = BillSet() billset.month = 10 billset.year = 2019 billset.house = self.house billset.save() pre_count = Bill.objects.count() bill = Bill() bill.set = billset bill.user = self.user bill.type = 'ELEC' bill.date = '2019-11-04' bill.amount = 199.99 bill.save() post_count = Bill.objects.count() self.assertGreater(post_count, pre_count)