[Answered ]-Django Form "'ForwardManyToOneDescriptor' object has no attribute 'all'"

1👍

Looking at your code, the error is raised because you’re specifying queryset=command_node.host_id in your form:

    host_id = forms.ModelChoiceField(
        required=True,
        queryset=command_node.host_id,
        widget=forms.Select(
            attrs={
                'class': 'form-control'
            },
        )
    )

Actually, command_node.host_id is a ForwardManyToOneDescriptor (this is the class assigned to fields that are marked as ForeignKey). In this case, what you want to supply as the queryset parameter is a set of objects that should belong to the model beacon which is the onea associated to host_id:

    host_id = forms.ModelChoiceField(
        required=True,
        queryset=beacon.objects.all(),
        widget=forms.Select(
            attrs={
                'class': 'form-control'
            },
        )
    )

This will display all beacon objects in your DB as options in a dropsdown in your form (the widget used is a Select). You could also display any queryset related to the beacon model. For example if you wanted to display only the beacon objects that have an internal IP equal to X.Y.Z.W you could sepecify queryset=beacon.objects.filter(internalIP="X.Y.Z.W").

Some things to note here:

  • Django already uses a ModelChoiceField when displaying the available options for fields that rely on a ForeignKey. You can check the associations Django makes between Model fields and Form fields here: https://docs.djangoproject.com/en/4.0/topics/forms/modelforms/#field-types. If you want all beacon objects to be able for selection in your form, your code could be simplified to:
class command_form(ModelForm):
    class Meta:
        model = command_node
        fields = (
            'host_id',
            'current_commands'
        )

        current_comamnds = forms.ChoiceField(
            required=True,
            attrs={
                'class': 'form-control'
            },
            
            choices=[
                ('Sleep', "Sleep"),
                ('Open SSH_Tunnel', 'Open SSH_Tunnel'),
                ('Close SSH_Tunnel', 'Close SSH_Tunnel'),
                ('Open TCP_Tunnel', 'Open TCP_Tunnel'),
                ('Close TCP_Tunnel', 'Close TCP_Tunnel'),
                ('Open Dynamic', 'Open Dynamic'),
                ('Close Dynamic', 'Close Dynamic'),
                ('Task', 'Task'),
            ])
👤mtzd

Leave a comment