0

I have a form in my site to get a report about some "collective payment". It has 3 main field: Value, date of payment and who paid.

The field "who paid" is a table containing the name of all users and a checkbox.

Currently I'm looping over all users, adding their full names to the table with a single checkbox. But I don't know how to get this data in my form associating it with each user name (just the text).

How can I get multiple BooleanFields in my form ? Is there a way of associate each BooleanField with an user's name?

model.py

from django.db import models

#created_date attibute needs it
from django.utils import timezone
# This Model is a super class "Financial Transaction"
class GroupTransaction(models.Model):
    name = models.CharField(max_length=257, default='')
    who_paid = models.CharField(max_length=257, default='')
    value = models.DecimalField(max_digits=6, decimal_places=2)
    justification = models.CharField(max_length=257, default='')

    created_date = models.DateTimeField(default=timezone.now)
    date = models.CharField(max_length=257, default='')
    receipt = models.FileField(upload_to='comprovantes', blank=True, null=True)
    its_type = models.CharField(max_length=257, default='')

    def __str__(self):
        #INCOMPLETOreturn "%s fez a movimentação financeira de %d para %s no dia " % (self.name, self.restaurant)
        return "%s - %s" % (self.name , self.who_paid)

view.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from deposit.forms import DepositForm,MonthlyDepositForm
from django.contrib.auth.models import User

# Create your views here.
@login_required
def deposito(request):
    if request.method == 'POST':
        form = DepositForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            HttpResponseRedirect('/historico/')
        else:
            print (str(form.errors.as_data()))
    else:
        form = DepositForm()
        groupForm = MonthlyDepositForm()
    return render(request, 'shell/app_shell.html', {
        'is_deposit' : True,
        'title' : 'Deposit',
        'transaction' : form,
        'groupTransaction' : groupForm,
        'users': User.objects.all()
    })

form.py

class MonthlyDepositForm(forms.ModelForm):
    value = forms.DecimalField()
    date = forms.CharField(widget=forms.TextInput(attrs={
        'class':'datepicker picker__input',
        'readonly':'',
        'tabindex':'54',
        'aria-haspopup':'True',
        'aria-expanded':'false',
        'aria-readonly':'false',
        'aria-owns':'birthdate_root'
        }))
    who_paid = forms.BooleanField()

    its_type = forms.CharField(widget=forms.HiddenInput(attrs={'readonly':True}),
                                initial='Deposito Mensal')


    class Meta:
        model = GroupTransaction
        fields = ('value', 'date','who_paid','its_type')

template.html:

<form class="col s12">

  {% csrf_token %}
  {{ groupTransaction.its_type }}
  <div class="row"></div>

  <!-- Nome do evento -->
  <div class="row">
    <div class="input-field col s6">
      <!-- <input id="nome_evento" type="number" value="10" step="any" min="0.05" max="400" class="validate" required> -->
      {{ groupTransaction.value }}
      <label for="nome_evento">Value</label>
    </div>
    <div class="input-field col s6">
      <!-- <input type="text" class="datepicker picker__input" readonly="" tabindex="54" aria-haspopup="true" aria-expanded="false" aria-readonly="false" aria-owns="birthdate_root" required> -->
      {{ groupTransaction.date }}
      <label for="data-mensal" data-error="Data inválida">Date</label>
    </div>
  </div>




  <!-- Petianos que irão para o evento -->
  <table class="striped">
    <thead>
      <!-- Cabeçalho tabela -->
      <tr>
        <th>Who Paid</th>
        <th>
          <div class="switch">
            <b class="center-align">Default</b>
            <label>
              <input type="checkbox">
              <span class="lever"></span>
            </label>
          </div>
        </th>
      </tr>
      <!-- ============= -->
    </thead>

    <tbody>
      {% for user in users %}
      <tr>
        <td>{{ user.get_full_name }}</td>
        <td>
          <div class="switch">
            <label>
              <!-- <input type="checkbox"> -->
              {{ groupTransaction.who_paid }}
              <span class="lever"></span>
            </label>
          </div>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>

  <div class="row"></div>
  <div class="row"></div>

  <!-- Botão de registrar saque (submit) -->

  <div class="row">
      <button class="btn waves-effect waves-light col s6 m3 offset-s6 offset-m9 blue" type="submit" name="action">Submit
        <i class="material-icons right">send</i>
      </button>
  </div>
</form>

How the form is:

How the form is

1 Answer 1

1

You need to make who_paid a ManyToManyField(User). Then in the form you can set its widget like this:

class Meta:
    model = GroupTransaction
    fields = ('value', 'date','who_paid','its_type')
    widgets = {
        'who_paid': forms.CheckboxSelectMultiple(),
    }

That will give you the right structure. Then you can render it manually if you want to change the display.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.