简体   繁体   中英

django forms with ModelChoiceField

After researching for days I'm still confused with creating a form involving 4 tables which are all connected via ForiegnKey. I'm not even sure if I'm using the right approach.

Should I use forms.Form or ModelForm? What I'm looking for I'm sure is common but all of my attempts are in vain. It seems like I'm making this more complicated than it should be since all 4 tables are related.

To the Point: To create a workorder, pick a Building, then pick a Unit within that Building, then pick a caller from Tenant(s) within that Unit. Then gather all data in view and save WorkOrder.

Using Django 1.6

# models.py
class Building(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=200)
    ...

def __unicode__(self):
    return self.name


class Unit(models.Model):
    name = models.ForeignKey(Building)
    unit = models.CharField(max_length=30)
    ...

    def __unicode__(self):
        return self.unit

class Tenant(models.Model):
    unit = models.ForeignKey(Unit)
    name = models.ForeignKey(Building)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    ...

    def __unicode__(self):
        return u'%s %s' % (self.first_name, self.last_name)


class WorkOrder(models.Model):
    name = models.ForeignKey(Building)
    unit = models.ForeignKey(Unit)
    ordernum = models.AutoField(primary_key=True)
    ...

    def __unicode__(self):
        return self.unit

forms.py

# forms.py

class WorkOrderForm(forms.Form):
    building_choice = forms.ModelChoiceField(queryset=Building.objects.all(),
                                             empty_label='Pick a building',
                                             )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['building_choice'].label = 'Building'


    unit_choice = forms.ModelChoiceField(queryset=Unit.objects.(????),
                                         empty_label='Pick a unit',
                                         )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['unit_choice'].label = 'Unit'

    caller_choice = forms.ModelChoiceField(queryset=Tenant.objects.(????),
                                       empty_label='Who called',
                                       )

    def __init__(self, *args, **kwargs):
        super(WorkOrderForm, self).__init__(*args, **kwargs)
        self.fields['caller_choice'].label = 'Tenant'

views.py (incomplete)

#views.py
def create(request):
    if request.method == 'POST':
        form = WorkOrderForm(request.POST)
        if form.is_valid():
            workorder = WorkOrder(name=form.cleaned_data['name'],
                                 unit=form.cleaned_data['unit'],
                                 call_date=form.cleaned_data['call_date'],
                                 caller=form.cleaned_data['caller'],
                                 problem_desc=form.cleaned_data['problem_desc'])
            workorder.save()

            return HttpResponseRedirect('/workorder/')
    else:
        form = WorkOrderForm()
    return render(request, 'workorder_form.html', {'form': form})

If someone could let me know the correct way to go about this I'd be forever grateful.

It's been a while since I posted this question but I found a django package django-clever-selects that met my needs. The docs and example project were well commented. Thanks to all that helped mr earlier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM