How do I filter ForeignKey choices in a Django ModelForm?
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.
So, provide a QuerySet to the field's queryset
attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.
form.rate.queryset = Rate.objects.filter(company_id=the_company.id)
If you take the default ModelForm object, form.fields["rate"].queryset = ...
This is done explicitly in the view. No hacking around.
Need help with Django ModelForm: How to filter ForeignKey/ManyToManyField?
I would edit Daniel Rosemans reply and vote it winner, but since i cant edit it i will post the correct answer here:
class IncomingForm(ModelForm):
class Meta:
model = Incoming
def __init__(self, *args, **kwargs):
super(IncomingForm, self).__init__(*args, **kwargs)
if self.instance:
self.fields['cat_id'].queryset = Category.objects.filter(
parents__exact=self.instance.id)
The difference is self.fields['cat_id'] (correct) vs self.fields['parents'] (wrong, we both made the same mistake)
Django ModelForm foreign key filtering
First of all, remove those print
statements after the return
statement as they will never get executed after a value is returned by the method. Secondly, add form_class
attribute to your view class like this:
class SongCreateView(CreateView):
template_name = 'music/song_create.html'
success_url = '/songs/'
form_class = SongCreateForm
Then in get_form
method:
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return form_class(user=self.request.user, **self.get_form_kwargs())
Then override form_valid
method to associate the logged in user with the Song
instance like this:
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return redirect(self.get_success_url())
Import redirect
from django.shortcuts
at the top. Hope it helps!
How can I filter users as a choice in a foreign key django forms?
You check the condition with:
class Projects(models.Model):
# …
project_manager = models.ForeignKey(
CustomUser,
on_delete=models.CASCADE,
limit_choices_to={'is_project_manager': True}
)
# …
you can also explicitly exclude is_inventory_admin=True
and is_client=True
(in case a CustomUser
can be two or three at the same time), with:
class Projects(models.Model):
# …
project_manager = models.ForeignKey(
CustomUser,
on_delete=models.CASCADE,
limit_choices_to={'is_project_manager': True, 'is_inventory_admin': False, 'is_client': False}
)
# …
Note: It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly. For more information you can see the referencing theUser
model section of the documentation.
Note: normally a Django model is given a singular name, so
Project
instead of.Projects
Django: How to filter ForeignKey choices (e.g. with request.user) with ModelFormSet and FormWizard?
You simply want your foreign key queryset for the attendee attribute on your Model to be a filtered one on your ModelForm. You are on the right lines here:
self.fields['attendee'].queryset = Person.objects.filter(owner=user)
This is assuming an attribute 'owner' exists on the Person class.
This won't work however, as where or what is your user arg? One solution is to curry the forms init method, as you mention, to include the correct user object:
form = staticmethod(curry(AttendeeForm, user=<the-user-obj>))
Now you pop your user arg from the kwargs in your init method:
user = kwargs.pop('user')
Now your filtered queryset will only display the Person you filtered for.
def __init__(self, user, *args, **kwargs): I tried this but I didn't get
it to work.
The line above won't work for a number of reasons, the primary being that it will never be called from anywhere, you are making a new function there, not overriding an existing one, which is what we are doing overring the init method.
Just some possibly helpful advice on design - You've got many threads here all providing many different ideas, complicating things a lot. Try to filter your problem to basic concepts. Here, it's a presentation of data issue, so think about starting in the Form, that's what it's there for. :-)
Queryset filtering on Foreignkey in Modelform
why my_user_form is not validated and saved. instead of modifying the queryset in the init i did it in the view itself using the statement
my_user_form.fields['created_by'] = forms.ModelChoiceField(User.objects.filter(username=request.user))
and this solves my problem. but i still don't know why it didn't work in the init method of the MyUsersForm?.
Related Topics
Unix Socket Credential Passing in Python
Why Aren't Python Nested Functions Called Closures
Run Linux Grep Command from Python Subprocess
Detect Specific Keypresses in Gui
Get Spotify Currently Playing Track
Which Is the Preferred Way to Concatenate a String in Python
Using Python Subprocess.Call() to Launch an Ncurses Process
Error Installing Uwsgi in Virtualenv
Convert Binary to Ascii and Vice Versa
How to Run Python Script in Cron
Python3 Flask Asyncio Subprocess in Route Hangs
Passing Variable from Python Script to Bash Script
Is There Something Wrong with This Python Code, Why Does It Run So Slow Compared to Ruby
How to Get the Pythonpath in Shell
Unicodedecodeerror, Invalid Continuation Byte
How to Install Writable Shared and User Specific Data Files with Setuptools
How Transform a Python Program .Py in an Executable Program in Ubuntu