def bill_edit(request, id, template_name='membership/entity_edit.html'): bill = get_object_or_404(Bill, id=id) class Form(ModelForm): class Meta: model = Bill exclude = ('billingcycle', 'reminder_count') before = bill.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': form = Form(request.POST, instance=bill) if form.is_valid(): form.save() after = bill.__dict__ log_change(bill, request.user, before, after) messages.success(request, unicode(_("Changes to bill %s saved.") % bill)) return redirect('bill_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to bill %s not saved.") % bill)) else: form = Form(instance=bill) logentries = bake_log_entries(bill.logs.all()) return render_to_response(template_name, {'form': form, 'bill': bill, 'logentries': logentries}, context_instance=RequestContext(request))
def contact_edit(request, id, template_name='membership/entity_edit.html'): contact = get_object_or_404(Contact, id=id) # XXX: I hate this. Wasn't there a shortcut for creating a form from instance? class Form(ModelForm): class Meta: model = Contact before = contact.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': if not request.user.has_perm('membership.manage_members'): messages.error(request, unicode(_("You are not authorized to modify memberships."))) return redirect('contact_edit', id) form = Form(request.POST, instance=contact) if form.is_valid(): form.save() after = contact.__dict__ log_change(contact, request.user, before, after) messages.success(request, unicode(_("Changes to contact %s saved.") % contact)) return redirect('contact_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to contact %s not saved.") % contact)) else: form = Form(instance=contact) message = "" logentries = bake_log_entries(contact.logs.all()) return render_to_response(template_name, {'form': form, 'contact': contact, 'logentries': logentries}, context_instance=RequestContext(request))
def delete_membership(self, user): assert user is not None me = Membership.objects.select_for_update().filter(pk=self.pk)[0] if me.status == STATUS_DELETED: raise MembershipAlreadyStatus("Membership already deleted") elif me.status == STATUS_NEW: # must be imported here due to cyclic imports from services.models import Service logger.info("Deleting services of the membership application %s." % repr(self)) for service in Service.objects.filter(owner=self): service.delete() logger.info("Deleting aliases of the membership application %s." % repr(self)) for alias in self.alias_set.all(): alias.delete() else: logger.info("Not deleting services of membership %s." % repr(self)) logger.info("Expiring aliases of membership %s." % repr(self)) for alias in self.alias_set.all(): alias.expire() contacts = [ self.person, self.billing_contact, self.tech_contact, self.organization ] self._change_status(new_status=STATUS_DELETED) for contact in contacts: if contact is not None: contact.delete_if_no_references(user) log_change(self, user, change_message="Deleted")
def delete_membership(self, user): assert user is not None me = Membership.objects.select_for_update().filter(pk=self.pk)[0] if me.status == STATUS_DELETED: raise MembershipAlreadyStatus("Membership already deleted") elif me.status == STATUS_NEW: # must be imported here due to cyclic imports from services.models import Service logger.info("Deleting services of the membership application %s." % repr(self)) for service in Service.objects.filter(owner=self): service.delete() logger.info("Deleting aliases of the membership application %s." % repr(self)) for alias in self.alias_set.all(): alias.delete() else: logger.info("Not deleting services of membership %s." % repr(self)) logger.info("Expiring aliases of membership %s." % repr(self)) for alias in self.alias_set.all(): alias.expire() contacts = [self.person, self.billing_contact, self.tech_contact, self.organization] self._change_status(new_status=STATUS_DELETED) for contact in contacts: if contact is not None: contact.delete_if_no_references(user) log_change(self, user, change_message="Deleted")
def bill_edit(request, id, template_name='membership/entity_edit.html'): bill = get_object_or_404(Bill, id=id) class Form(ModelForm): class Meta: model = Bill exclude = ('billingcycle', 'reminder_count') before = bill.__dict__.copy( ) # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': form = Form(request.POST, instance=bill) if form.is_valid(): form.save() after = bill.__dict__ log_change(bill, request.user, before, after) messages.success(request, unicode(_("Changes to bill %s saved.") % bill)) return redirect( 'bill_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to bill %s not saved.") % bill)) else: form = Form(instance=bill) logentries = bake_log_entries(bill.logs.all()) return render_to_response(template_name, { 'form': form, 'bill': bill, 'logentries': logentries }, context_instance=RequestContext(request))
def delete_membership(self, user): if self.status == 'D': raise MembershipOperationError("A deleted membership can't be deleted.") elif self.status == 'N': # must be imported here due to cyclic imports from services.models import Service logger.info("Deleting services of the membership application %s." % repr(self)) for service in Service.objects.filter(owner=self): service.delete() logger.info("Deleting aliases of the membership application %s." % repr(self)) for alias in self.alias_set.all(): alias.delete() else: logger.info("Not deleting services of membership %s." % repr(self)) logger.info("Expiring aliases of membership %s." % repr(self)) for alias in self.alias_set.all(): alias.expire() self.status = 'D' contacts = [self.person, self.billing_contact, self.tech_contact, self.organization] self.person = None self.billing_contact = None self.tech_contact = None self.organization = None self.save() for contact in contacts: if contact != None: contact.delete_if_no_references(user) log_change(self, user, change_message="Deleted")
def membership_convert_to_organization(request, id, template_name='membership/membership_convert_to_organization.html'): membership = get_object_or_404(Membership, id=id) class ConfirmForm(Form): confirm = BooleanField(label=_('To confirm conversion, you must check this box:'), required=True) if request.method == 'POST': form = ConfirmForm(request.POST) if form.is_valid(): f = form.cleaned_data membership.type = 'O' contact = membership.person membership.person = None membership.organization = contact membership.save() log_change(membership, request.user, change_message="Converted to an organization") messages.success(request, unicode(_('Member %s successfully converted to an organization.') % membership)) logger.info("User %s converted member %s to an organization." % (request.user.username, membership)) return redirect('membership_edit', membership.id) else: form = ConfirmForm() return render_to_response(template_name, {'form': form, 'membership': membership }, context_instance=RequestContext(request))
def cancel_dissociation_request(self, user): assert user is not None if not self.approved: raise MembershipOperationError( "Can't cancel dissociation request unless approved as member") self._change_status(new_status=STATUS_APPROVED) log_change(self, user, change_message="Dissociation request state reverted")
def preapprove(self, user): assert user is not None self._change_status(new_status=STATUS_PREAPPROVED) log_change(self, user, change_message="Preapproved") ret_items = send_preapprove_email.send_robust(self.__class__, instance=self, user=user) for item in ret_items: sender, error = item if error is not None: raise error logger.info("Membership {membership} preapproved.".format(membership=self))
def detach_from_cycle(self, user=None): if not self.billingcycle: return cycle = self.billingcycle logger.info("Payment %s detached from cycle %s." % (repr(self), repr(cycle))) self.billingcycle = None self.save() if user: log_change(self, user, change_message="Detached from billing cycle") cycle.update_is_paid()
def send_duplicate_payment_notice(self, user, **kwargs): if not user: raise Exception('send_duplicate_payment_notice user objects as parameter') billingcycle = BillingCycle.objects.get(reference_number=self.reference_number) if billingcycle.sum > 0: ret_items = send_duplicate_payment_notice.send_robust(self.__class__, instance=self, user=user, billingcycle=billingcycle) for item in ret_items: sender, error = item if error != None: logger.error("%s" % traceback.format_exc()) raise error log_change(self, user, change_message="Duplicate payment notice sent")
def approve(self, user): if self.status != 'P': raise MembershipOperationError("A membership from other state than preapproved can't be approved.") if user == None: msg = "Membership.approve() needs user object as a parameter" logger.critical("%s" % traceback.format_exc()) logger.critical(msg) raise MembershipOperationError(msg) self.status = 'A' self.approved = datetime.now() self.save() log_change(self, user, change_message="Approved")
def attach_to_cycle(self, cycle, user=None): if self.billingcycle: raise PaymentAttachedError("Payment %s already attached to BillingCycle %s." % (repr(self), repr(cycle))) self.billingcycle = cycle self.ignore = False self.save() logger.info("Payment %s attached to member %s cycle %s." % (repr(self), cycle.membership.id, repr(cycle))) if user: log_change(self, user, change_message="Attached to billing cycle") cycle.update_is_paid(user=user)
def billingcycle_edit(request, id, template_name='membership/entity_edit.html'): cycle = get_object_or_404(BillingCycle, id=id) class Form(ModelForm): is_paid_forced = False class Meta: model = BillingCycle exclude = ('membership', 'start', 'end', 'sum', 'reference_number') def disable_fields(self): self.fields['is_paid'].required = False if cycle.amount_paid() >= cycle.sum and cycle.is_paid: self.fields['is_paid'].widget.attrs['disabled'] = 'disabled' self.is_paid_forced = True def clean_is_paid(self): if self.is_paid_forced: return cycle.is_paid else: return self.cleaned_data['is_paid'] before = cycle.__dict__.copy( ) # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': form = Form(request.POST, instance=cycle) form.disable_fields() if form.is_valid(): form.save() after = cycle.__dict__ log_change(cycle, request.user, before, after) messages.success( request, unicode(_("Changes to billing cycle %s saved.") % cycle)) return redirect( 'billingcycle_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to bill %s not saved.") % cycle)) else: form = Form(instance=cycle) form.disable_fields() logentries = bake_log_entries(cycle.logs.all()) return render_to_response(template_name, { 'form': form, 'cycle': cycle, 'logentries': logentries }, context_instance=RequestContext(request))
def cancel_dissociation_request(self, user): if self.status != 'S': raise MembershipOperationError("A membership has to be in dissociation requested state for the state to be canceled.") if user == None: msg = "Membership.cancel_dissociation_request() needs user object as a parameter" logger.critical("%s" % traceback.format_exc()) logger.critical(msg) raise MembershipOperationError(msg) self.status = 'A' self.dissociation_requested = None self.save() log_change(self, user, change_message="Dissociation request state reverted")
def dissociate(self, user): if self.status not in ('A', 'S'): raise MembershipOperationError("A membership from other state than dissociation requested or approved can't be dissociated.") if user == None: msg = "Membership.dissociate() needs user object as a parameter" logger.critical("%s" % traceback.format_exc()) logger.critical(msg) raise MembershipOperationError(msg) self.status = 'I' self.dissociated = datetime.now() self.save() log_change(self, user, change_message="Dissociated")
def attach_to_cycle(self, cycle, user=None): if self.billingcycle: raise PaymentAttachedError( "Payment %s already attached to BillingCycle %s." % (repr(self), repr(cycle))) self.billingcycle = cycle self.ignore = False self.save() logger.info("Payment %s attached to member %s cycle %s." % (repr(self), cycle.membership.id, repr(cycle))) if user: log_change(self, user, change_message="Attached to billing cycle") cycle.update_is_paid(user=user)
def preapprove(self, user): assert user is not None self._change_status(new_status=STATUS_PREAPPROVED) log_change(self, user, change_message="Preapproved") ret_items = send_preapprove_email.send_robust(self.__class__, instance=self, user=user) for item in ret_items: sender, error = item if error is not None: raise error logger.info( "Membership {membership} preapproved.".format(membership=self))
def update_is_paid(self, user=None): was_paid = self.is_paid total_paid = self.amount_paid() if not was_paid and total_paid >= self.sum: self.is_paid = True self.save() logger.info("BillingCycle %s marked as paid, total paid: %.2f." % (repr(self), total_paid)) elif was_paid and total_paid < self.sum: self.is_paid = False self.save() logger.info("BillingCycle %s marked as unpaid, total paid: %.2f." % (repr(self), total_paid)) if user: log_change(self, user, change_message="Marked as paid")
def update_is_paid(self, user=None): was_paid = self.is_paid total_paid = self.amount_paid() if not was_paid and total_paid >= self.sum: self.is_paid = True self.save() logger.info("BillingCycle %s marked as paid, total paid: %.2f." % ( repr(self), total_paid)) elif was_paid and total_paid < self.sum: self.is_paid = False self.save() logger.info("BillingCycle %s marked as unpaid, total paid: %.2f." % ( repr(self), total_paid)) if user: log_change(self, user, change_message="Marked as paid")
def membership_edit(request, id, template_name='membership/membership_edit.html'): membership = get_object_or_404(Membership, id=id) class Form(ModelForm): class Meta: model = Membership exclude = ('person', 'billing_contact', 'tech_contact', 'organization') def clean_status(self): return membership.status def clean_approved(self): return membership.approved def disable_fields(self): self.fields['status'].required = False self.fields['status'].widget.attrs['disabled'] = 'disabled' self.fields['approved'].required = False self.fields['approved'].widget.attrs['disabled'] = 'disabled' if request.method == 'POST': if not request.user.has_perm('membership.manage_members'): return HttpResponseForbidden(_("Permission manage required")) form = Form(request.POST, instance=membership) before = membership.__dict__.copy() form.disable_fields() if form.is_valid(): form.save() after = membership.__dict__ log_change(membership, request.user, before, after) return redirect( 'membership_edit', id) # form stays as POST otherwise if someone refreshes else: form = Form(instance=membership) form.disable_fields() # Pretty print log entries for template logentries = bake_log_entries(membership.logs.all()) return render_to_response(template_name, { 'form': form, 'membership': membership, 'logentries': logentries }, context_instance=RequestContext(request))
def preapprove(self, user): if self.status != 'N': raise MembershipOperationError("A membership from other state than new can't be preapproved.") if user == None: msg = "Membership.preapprove() needs user object as a parameter" logger.critical("%s" % traceback.format_exc()) logger.critical(msg) raise MembershipOperationError(msg) self.status = 'P' self.save() log_change(self, user, change_message="Preapproved") ret_items = send_preapprove_email.send_robust(self.__class__, instance=self, user=user) for item in ret_items: sender, error = item if error != None: raise error logger.info("Membership %s preapproved." % self)
def contact_edit(request, id, template_name='membership/entity_edit.html'): contact = get_object_or_404(Contact, id=id) # XXX: I hate this. Wasn't there a shortcut for creating a form from instance? class Form(ModelForm): class Meta: model = Contact before = contact.__dict__.copy( ) # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': if not request.user.has_perm('membership.manage_members'): messages.error( request, unicode(_("You are not authorized to modify memberships."))) return redirect('contact_edit', id) form = Form(request.POST, instance=contact) if form.is_valid(): form.save() after = contact.__dict__ log_change(contact, request.user, before, after) messages.success( request, unicode(_("Changes to contact %s saved.") % contact)) return redirect( 'contact_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error( request, unicode(_("Changes to contact %s not saved.") % contact)) else: form = Form(instance=contact) message = "" logentries = bake_log_entries(contact.logs.all()) return render_to_response(template_name, { 'form': form, 'contact': contact, 'logentries': logentries }, context_instance=RequestContext(request))
def send_duplicate_payment_notice(self, user, **kwargs): if not user: raise Exception( 'send_duplicate_payment_notice user objects as parameter') billingcycle = BillingCycle.objects.get( reference_number=self.reference_number) if billingcycle.sum > 0: ret_items = send_duplicate_payment_notice.send_robust( self.__class__, instance=self, user=user, billingcycle=billingcycle) for item in ret_items: sender, error = item if error != None: logger.error("%s" % traceback.format_exc()) raise error log_change(self, user, change_message="Duplicate payment notice sent")
def billingcycle_edit(request, id, template_name='membership/entity_edit.html'): cycle = get_object_or_404(BillingCycle, id=id) class Form(ModelForm): is_paid_forced = False class Meta: model = BillingCycle exclude = ('membership', 'start', 'end', 'sum', 'reference_number') def disable_fields(self): self.fields['is_paid'].required = False if cycle.amount_paid() >= cycle.sum and cycle.is_paid: self.fields['is_paid'].widget.attrs['disabled'] = 'disabled' self.is_paid_forced = True def clean_is_paid(self): if self.is_paid_forced: return cycle.is_paid else: return self.cleaned_data['is_paid'] before = cycle.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here if request.method == 'POST': form = Form(request.POST, instance=cycle) form.disable_fields() if form.is_valid(): form.save() after = cycle.__dict__ log_change(cycle, request.user, before, after) messages.success(request, unicode(_("Changes to billing cycle %s saved.") % cycle)) return redirect('billingcycle_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to bill %s not saved.") % cycle)) else: form = Form(instance=cycle) form.disable_fields() logentries = bake_log_entries(cycle.logs.all()) return render_to_response(template_name, {'form': form, 'cycle': cycle, 'logentries': logentries}, context_instance=RequestContext(request))
def membership_convert_to_organization( request, id, template_name='membership/membership_convert_to_organization.html'): membership = get_object_or_404(Membership, id=id) class ConfirmForm(Form): confirm = BooleanField( label=_('To confirm conversion, you must check this box:'), required=True) if request.method == 'POST': form = ConfirmForm(request.POST) if form.is_valid(): f = form.cleaned_data membership.type = 'O' contact = membership.person membership.person = None membership.organization = contact membership.save() log_change(membership, request.user, change_message="Converted to an organization") messages.success( request, unicode( _('Member %s successfully converted to an organization.') % membership)) logger.info("User %s converted member %s to an organization." % (request.user.username, membership)) return redirect('membership_edit', membership.id) else: form = ConfirmForm() return render_to_response(template_name, { 'form': form, 'membership': membership }, context_instance=RequestContext(request))
def membership_edit(request, id, template_name='membership/membership_edit.html'): membership = get_object_or_404(Membership, id=id) class Form(ModelForm): class Meta: model = Membership exclude = ('person', 'billing_contact', 'tech_contact', 'organization') def clean_status(self): return membership.status def clean_approved(self): return membership.approved def disable_fields(self): self.fields['status'].required = False self.fields['status'].widget.attrs['disabled'] = 'disabled' self.fields['approved'].required = False self.fields['approved'].widget.attrs['disabled'] = 'disabled' if request.method == 'POST': if not request.user.has_perm('membership.manage_members'): return HttpResponseForbidden(_("Permission manage required")) form = Form(request.POST, instance=membership) before = membership.__dict__.copy() form.disable_fields() if form.is_valid(): form.save() after = membership.__dict__ log_change(membership, request.user, before, after) return redirect('membership_edit', id) # form stays as POST otherwise if someone refreshes else: form = Form(instance=membership) form.disable_fields() # Pretty print log entries for template logentries = bake_log_entries(membership.logs.all()) return render_to_response(template_name, {'form': form, 'membership': membership, 'logentries': logentries}, context_instance=RequestContext(request))
def billingcycle_connect_payment( request, id, template_name='membership/billingcycle_connect_payment.html'): billingcycle = get_object_or_404(BillingCycle, id=id) class SpeciallyLabeledModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return u"%s, %s, %s, %s" % (obj.payer_name, obj.reference_number, obj.amount, obj.payment_day) class PaymentForm(Form): qs = Payment.objects.filter(billingcycle__exact=None, ignore=False).order_by("payer_name") payment = SpeciallyLabeledModelChoiceField( queryset=qs, empty_label=_("None chosen"), required=True) if request.method == 'POST': form = PaymentForm(request.POST) if form.is_valid(): f = form.cleaned_data payment = f['payment'] before = payment.__dict__.copy() oldcycle = payment.billingcycle if oldcycle: oldcycle_before = oldcycle.__dict__.copy() payment.detach_from_cycle() oldcycle_after = oldcycle.__dict__.copy() log_change(oldcycle, request.user, oldcycle_before, oldcycle_after) newcycle = billingcycle newcycle_before = newcycle.__dict__.copy() payment.attach_to_cycle(newcycle) newcycle_after = newcycle.__dict__.copy() after = payment.__dict__ log_change(payment, request.user, before, after) log_change(newcycle, request.user, newcycle_before, newcycle_after) messages.success( request, unicode(_("Changes to payment %s saved.") % payment)) return redirect('billingcycle_edit', id) else: messages.error( request, unicode( _("Changes to BillingCycle %s not saved.") % billingcycle)) else: form = PaymentForm() logentries = bake_log_entries(billingcycle.logs.all()) return render_to_response(template_name, { 'form': form, 'cycle': billingcycle, 'logentries': logentries }, context_instance=RequestContext(request))
def billingcycle_connect_payment(request, id, template_name='membership/billingcycle_connect_payment.html'): billingcycle = get_object_or_404(BillingCycle, id=id) class SpeciallyLabeledModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return u"%s, %s, %s, %s" % (obj.payer_name, obj.reference_number, obj.amount, obj.payment_day) class PaymentForm(Form): qs = Payment.objects.filter(billingcycle__exact=None, ignore=False).order_by("payer_name") payment = SpeciallyLabeledModelChoiceField(queryset=qs, empty_label=_("None chosen"), required=True) if request.method == 'POST': form = PaymentForm(request.POST) if form.is_valid(): f = form.cleaned_data payment = f['payment'] before = payment.__dict__.copy() oldcycle = payment.billingcycle if oldcycle: oldcycle_before = oldcycle.__dict__.copy() payment.detach_from_cycle() oldcycle_after = oldcycle.__dict__.copy() log_change(oldcycle, request.user, oldcycle_before, oldcycle_after) newcycle = billingcycle newcycle_before = newcycle.__dict__.copy() payment.attach_to_cycle(newcycle) newcycle_after = newcycle.__dict__.copy() after = payment.__dict__ log_change(payment, request.user, before, after) log_change(newcycle, request.user, newcycle_before, newcycle_after) messages.success(request, unicode(_("Changes to payment %s saved.") % payment)) return redirect('billingcycle_edit', id) else: messages.error(request, unicode(_("Changes to BillingCycle %s not saved.") % billingcycle)) else: form = PaymentForm() logentries = bake_log_entries(billingcycle.logs.all()) return render_to_response(template_name, {'form': form, 'cycle': billingcycle, 'logentries': logentries}, context_instance=RequestContext(request))
def request_dissociation(self, user): assert user is not None self._change_status(new_status='S') log_change(self, user, change_message="Dissociation requested")
def dissociate(self, user): assert user is not None self._change_status(new_status=STATUS_DISASSOCIATED) log_change(self, user, change_message="Dissociated")
def cancel_dissociation_request(self, user): assert user is not None if not self.approved: raise MembershipOperationError("Can't cancel dissociation request unless approved as member") self._change_status(new_status=STATUS_APPROVED) log_change(self, user, change_message="Dissociation request state reverted")
def approve(self, user): assert user is not None self._change_status(new_status=STATUS_APPROVED) log_change(self, user, change_message="Approved")
def payment_edit(request, id, template_name='membership/entity_edit.html'): payment = get_object_or_404(Payment, id=id) class SpeciallyLabeledModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return u"%s, %s" % (obj.membership, unicode(obj)) class Form(ModelForm): class Meta: model = Payment #exclude = ('billingcycle') billingcycle = CharField(widget=HiddenInput(), required=False) #billingcycle = CharField(required=False) message = CharField(widget=Textarea(attrs={'rows': 5, 'cols': 60})) def disable_fields(self): if payment.billingcycle: self.fields['ignore'].required = False self.fields['ignore'].widget.attrs['disabled'] = 'disabled' self.fields['billingcycle'].required = False self.fields['billingcycle'].widget.attrs['disabled'] = 'disabled' self.fields['reference_number'].required = False self.fields['reference_number'].widget.attrs['disabled'] = 'disabled' self.fields['message'].required = False self.fields['message'].widget.attrs['disabled'] = 'disabled' self.fields['transaction_id'].required = False self.fields['transaction_id'].widget.attrs['disabled'] = 'disabled' self.fields['payment_day'].required = False self.fields['payment_day'].widget.attrs['disabled'] = 'disabled' self.fields['amount'].required = False self.fields['amount'].widget.attrs['disabled'] = 'disabled' self.fields['type'].required = False self.fields['type'].widget.attrs['disabled'] = 'disabled' self.fields['payer_name'].required = False self.fields['payer_name'].widget.attrs['disabled'] = 'disabled' self.fields['comment'].required = False def clean_ignore(self): if payment.billingcycle: return False else: return self.cleaned_data['ignore'] def clean_billingcycle(self): return payment.billingcycle def clean_reference_number(self): return payment.reference_number def clean_message(self): return payment.message def clean_transaction_id(self): return payment.transaction_id def clean_payment_day(self): return payment.payment_day def clean_amount(self): return payment.amount def clean_type(self): return payment.type def clean_payer_name(self): return payment.payer_name before = payment.__dict__.copy() # Otherwise save() (or valid?) will change the dict, needs to be here oldcycle = payment.billingcycle if request.method == 'POST': form = Form(request.POST, instance=payment) form.disable_fields() if form.is_valid(): form.save() newcycle = payment.billingcycle if oldcycle != newcycle: if oldcycle: oldcycle.update_is_paid() if newcycle: newcycle.update_is_paid() after = payment.__dict__ log_change(payment, request.user, before, after) messages.success(request, unicode(_("Changes to payment %s saved.") % payment)) return redirect('payment_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error(request, unicode(_("Changes to payment %s not saved.") % payment)) return redirect('payment_edit', id) # form clears otherwise, this is a borderline acceptable hack else: form = Form(instance=payment) form.disable_fields() logentries = bake_log_entries(payment.logs.all()) return render_to_response(template_name, {'form': form, 'payment': payment, 'logentries': logentries}, context_instance=RequestContext(request))
def payment_edit(request, id, template_name='membership/entity_edit.html'): payment = get_object_or_404(Payment, id=id) class SpeciallyLabeledModelChoiceField(ModelChoiceField): def label_from_instance(self, obj): return u"%s, %s" % (obj.membership, unicode(obj)) class Form(ModelForm): class Meta: model = Payment #exclude = ('billingcycle') billingcycle = CharField(widget=HiddenInput(), required=False) #billingcycle = CharField(required=False) message = CharField(widget=Textarea(attrs={'rows': 5, 'cols': 60})) def disable_fields(self): if payment.billingcycle: self.fields['ignore'].required = False self.fields['ignore'].widget.attrs['disabled'] = 'disabled' self.fields['billingcycle'].required = False self.fields['billingcycle'].widget.attrs['disabled'] = 'disabled' self.fields['reference_number'].required = False self.fields['reference_number'].widget.attrs[ 'disabled'] = 'disabled' self.fields['message'].required = False self.fields['message'].widget.attrs['disabled'] = 'disabled' self.fields['transaction_id'].required = False self.fields['transaction_id'].widget.attrs['disabled'] = 'disabled' self.fields['payment_day'].required = False self.fields['payment_day'].widget.attrs['disabled'] = 'disabled' self.fields['amount'].required = False self.fields['amount'].widget.attrs['disabled'] = 'disabled' self.fields['type'].required = False self.fields['type'].widget.attrs['disabled'] = 'disabled' self.fields['payer_name'].required = False self.fields['payer_name'].widget.attrs['disabled'] = 'disabled' self.fields['comment'].required = False def clean_ignore(self): if payment.billingcycle: return False else: return self.cleaned_data['ignore'] def clean_billingcycle(self): return payment.billingcycle def clean_reference_number(self): return payment.reference_number def clean_message(self): return payment.message def clean_transaction_id(self): return payment.transaction_id def clean_payment_day(self): return payment.payment_day def clean_amount(self): return payment.amount def clean_type(self): return payment.type def clean_payer_name(self): return payment.payer_name before = payment.__dict__.copy( ) # Otherwise save() (or valid?) will change the dict, needs to be here oldcycle = payment.billingcycle if request.method == 'POST': form = Form(request.POST, instance=payment) form.disable_fields() if form.is_valid(): form.save() newcycle = payment.billingcycle if oldcycle != newcycle: if oldcycle: oldcycle.update_is_paid() if newcycle: newcycle.update_is_paid() after = payment.__dict__ log_change(payment, request.user, before, after) messages.success( request, unicode(_("Changes to payment %s saved.") % payment)) return redirect( 'payment_edit', id) # form stays as POST otherwise if someone refreshes else: messages.error( request, unicode(_("Changes to payment %s not saved.") % payment)) return redirect( 'payment_edit', id ) # form clears otherwise, this is a borderline acceptable hack else: form = Form(instance=payment) form.disable_fields() logentries = bake_log_entries(payment.logs.all()) return render_to_response(template_name, { 'form': form, 'payment': payment, 'logentries': logentries }, context_instance=RequestContext(request))