0

First, I am quite new with django... I am trying to add a dropdown menu of available distinct Users (by name and coming from my db "dynamically") in a form.

I am using django 2.2.6.

# MyCustomForm
class DetailedReportForm(forms.Form):
    AVAILABLE_USERS = MyUserModel.objects.order_by().values_list('name').distinct()
    selected_date = forms.DateTimeField(input_formats=['%d/%m/%Y'], required=True, widget=DateInput())
    selected_user = forms.CharField(label="Select a user", widget=forms.Select(choices=AVAILABLE_USERS))

# MyModel
class MyUserModel(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)
    name = models.CharField(db_column='Name', unique=True, max_length=90)
    ...
    def __str__(self):
        return str(self.name)

The issue I am facing is my queryset is not working (not sure why) as it is giving me the following: not enough values to unpack (expected 2, got 1)

I tried to google it but still not very clear to me what this error message means.

Can someone please explain what this django error means so I can fix it and include the dropdown list in my form?

1 Answer 1

3

The problem is choices argument expecting list of tuples like this: [(1, "one"), (2, "two")]. First element in tuple actual value to store in DB, second is human readable representation.

But actually in your case you can just use ModelChoiceField instead:

class DetailedReportForm(forms.Form):
    AVAILABLE_USERS = MyUserModel.objects.order_by().values_list('name').distinct()
    selected_date = forms.DateTimeField(input_formats=['%d/%m/%Y'], required=True, widget=DateInput())
    selected_user = forms.ModelChoiceField(label="Select a user", queryset=MyUserModel.objects.order_by().distinct("name"))

Otherwise list of available options wiil not updated dynamically, since code inside form class running only once on django starting.

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

2 Comments

Thank you for your answer, for some reason. I cannot distinct on field when the backend is MySQL. So I had to replace your dictinct("name") to be distinct() here
@WilliamW yep, unfortunatelly distinct by field only work on PostgreSQL now.

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.