This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Django override of ModelForm init methods

By: a guest on Mar 27th, 2013  |  syntax: Python  |  size: 1.44 KB  |  views: 42  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. # views.py
  2. @login_required
  3. def create_payment(request):
  4.     user = request.user
  5.     if not user.vehicle_set.all():
  6.         return redirect("vehicle_auth_send")  
  7.     else:
  8.         if request.method == 'POST':
  9.             form = PaymentForm(user=user, data=request.POST)
  10.             if form.is_valid():
  11.                 form.save()
  12.                 return redirect('home')
  13.         else:
  14.             form = PaymentForm(user=user)
  15.        
  16.         return render(request, 'forms.html', {'form': form})
  17.  
  18. #forms.py
  19. class PaymentForm(forms.ModelForm):
  20.    
  21.     class Meta:
  22.         model = Payment
  23.    
  24.     def __init__(self, user=None, *args, **kwargs):
  25.         super(PaymentForm, self).__init__(*args, **kwargs)
  26.        
  27.         # pass in user and override queryset for ModelChoiceField
  28.         self._user = user                
  29.         vehicles = self._user.vehicle_set.all().prefetch_related('ticket_set')
  30.         ticket_list= []
  31.         for i in vehicles:
  32.             for j in i.ticket_set.all():
  33.                 if j.sum_outstanding():
  34.                     ticket_list.append(j.pk)
  35.         self.ticket_queryset = Ticket.objects.filter(pk__in=ticket_list)        
  36.         self.fields['ticket'].queryset = self.ticket_queryset
  37.        
  38.     def save(self, commit=True):
  39.         instance = super(PaymentForm, self).save(commit=False)
  40.         instance.user = self._user
  41.         if commit:
  42.             instance.save()
  43.         return instance
clone this paste RAW Paste Data