0

I have been trying to create a select input from options based on a Model. I have tried several changes but the error persists. I hope someone can help.

The forms.py code.

transaction_type = forms.ChoiceField(choices=TRANSACTION_TYPE_CHOICES, widget=forms.RadioSelect(), required=True)
transaction_purpose = forms.ChoiceField(choices=TRANSACTION_PURPOSE_CHOICES, widget=forms.RadioSelect(), required=True)
transaction_payment_method = forms.ChoiceField(choices=TRANSACTION_PAYMENT_METHOD_CHOICES, widget=forms.RadioSelect(), required=True)
transaction_currency = forms.ChoiceField(choices=TRANSACTION_CURRENCY, widget=forms.RadioSelect(attrs={'checked':'checked'}), required=True)
transaction_description = forms.CharField(widget=forms.Textarea(), required=False)
transaction_after_balance = forms.IntegerField(required=False)
transaction_account = forms.ModelChoiceField(required=False, queryset=Accounts.objects.none(), empty_label="Select Account")

class Meta:
    model = Transactions
    fields = ('transaction_amount','transaction_type', 'transaction_title',
    'transaction_description','transaction_currency','transaction_account',
    'transaction_purpose', 'transaction_payment_method','transaction_after_balance')

views.py code

def get(self, request):
    employee_name = Employees.objects.get(user=request.user)
    form = TransactionForm()
    form.fields['transaction_account'].queryset = Accounts.objects.filter(user=request.user)
    print(form.fields['transaction_account'].queryset)

    args = {}
    args['transaction_form'] = form
    args['employee_search'] = employee_name
    return render(request,'finance/add_transaction.html', args)

def post(self, request):
    transaction_form = TransactionForm(request.POST)
    transaction_balance = Transactions.objects.filter(user=request.user).latest('transaction_created_at').transaction_after_balance
    print (transaction_form)
    if transaction_form.is_valid():
        form_obj = transaction_form.save(commit=False)
        if form_obj.transaction_type == "Credit":
            transaction_balance = transaction_balance - form_obj.transaction_amount
            form_obj.transaction_after_balance = transaction_balance

        else:
            print (transaction_balance, form_obj.transaction_amount)
            transaction_balance = transaction_balance + form_obj.transaction_amount
            form_obj.transaction_after_balance = transaction_balance
        form_obj.user= request.user
        form_obj.save()
        return render(request,'dashboard')

    return render(request,'Error')

html template code

<div class="col-lg-3">
        <label>
          Account:
        </label>
        <div class="">
          {% render_field transaction_form.transaction_account class="form-control m-select2" id="account_select" name="transaction_account" %}
        </div>
      </div>

Template is rendering ok. This is the rendered template showing options.

Rendered HTML Code:

    <select name="transaction_account" id="account_select" class="form-control m-select2 select2-hidden-accessible" data-select2-id="account_select" tabindex="-1" aria-hidden="true">
  <option value="" selected="" data-select2-id="2">Select Account</option>
  <option value="1" data-select2-id="13">MCB</option>
</select>

When I submit the form. The form does not validate. If remove validation and try to save form object directly. It raises an exception that "1" should be an instance of Account.

Please help as I cannot figure out what I am doing wrong here.

models.py code

class Transactions(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    transaction_created_at = models.DateTimeField(auto_now_add='True')
    transaction_amount = models.IntegerField()
    transaction_title = models.CharField(max_length=150, blank=True, null=True)
    transaction_type= models.CharField(max_length=10)
    transaction_description= models.CharField(max_length=1000)
    transaction_after_balance= models.IntegerField(blank=True, null=True)
    transaction_currency=models.CharField(max_length=20)
    transaction_account=models.ForeignKey(Accounts, on_delete=models.CASCADE, blank=True, null=True)
    transaction_purpose=models.CharField(max_length=300)
    transaction_payment_method = models.CharField(max_length=20)

I have added code for the models.py file.

Update

I have manually assigned the object based on id from select in views.py. Other ModelSelectFields are working fine.

  • can you show the model `Transactions`? – Lemayzeur Jul 20 '18 at 00:27
  • I have added the Transaction model. – Talha Masoud Jul 20 '18 at 14:12
  • Why is the form not validating? What errors are in `form.errors`. Does the primary key of `Accounts` object `MCB` equal to 1? Does the form validate with the same data if you use the shell? – CoffeeBasedLifeform Jul 20 '18 at 15:58
  • form.errors says select a valid choice for transaction_account. PK of Accounts object is equal to "1". I have not tried this in shell. I think it will validate because if I pass the object hardcoded it validates. Error is with the select returning wrong type of object. – Talha Masoud Jul 20 '18 at 18:03

0 Answers0