205π
you can filter the waypoints by passing the user to the form init
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(
choices=[(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
)
from your view while initiating the form pass the user
form = waypointForm(user)
in case of model form
class waypointForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ModelChoiceField(
queryset=Waypoint.objects.filter(user=user)
)
class Meta:
model = Waypoint
13π
Thereβs built-in solution for your problem: ModelChoiceField.
Generally, itβs always worth trying to use ModelForm
when you need to create/change database objects. Works in 95% of the cases and itβs much cleaner than creating your own implementation.
- [Django]-What is pip install -q -e . for in this Travis-CI build tutorial?
- [Django]-Running a specific test case in Django when your app has a tests directory
- [Django]-How to manage local vs production settings in Django?
8π
the problem is when you do
def __init__(self, user, *args, **kwargs):
super(waypointForm, self).__init__(*args, **kwargs)
self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])
in a update request, the previous value will lost!
- [Django]-Programmatically saving image to Django ImageField
- [Django]-Where's my JSON data in my incoming Django request?
- [Django]-How to move a model between two Django apps (Django 1.7)
4π
How about passing the rider instance to the form while initializing it?
class WaypointForm(forms.Form):
def __init__(self, rider, *args, **kwargs):
super(joinTripForm, self).__init__(*args, **kwargs)
qs = rider.Waypoint_set.all()
self.fields['waypoints'] = forms.ChoiceField(choices=[(o.id, str(o)) for o in qs])
# In view:
rider = request.user
form = WaypointForm(rider)
- [Django]-How to set and get cookies in Django?
- [Django]-Django-celery: No result backend configured
- [Django]-How to customize activate_url on django-allauth?
4π
You can declare the field as a first-class attribute of your form and just set choices dynamically in __init__
:
class WaypointForm(forms.Form):
waypoints = forms.ChoiceField(choices=[])
def __init__(self, user, *args, **kwargs):
super().__init__(*args, **kwargs)
waypoint_choices = [(o.id, str(o)) for o in Waypoint.objects.filter(user=user)]
self.fields['waypoints'].choices = waypoint_choices
This approach also works with a ModelChoiceField.
This approach is superior if you are using a ModelForm, and want to override choices of an autogenerated field.
- [Django]-Django Cannot set values on a ManyToManyField which specifies an intermediary model. Use Manager instead
- [Django]-Specifying limit and offset in Django QuerySet wont work
- [Django]-Django admin default filter
3π
If you need a dynamic choice field in django admin; This works for django >=2.1.
class CarAdminForm(forms.ModelForm):
class Meta:
model = Car
def __init__(self, *args, **kwargs):
super(CarForm, self).__init__(*args, **kwargs)
# Now you can make it dynamic.
choices = (
('audi', 'Audi'),
('tesla', 'Tesla')
)
self.fields.get('car_field').choices = choices
car_field = forms.ChoiceField(choices=[])
@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
form = CarAdminForm
Hope this helps.
- [Django]-Django character set with MySQL weirdness
- [Django]-Django database query: How to get object by id?
- [Django]-How to create an object for a Django model with a many to many field?
2π
Underneath working solution with normal choice field.
my problem was that each user have their own CUSTOM choicefield options based on few conditions.
class SupportForm(BaseForm):
affiliated = ChoiceField(required=False, label='Fieldname', choices=[], widget=Select(attrs={'onchange': 'sysAdminCheck();'}))
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
grid_id = get_user_from_request(self.request)
for l in get_all_choices().filter(user=user_id):
admin = 'y' if l in self.core else 'n'
choice = (('%s_%s' % (l.name, admin)), ('%s' % l.name))
self.affiliated_choices.append(choice)
super(SupportForm, self).__init__(*args, **kwargs)
self.fields['affiliated'].choices = self.affiliated_choice
- [Django]-Django-Bower + Foundation 5 + SASS, How to configure?
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
- [Django]-Django staticfiles not found on Heroku (with whitenoise)
1π
As pointed by Breedly and Liang, Ashokβs solution will prevent you from getting the select value when posting the form.
One slightly different, but still imperfect, way to solve that would be:
class waypointForm(forms.Form):
def __init__(self, user, *args, **kwargs):
self.base_fields['waypoints'].choices = self._do_the_choicy_thing()
super(waypointForm, self).__init__(*args, **kwargs)
This could cause some concurrence problems, though.
- [Django]-Referencing multiple submit buttons in django
- [Django]-How to convert JSON data into a Python object?
- [Django]-How to test "render to template" functions in django? (TDD)