How to pass a request to ModelChoiceField using self.field_value in Django ModelForms

I could explain all this to you, but I think the code is better than the words, so β†’

class Skills(models.Model): skill = models.ForeignKey(ReferenceSkills) person = models.ForeignKey(User) class SkillForm(ModelForm): class Meta: model = Skills fields = ( 'person', 'skill') (???)skill = forms.ModelChoiceField(queryset= SkillsReference.objects.filter(person = self.person) 

I just guess how I can do this. But I hope you guys understand what I'm trying to do.

+9
source share
3 answers

You can update the structure of the form before creating an instance of the form, for example:

 class SkillForm(ModelForm): class Meta: model = Skills fields = ( 'person', 'skill') 

In your opinion:

 SkillForm.base_fields['skill'] = forms.ModelChoiceField(queryset= ...) form = SkillForm() 

You can override it anytime you want in your view, and you need to do this before creating an instance of the form with

 form = SkillForm() 
+10
source

Assuming you are using class-based views, you can pass a set of requests in the form of kwargs, and then replace it with the init method of the form:

 # views.py class SkillUpdateView(UpdateView): def get_form_kwargs(self, **kwargs): kwargs.update({ 'skill_qs': Skills.objects.filter(skill='medium') }) return super(self, SkillUpdateView).get_form_kwargs(**kwargs) # forms.py class SkillForm(forms.ModelForm): def __init__(self, *args, **kwargs): qs = kwargs.pop('skill_ks') super(self, SkillForm).__init__(*args, **kwargs) self.fields['skill'].queryset = qs 

But personally, I prefer this second approach. I get an instance of the form in the view and then replace the set of field requests before django wraps it in context:

 # views.py class SkillsUpdateView(UpdateView): form_class = SkillForm def get_form(self, form_class=None): form = super().get_form(form_class=self.form_class) form.fields['skill'].queryset = Skills.objects.filter(skill='medium') return form 
0
source

Your code looks almost normal. Try this skill:

 class SkillForm(ModelForm): skill = forms.ModelChoiceField(queryset= SkillsReference.objects.filter(person = self.person) class Meta: model = Skills fields = ( 'person', 'skill') 

The difference is that skill is a form field, should not be in a meta class

EDITED

The above solution is wrong, but this link describes how to achieve what you want: http://www.zoia.org/blog/2007/04/23/using-dynamic-choices-with-django-newforms-and-custom -widgets /

-1
source

Source: https://habr.com/ru/post/889202/


All Articles